1 | import { combine, dateAdd, hOP, isFunc, objectDefinedNotNull } from "@pnp/core";
|
2 | import { JSONParse } from "@pnp/queryable";
|
3 | import { extractWebUrl } from "../utils/extract-web-url.js";
|
4 | import { SPQueryable } from "../spqueryable.js";
|
5 | import { spPost } from "../operations.js";
|
6 | import { BatchNever } from "../batching.js";
|
7 | function clearExpired(digest) {
|
8 | const now = new Date();
|
9 | return !objectDefinedNotNull(digest) || (now > digest.expiration) ? null : digest;
|
10 | }
|
11 |
|
12 | const digests = new Map();
|
13 | export function RequestDigest(hook) {
|
14 | return (instance) => {
|
15 | instance.on.pre(async function (url, init, result) {
|
16 |
|
17 | this.on.auth(async (url, init) => {
|
18 |
|
19 | if (/get/i.test(init.method) || (init.headers && (hOP(init.headers, "X-RequestDigest") || hOP(init.headers, "Authorization") || hOP(init.headers, "X-PnPjs-NoDigest")))) {
|
20 | return [url, init];
|
21 | }
|
22 | const urlAsString = url.toString();
|
23 | const webUrl = extractWebUrl(urlAsString);
|
24 |
|
25 |
|
26 | let digest = clearExpired(digests.get(webUrl));
|
27 | if (!objectDefinedNotNull(digest) && isFunc(hook)) {
|
28 | digest = clearExpired(hook(urlAsString, init));
|
29 | }
|
30 | if (!objectDefinedNotNull(digest)) {
|
31 | digest = await spPost(SPQueryable([this, combine(webUrl, "_api/contextinfo")]).using(JSONParse(), BatchNever()), {
|
32 | headers: {
|
33 | "X-PnPjs-NoDigest": "1",
|
34 | },
|
35 | }).then(p => ({
|
36 | expiration: dateAdd(new Date(), "second", p.FormDigestTimeoutSeconds),
|
37 | value: p.FormDigestValue,
|
38 | }));
|
39 | }
|
40 | if (objectDefinedNotNull(digest)) {
|
41 |
|
42 | init.headers = {
|
43 | "X-RequestDigest": digest.value,
|
44 | ...init.headers,
|
45 | };
|
46 |
|
47 | digests.set(webUrl, digest);
|
48 | }
|
49 | return [url, init];
|
50 | });
|
51 | return [url, init, result];
|
52 | });
|
53 | return instance;
|
54 | };
|
55 | }
|
56 |
|
\ | No newline at end of file |