@kevisual/auth 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js ADDED
@@ -0,0 +1,3495 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+
12
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/buffer_utils.js
13
+ var encoder = new TextEncoder;
14
+ var decoder = new TextDecoder;
15
+ var MAX_INT32 = 2 ** 32;
16
+ function concat(...buffers) {
17
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
18
+ const buf = new Uint8Array(size);
19
+ let i = 0;
20
+ for (const buffer of buffers) {
21
+ buf.set(buffer, i);
22
+ i += buffer.length;
23
+ }
24
+ return buf;
25
+ }
26
+ function encode(string) {
27
+ const bytes = new Uint8Array(string.length);
28
+ for (let i = 0;i < string.length; i++) {
29
+ const code = string.charCodeAt(i);
30
+ if (code > 127) {
31
+ throw new TypeError("non-ASCII string encountered in encode()");
32
+ }
33
+ bytes[i] = code;
34
+ }
35
+ return bytes;
36
+ }
37
+
38
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/base64.js
39
+ function encodeBase64(input) {
40
+ if (Uint8Array.prototype.toBase64) {
41
+ return input.toBase64();
42
+ }
43
+ const CHUNK_SIZE = 32768;
44
+ const arr = [];
45
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
46
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
47
+ }
48
+ return btoa(arr.join(""));
49
+ }
50
+ function decodeBase64(encoded) {
51
+ if (Uint8Array.fromBase64) {
52
+ return Uint8Array.fromBase64(encoded);
53
+ }
54
+ const binary = atob(encoded);
55
+ const bytes = new Uint8Array(binary.length);
56
+ for (let i = 0;i < binary.length; i++) {
57
+ bytes[i] = binary.charCodeAt(i);
58
+ }
59
+ return bytes;
60
+ }
61
+
62
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/util/base64url.js
63
+ function decode(input) {
64
+ if (Uint8Array.fromBase64) {
65
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
66
+ alphabet: "base64url"
67
+ });
68
+ }
69
+ let encoded = input;
70
+ if (encoded instanceof Uint8Array) {
71
+ encoded = decoder.decode(encoded);
72
+ }
73
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
74
+ try {
75
+ return decodeBase64(encoded);
76
+ } catch {
77
+ throw new TypeError("The input to be decoded is not correctly encoded.");
78
+ }
79
+ }
80
+ function encode2(input) {
81
+ let unencoded = input;
82
+ if (typeof unencoded === "string") {
83
+ unencoded = encoder.encode(unencoded);
84
+ }
85
+ if (Uint8Array.prototype.toBase64) {
86
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
87
+ }
88
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
89
+ }
90
+
91
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/util/errors.js
92
+ var exports_errors = {};
93
+ __export(exports_errors, {
94
+ JWTInvalid: () => JWTInvalid,
95
+ JWTExpired: () => JWTExpired,
96
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
97
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
98
+ JWSInvalid: () => JWSInvalid,
99
+ JWKSTimeout: () => JWKSTimeout,
100
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
101
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
102
+ JWKSInvalid: () => JWKSInvalid,
103
+ JWKInvalid: () => JWKInvalid,
104
+ JWEInvalid: () => JWEInvalid,
105
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
106
+ JOSENotSupported: () => JOSENotSupported,
107
+ JOSEError: () => JOSEError,
108
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed
109
+ });
110
+
111
+ class JOSEError extends Error {
112
+ static code = "ERR_JOSE_GENERIC";
113
+ code = "ERR_JOSE_GENERIC";
114
+ constructor(message, options) {
115
+ super(message, options);
116
+ this.name = this.constructor.name;
117
+ Error.captureStackTrace?.(this, this.constructor);
118
+ }
119
+ }
120
+
121
+ class JWTClaimValidationFailed extends JOSEError {
122
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
123
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
124
+ claim;
125
+ reason;
126
+ payload;
127
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
128
+ super(message, { cause: { claim, reason, payload } });
129
+ this.claim = claim;
130
+ this.reason = reason;
131
+ this.payload = payload;
132
+ }
133
+ }
134
+
135
+ class JWTExpired extends JOSEError {
136
+ static code = "ERR_JWT_EXPIRED";
137
+ code = "ERR_JWT_EXPIRED";
138
+ claim;
139
+ reason;
140
+ payload;
141
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
142
+ super(message, { cause: { claim, reason, payload } });
143
+ this.claim = claim;
144
+ this.reason = reason;
145
+ this.payload = payload;
146
+ }
147
+ }
148
+
149
+ class JOSEAlgNotAllowed extends JOSEError {
150
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
151
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
152
+ }
153
+
154
+ class JOSENotSupported extends JOSEError {
155
+ static code = "ERR_JOSE_NOT_SUPPORTED";
156
+ code = "ERR_JOSE_NOT_SUPPORTED";
157
+ }
158
+
159
+ class JWEDecryptionFailed extends JOSEError {
160
+ static code = "ERR_JWE_DECRYPTION_FAILED";
161
+ code = "ERR_JWE_DECRYPTION_FAILED";
162
+ constructor(message = "decryption operation failed", options) {
163
+ super(message, options);
164
+ }
165
+ }
166
+
167
+ class JWEInvalid extends JOSEError {
168
+ static code = "ERR_JWE_INVALID";
169
+ code = "ERR_JWE_INVALID";
170
+ }
171
+
172
+ class JWSInvalid extends JOSEError {
173
+ static code = "ERR_JWS_INVALID";
174
+ code = "ERR_JWS_INVALID";
175
+ }
176
+
177
+ class JWTInvalid extends JOSEError {
178
+ static code = "ERR_JWT_INVALID";
179
+ code = "ERR_JWT_INVALID";
180
+ }
181
+
182
+ class JWKInvalid extends JOSEError {
183
+ static code = "ERR_JWK_INVALID";
184
+ code = "ERR_JWK_INVALID";
185
+ }
186
+
187
+ class JWKSInvalid extends JOSEError {
188
+ static code = "ERR_JWKS_INVALID";
189
+ code = "ERR_JWKS_INVALID";
190
+ }
191
+
192
+ class JWKSNoMatchingKey extends JOSEError {
193
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
194
+ code = "ERR_JWKS_NO_MATCHING_KEY";
195
+ constructor(message = "no applicable key found in the JSON Web Key Set", options) {
196
+ super(message, options);
197
+ }
198
+ }
199
+
200
+ class JWKSMultipleMatchingKeys extends JOSEError {
201
+ [Symbol.asyncIterator];
202
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
203
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
204
+ constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
205
+ super(message, options);
206
+ }
207
+ }
208
+
209
+ class JWKSTimeout extends JOSEError {
210
+ static code = "ERR_JWKS_TIMEOUT";
211
+ code = "ERR_JWKS_TIMEOUT";
212
+ constructor(message = "request timed out", options) {
213
+ super(message, options);
214
+ }
215
+ }
216
+
217
+ class JWSSignatureVerificationFailed extends JOSEError {
218
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
219
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
220
+ constructor(message = "signature verification failed", options) {
221
+ super(message, options);
222
+ }
223
+ }
224
+
225
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/crypto_key.js
226
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
227
+ var isAlgorithm = (algorithm, name) => algorithm.name === name;
228
+ function getHashLength(hash) {
229
+ return parseInt(hash.name.slice(4), 10);
230
+ }
231
+ function getNamedCurve(alg) {
232
+ switch (alg) {
233
+ case "ES256":
234
+ return "P-256";
235
+ case "ES384":
236
+ return "P-384";
237
+ case "ES512":
238
+ return "P-521";
239
+ default:
240
+ throw new Error("unreachable");
241
+ }
242
+ }
243
+ function checkUsage(key, usage) {
244
+ if (usage && !key.usages.includes(usage)) {
245
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
246
+ }
247
+ }
248
+ function checkSigCryptoKey(key, alg, usage) {
249
+ switch (alg) {
250
+ case "HS256":
251
+ case "HS384":
252
+ case "HS512": {
253
+ if (!isAlgorithm(key.algorithm, "HMAC"))
254
+ throw unusable("HMAC");
255
+ const expected = parseInt(alg.slice(2), 10);
256
+ const actual = getHashLength(key.algorithm.hash);
257
+ if (actual !== expected)
258
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
259
+ break;
260
+ }
261
+ case "RS256":
262
+ case "RS384":
263
+ case "RS512": {
264
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
265
+ throw unusable("RSASSA-PKCS1-v1_5");
266
+ const expected = parseInt(alg.slice(2), 10);
267
+ const actual = getHashLength(key.algorithm.hash);
268
+ if (actual !== expected)
269
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
270
+ break;
271
+ }
272
+ case "PS256":
273
+ case "PS384":
274
+ case "PS512": {
275
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
276
+ throw unusable("RSA-PSS");
277
+ const expected = parseInt(alg.slice(2), 10);
278
+ const actual = getHashLength(key.algorithm.hash);
279
+ if (actual !== expected)
280
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
281
+ break;
282
+ }
283
+ case "Ed25519":
284
+ case "EdDSA": {
285
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
286
+ throw unusable("Ed25519");
287
+ break;
288
+ }
289
+ case "ML-DSA-44":
290
+ case "ML-DSA-65":
291
+ case "ML-DSA-87": {
292
+ if (!isAlgorithm(key.algorithm, alg))
293
+ throw unusable(alg);
294
+ break;
295
+ }
296
+ case "ES256":
297
+ case "ES384":
298
+ case "ES512": {
299
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
300
+ throw unusable("ECDSA");
301
+ const expected = getNamedCurve(alg);
302
+ const actual = key.algorithm.namedCurve;
303
+ if (actual !== expected)
304
+ throw unusable(expected, "algorithm.namedCurve");
305
+ break;
306
+ }
307
+ default:
308
+ throw new TypeError("CryptoKey does not support this operation");
309
+ }
310
+ checkUsage(key, usage);
311
+ }
312
+
313
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/invalid_key_input.js
314
+ function message(msg, actual, ...types) {
315
+ types = types.filter(Boolean);
316
+ if (types.length > 2) {
317
+ const last = types.pop();
318
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
319
+ } else if (types.length === 2) {
320
+ msg += `one of type ${types[0]} or ${types[1]}.`;
321
+ } else {
322
+ msg += `of type ${types[0]}.`;
323
+ }
324
+ if (actual == null) {
325
+ msg += ` Received ${actual}`;
326
+ } else if (typeof actual === "function" && actual.name) {
327
+ msg += ` Received function ${actual.name}`;
328
+ } else if (typeof actual === "object" && actual != null) {
329
+ if (actual.constructor?.name) {
330
+ msg += ` Received an instance of ${actual.constructor.name}`;
331
+ }
332
+ }
333
+ return msg;
334
+ }
335
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
336
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
337
+
338
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/is_key_like.js
339
+ var isCryptoKey = (key) => {
340
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
341
+ return true;
342
+ try {
343
+ return key instanceof CryptoKey;
344
+ } catch {
345
+ return false;
346
+ }
347
+ };
348
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
349
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
350
+
351
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/is_disjoint.js
352
+ function isDisjoint(...headers) {
353
+ const sources = headers.filter(Boolean);
354
+ if (sources.length === 0 || sources.length === 1) {
355
+ return true;
356
+ }
357
+ let acc;
358
+ for (const header of sources) {
359
+ const parameters = Object.keys(header);
360
+ if (!acc || acc.size === 0) {
361
+ acc = new Set(parameters);
362
+ continue;
363
+ }
364
+ for (const parameter of parameters) {
365
+ if (acc.has(parameter)) {
366
+ return false;
367
+ }
368
+ acc.add(parameter);
369
+ }
370
+ }
371
+ return true;
372
+ }
373
+
374
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/is_object.js
375
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
376
+ function isObject(input) {
377
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
378
+ return false;
379
+ }
380
+ if (Object.getPrototypeOf(input) === null) {
381
+ return true;
382
+ }
383
+ let proto = input;
384
+ while (Object.getPrototypeOf(proto) !== null) {
385
+ proto = Object.getPrototypeOf(proto);
386
+ }
387
+ return Object.getPrototypeOf(input) === proto;
388
+ }
389
+
390
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/check_key_length.js
391
+ function checkKeyLength(alg, key) {
392
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
393
+ const { modulusLength } = key.algorithm;
394
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
395
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
396
+ }
397
+ }
398
+ }
399
+
400
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/asn1.js
401
+ var formatPEM = (b64, descriptor) => {
402
+ const newlined = (b64.match(/.{1,64}/g) || []).join(`
403
+ `);
404
+ return `-----BEGIN ${descriptor}-----
405
+ ${newlined}
406
+ -----END ${descriptor}-----`;
407
+ };
408
+ var genericExport = async (keyType, keyFormat, key) => {
409
+ if (isKeyObject(key)) {
410
+ if (key.type !== keyType) {
411
+ throw new TypeError(`key is not a ${keyType} key`);
412
+ }
413
+ return key.export({ format: "pem", type: keyFormat });
414
+ }
415
+ if (!isCryptoKey(key)) {
416
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
417
+ }
418
+ if (!key.extractable) {
419
+ throw new TypeError("CryptoKey is not extractable");
420
+ }
421
+ if (key.type !== keyType) {
422
+ throw new TypeError(`key is not a ${keyType} key`);
423
+ }
424
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
425
+ };
426
+ var toSPKI = (key) => genericExport("public", "spki", key);
427
+ var toPKCS8 = (key) => genericExport("private", "pkcs8", key);
428
+ var bytesEqual = (a, b) => {
429
+ if (a.byteLength !== b.length)
430
+ return false;
431
+ for (let i = 0;i < a.byteLength; i++) {
432
+ if (a[i] !== b[i])
433
+ return false;
434
+ }
435
+ return true;
436
+ };
437
+ var createASN1State = (data) => ({ data, pos: 0 });
438
+ var parseLength = (state) => {
439
+ const first = state.data[state.pos++];
440
+ if (first & 128) {
441
+ const lengthOfLen = first & 127;
442
+ let length = 0;
443
+ for (let i = 0;i < lengthOfLen; i++) {
444
+ length = length << 8 | state.data[state.pos++];
445
+ }
446
+ return length;
447
+ }
448
+ return first;
449
+ };
450
+ var expectTag = (state, expectedTag, errorMessage) => {
451
+ if (state.data[state.pos++] !== expectedTag) {
452
+ throw new Error(errorMessage);
453
+ }
454
+ };
455
+ var getSubarray = (state, length) => {
456
+ const result = state.data.subarray(state.pos, state.pos + length);
457
+ state.pos += length;
458
+ return result;
459
+ };
460
+ var parseAlgorithmOID = (state) => {
461
+ expectTag(state, 6, "Expected algorithm OID");
462
+ const oidLen = parseLength(state);
463
+ return getSubarray(state, oidLen);
464
+ };
465
+ function parsePKCS8Header(state) {
466
+ expectTag(state, 48, "Invalid PKCS#8 structure");
467
+ parseLength(state);
468
+ expectTag(state, 2, "Expected version field");
469
+ const verLen = parseLength(state);
470
+ state.pos += verLen;
471
+ expectTag(state, 48, "Expected algorithm identifier");
472
+ const algIdLen = parseLength(state);
473
+ const algIdStart = state.pos;
474
+ return { algIdStart, algIdLength: algIdLen };
475
+ }
476
+ function parseSPKIHeader(state) {
477
+ expectTag(state, 48, "Invalid SPKI structure");
478
+ parseLength(state);
479
+ expectTag(state, 48, "Expected algorithm identifier");
480
+ const algIdLen = parseLength(state);
481
+ const algIdStart = state.pos;
482
+ return { algIdStart, algIdLength: algIdLen };
483
+ }
484
+ var parseECAlgorithmIdentifier = (state) => {
485
+ const algOid = parseAlgorithmOID(state);
486
+ if (bytesEqual(algOid, [43, 101, 110])) {
487
+ return "X25519";
488
+ }
489
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
490
+ throw new Error("Unsupported key algorithm");
491
+ }
492
+ expectTag(state, 6, "Expected curve OID");
493
+ const curveOidLen = parseLength(state);
494
+ const curveOid = getSubarray(state, curveOidLen);
495
+ for (const { name, oid } of [
496
+ { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] },
497
+ { name: "P-384", oid: [43, 129, 4, 0, 34] },
498
+ { name: "P-521", oid: [43, 129, 4, 0, 35] }
499
+ ]) {
500
+ if (bytesEqual(curveOid, oid)) {
501
+ return name;
502
+ }
503
+ }
504
+ throw new Error("Unsupported named curve");
505
+ };
506
+ var genericImport = async (keyFormat, keyData, alg, options) => {
507
+ let algorithm;
508
+ let keyUsages;
509
+ const isPublic = keyFormat === "spki";
510
+ const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
511
+ const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
512
+ switch (alg) {
513
+ case "PS256":
514
+ case "PS384":
515
+ case "PS512":
516
+ algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
517
+ keyUsages = getSigUsages();
518
+ break;
519
+ case "RS256":
520
+ case "RS384":
521
+ case "RS512":
522
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
523
+ keyUsages = getSigUsages();
524
+ break;
525
+ case "RSA-OAEP":
526
+ case "RSA-OAEP-256":
527
+ case "RSA-OAEP-384":
528
+ case "RSA-OAEP-512":
529
+ algorithm = {
530
+ name: "RSA-OAEP",
531
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
532
+ };
533
+ keyUsages = getEncUsages();
534
+ break;
535
+ case "ES256":
536
+ case "ES384":
537
+ case "ES512": {
538
+ const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
539
+ algorithm = { name: "ECDSA", namedCurve: curveMap[alg] };
540
+ keyUsages = getSigUsages();
541
+ break;
542
+ }
543
+ case "ECDH-ES":
544
+ case "ECDH-ES+A128KW":
545
+ case "ECDH-ES+A192KW":
546
+ case "ECDH-ES+A256KW": {
547
+ try {
548
+ const namedCurve = options.getNamedCurve(keyData);
549
+ algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve };
550
+ } catch (cause) {
551
+ throw new JOSENotSupported("Invalid or unsupported key format");
552
+ }
553
+ keyUsages = isPublic ? [] : ["deriveBits"];
554
+ break;
555
+ }
556
+ case "Ed25519":
557
+ case "EdDSA":
558
+ algorithm = { name: "Ed25519" };
559
+ keyUsages = getSigUsages();
560
+ break;
561
+ case "ML-DSA-44":
562
+ case "ML-DSA-65":
563
+ case "ML-DSA-87":
564
+ algorithm = { name: alg };
565
+ keyUsages = getSigUsages();
566
+ break;
567
+ default:
568
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
569
+ }
570
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
571
+ };
572
+ var processPEMData = (pem, pattern) => {
573
+ return decodeBase64(pem.replace(pattern, ""));
574
+ };
575
+ var fromPKCS8 = (pem, alg, options) => {
576
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
577
+ let opts = options;
578
+ if (alg?.startsWith?.("ECDH-ES")) {
579
+ opts ||= {};
580
+ opts.getNamedCurve = (keyData2) => {
581
+ const state = createASN1State(keyData2);
582
+ parsePKCS8Header(state);
583
+ return parseECAlgorithmIdentifier(state);
584
+ };
585
+ }
586
+ return genericImport("pkcs8", keyData, alg, opts);
587
+ };
588
+ var fromSPKI = (pem, alg, options) => {
589
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
590
+ let opts = options;
591
+ if (alg?.startsWith?.("ECDH-ES")) {
592
+ opts ||= {};
593
+ opts.getNamedCurve = (keyData2) => {
594
+ const state = createASN1State(keyData2);
595
+ parseSPKIHeader(state);
596
+ return parseECAlgorithmIdentifier(state);
597
+ };
598
+ }
599
+ return genericImport("spki", keyData, alg, opts);
600
+ };
601
+
602
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/jwk_to_key.js
603
+ function subtleMapping(jwk) {
604
+ let algorithm;
605
+ let keyUsages;
606
+ switch (jwk.kty) {
607
+ case "AKP": {
608
+ switch (jwk.alg) {
609
+ case "ML-DSA-44":
610
+ case "ML-DSA-65":
611
+ case "ML-DSA-87":
612
+ algorithm = { name: jwk.alg };
613
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
614
+ break;
615
+ default:
616
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
617
+ }
618
+ break;
619
+ }
620
+ case "RSA": {
621
+ switch (jwk.alg) {
622
+ case "PS256":
623
+ case "PS384":
624
+ case "PS512":
625
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
626
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
627
+ break;
628
+ case "RS256":
629
+ case "RS384":
630
+ case "RS512":
631
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
632
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
633
+ break;
634
+ case "RSA-OAEP":
635
+ case "RSA-OAEP-256":
636
+ case "RSA-OAEP-384":
637
+ case "RSA-OAEP-512":
638
+ algorithm = {
639
+ name: "RSA-OAEP",
640
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
641
+ };
642
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
643
+ break;
644
+ default:
645
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
646
+ }
647
+ break;
648
+ }
649
+ case "EC": {
650
+ switch (jwk.alg) {
651
+ case "ES256":
652
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
653
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
654
+ break;
655
+ case "ES384":
656
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
657
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
658
+ break;
659
+ case "ES512":
660
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
661
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
662
+ break;
663
+ case "ECDH-ES":
664
+ case "ECDH-ES+A128KW":
665
+ case "ECDH-ES+A192KW":
666
+ case "ECDH-ES+A256KW":
667
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
668
+ keyUsages = jwk.d ? ["deriveBits"] : [];
669
+ break;
670
+ default:
671
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
672
+ }
673
+ break;
674
+ }
675
+ case "OKP": {
676
+ switch (jwk.alg) {
677
+ case "Ed25519":
678
+ case "EdDSA":
679
+ algorithm = { name: "Ed25519" };
680
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
681
+ break;
682
+ case "ECDH-ES":
683
+ case "ECDH-ES+A128KW":
684
+ case "ECDH-ES+A192KW":
685
+ case "ECDH-ES+A256KW":
686
+ algorithm = { name: jwk.crv };
687
+ keyUsages = jwk.d ? ["deriveBits"] : [];
688
+ break;
689
+ default:
690
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
691
+ }
692
+ break;
693
+ }
694
+ default:
695
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
696
+ }
697
+ return { algorithm, keyUsages };
698
+ }
699
+ async function jwkToKey(jwk) {
700
+ if (!jwk.alg) {
701
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
702
+ }
703
+ const { algorithm, keyUsages } = subtleMapping(jwk);
704
+ const keyData = { ...jwk };
705
+ if (keyData.kty !== "AKP") {
706
+ delete keyData.alg;
707
+ }
708
+ delete keyData.use;
709
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
710
+ }
711
+
712
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/key/import.js
713
+ async function importSPKI(spki, alg, options) {
714
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
715
+ throw new TypeError('"spki" must be SPKI formatted string');
716
+ }
717
+ return fromSPKI(spki, alg, options);
718
+ }
719
+ async function importPKCS8(pkcs8, alg, options) {
720
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
721
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
722
+ }
723
+ return fromPKCS8(pkcs8, alg, options);
724
+ }
725
+ async function importJWK(jwk, alg, options) {
726
+ if (!isObject(jwk)) {
727
+ throw new TypeError("JWK must be an object");
728
+ }
729
+ let ext;
730
+ alg ??= jwk.alg;
731
+ ext ??= options?.extractable ?? jwk.ext;
732
+ switch (jwk.kty) {
733
+ case "oct":
734
+ if (typeof jwk.k !== "string" || !jwk.k) {
735
+ throw new TypeError('missing "k" (Key Value) Parameter value');
736
+ }
737
+ return decode(jwk.k);
738
+ case "RSA":
739
+ if ("oth" in jwk && jwk.oth !== undefined) {
740
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
741
+ }
742
+ return jwkToKey({ ...jwk, alg, ext });
743
+ case "AKP": {
744
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
745
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
746
+ }
747
+ if (alg !== undefined && alg !== jwk.alg) {
748
+ throw new TypeError("JWK alg and alg option value mismatch");
749
+ }
750
+ return jwkToKey({ ...jwk, ext });
751
+ }
752
+ case "EC":
753
+ case "OKP":
754
+ return jwkToKey({ ...jwk, alg, ext });
755
+ default:
756
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
757
+ }
758
+ }
759
+
760
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/validate_crit.js
761
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
762
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
763
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
764
+ }
765
+ if (!protectedHeader || protectedHeader.crit === undefined) {
766
+ return new Set;
767
+ }
768
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
769
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
770
+ }
771
+ let recognized;
772
+ if (recognizedOption !== undefined) {
773
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
774
+ } else {
775
+ recognized = recognizedDefault;
776
+ }
777
+ for (const parameter of protectedHeader.crit) {
778
+ if (!recognized.has(parameter)) {
779
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
780
+ }
781
+ if (joseHeader[parameter] === undefined) {
782
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
783
+ }
784
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
785
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
786
+ }
787
+ }
788
+ return new Set(protectedHeader.crit);
789
+ }
790
+
791
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/validate_algorithms.js
792
+ function validateAlgorithms(option, algorithms) {
793
+ if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
794
+ throw new TypeError(`"${option}" option must be an array of strings`);
795
+ }
796
+ if (!algorithms) {
797
+ return;
798
+ }
799
+ return new Set(algorithms);
800
+ }
801
+
802
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/is_jwk.js
803
+ var isJWK = (key) => isObject(key) && typeof key.kty === "string";
804
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
805
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
806
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
807
+
808
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/normalize_key.js
809
+ var cache;
810
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
811
+ cache ||= new WeakMap;
812
+ let cached = cache.get(key);
813
+ if (cached?.[alg]) {
814
+ return cached[alg];
815
+ }
816
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
817
+ if (freeze)
818
+ Object.freeze(key);
819
+ if (!cached) {
820
+ cache.set(key, { [alg]: cryptoKey });
821
+ } else {
822
+ cached[alg] = cryptoKey;
823
+ }
824
+ return cryptoKey;
825
+ };
826
+ var handleKeyObject = (keyObject, alg) => {
827
+ cache ||= new WeakMap;
828
+ let cached = cache.get(keyObject);
829
+ if (cached?.[alg]) {
830
+ return cached[alg];
831
+ }
832
+ const isPublic = keyObject.type === "public";
833
+ const extractable = isPublic ? true : false;
834
+ let cryptoKey;
835
+ if (keyObject.asymmetricKeyType === "x25519") {
836
+ switch (alg) {
837
+ case "ECDH-ES":
838
+ case "ECDH-ES+A128KW":
839
+ case "ECDH-ES+A192KW":
840
+ case "ECDH-ES+A256KW":
841
+ break;
842
+ default:
843
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
844
+ }
845
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
846
+ }
847
+ if (keyObject.asymmetricKeyType === "ed25519") {
848
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
849
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
850
+ }
851
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
852
+ isPublic ? "verify" : "sign"
853
+ ]);
854
+ }
855
+ switch (keyObject.asymmetricKeyType) {
856
+ case "ml-dsa-44":
857
+ case "ml-dsa-65":
858
+ case "ml-dsa-87": {
859
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
860
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
861
+ }
862
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
863
+ isPublic ? "verify" : "sign"
864
+ ]);
865
+ }
866
+ }
867
+ if (keyObject.asymmetricKeyType === "rsa") {
868
+ let hash;
869
+ switch (alg) {
870
+ case "RSA-OAEP":
871
+ hash = "SHA-1";
872
+ break;
873
+ case "RS256":
874
+ case "PS256":
875
+ case "RSA-OAEP-256":
876
+ hash = "SHA-256";
877
+ break;
878
+ case "RS384":
879
+ case "PS384":
880
+ case "RSA-OAEP-384":
881
+ hash = "SHA-384";
882
+ break;
883
+ case "RS512":
884
+ case "PS512":
885
+ case "RSA-OAEP-512":
886
+ hash = "SHA-512";
887
+ break;
888
+ default:
889
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
890
+ }
891
+ if (alg.startsWith("RSA-OAEP")) {
892
+ return keyObject.toCryptoKey({
893
+ name: "RSA-OAEP",
894
+ hash
895
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
896
+ }
897
+ cryptoKey = keyObject.toCryptoKey({
898
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
899
+ hash
900
+ }, extractable, [isPublic ? "verify" : "sign"]);
901
+ }
902
+ if (keyObject.asymmetricKeyType === "ec") {
903
+ const nist = new Map([
904
+ ["prime256v1", "P-256"],
905
+ ["secp384r1", "P-384"],
906
+ ["secp521r1", "P-521"]
907
+ ]);
908
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
909
+ if (!namedCurve) {
910
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
911
+ }
912
+ if (alg === "ES256" && namedCurve === "P-256") {
913
+ cryptoKey = keyObject.toCryptoKey({
914
+ name: "ECDSA",
915
+ namedCurve
916
+ }, extractable, [isPublic ? "verify" : "sign"]);
917
+ }
918
+ if (alg === "ES384" && namedCurve === "P-384") {
919
+ cryptoKey = keyObject.toCryptoKey({
920
+ name: "ECDSA",
921
+ namedCurve
922
+ }, extractable, [isPublic ? "verify" : "sign"]);
923
+ }
924
+ if (alg === "ES512" && namedCurve === "P-521") {
925
+ cryptoKey = keyObject.toCryptoKey({
926
+ name: "ECDSA",
927
+ namedCurve
928
+ }, extractable, [isPublic ? "verify" : "sign"]);
929
+ }
930
+ if (alg.startsWith("ECDH-ES")) {
931
+ cryptoKey = keyObject.toCryptoKey({
932
+ name: "ECDH",
933
+ namedCurve
934
+ }, extractable, isPublic ? [] : ["deriveBits"]);
935
+ }
936
+ }
937
+ if (!cryptoKey) {
938
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
939
+ }
940
+ if (!cached) {
941
+ cache.set(keyObject, { [alg]: cryptoKey });
942
+ } else {
943
+ cached[alg] = cryptoKey;
944
+ }
945
+ return cryptoKey;
946
+ };
947
+ async function normalizeKey(key, alg) {
948
+ if (key instanceof Uint8Array) {
949
+ return key;
950
+ }
951
+ if (isCryptoKey(key)) {
952
+ return key;
953
+ }
954
+ if (isKeyObject(key)) {
955
+ if (key.type === "secret") {
956
+ return key.export();
957
+ }
958
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
959
+ try {
960
+ return handleKeyObject(key, alg);
961
+ } catch (err) {
962
+ if (err instanceof TypeError) {
963
+ throw err;
964
+ }
965
+ }
966
+ }
967
+ let jwk = key.export({ format: "jwk" });
968
+ return handleJWK(key, jwk, alg);
969
+ }
970
+ if (isJWK(key)) {
971
+ if (key.k) {
972
+ return decode(key.k);
973
+ }
974
+ return handleJWK(key, key, alg, true);
975
+ }
976
+ throw new Error("unreachable");
977
+ }
978
+
979
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/check_key_type.js
980
+ var tag = (key) => key?.[Symbol.toStringTag];
981
+ var jwkMatchesOp = (alg, key, usage) => {
982
+ if (key.use !== undefined) {
983
+ let expected;
984
+ switch (usage) {
985
+ case "sign":
986
+ case "verify":
987
+ expected = "sig";
988
+ break;
989
+ case "encrypt":
990
+ case "decrypt":
991
+ expected = "enc";
992
+ break;
993
+ }
994
+ if (key.use !== expected) {
995
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
996
+ }
997
+ }
998
+ if (key.alg !== undefined && key.alg !== alg) {
999
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1000
+ }
1001
+ if (Array.isArray(key.key_ops)) {
1002
+ let expectedKeyOp;
1003
+ switch (true) {
1004
+ case (usage === "sign" || usage === "verify"):
1005
+ case alg === "dir":
1006
+ case alg.includes("CBC-HS"):
1007
+ expectedKeyOp = usage;
1008
+ break;
1009
+ case alg.startsWith("PBES2"):
1010
+ expectedKeyOp = "deriveBits";
1011
+ break;
1012
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1013
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
1014
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1015
+ } else {
1016
+ expectedKeyOp = usage;
1017
+ }
1018
+ break;
1019
+ case (usage === "encrypt" && alg.startsWith("RSA")):
1020
+ expectedKeyOp = "wrapKey";
1021
+ break;
1022
+ case usage === "decrypt":
1023
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1024
+ break;
1025
+ }
1026
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
1027
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1028
+ }
1029
+ }
1030
+ return true;
1031
+ };
1032
+ var symmetricTypeCheck = (alg, key, usage) => {
1033
+ if (key instanceof Uint8Array)
1034
+ return;
1035
+ if (isJWK(key)) {
1036
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
1037
+ return;
1038
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
1039
+ }
1040
+ if (!isKeyLike(key)) {
1041
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1042
+ }
1043
+ if (key.type !== "secret") {
1044
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1045
+ }
1046
+ };
1047
+ var asymmetricTypeCheck = (alg, key, usage) => {
1048
+ if (isJWK(key)) {
1049
+ switch (usage) {
1050
+ case "decrypt":
1051
+ case "sign":
1052
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
1053
+ return;
1054
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1055
+ case "encrypt":
1056
+ case "verify":
1057
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
1058
+ return;
1059
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1060
+ }
1061
+ }
1062
+ if (!isKeyLike(key)) {
1063
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1064
+ }
1065
+ if (key.type === "secret") {
1066
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1067
+ }
1068
+ if (key.type === "public") {
1069
+ switch (usage) {
1070
+ case "sign":
1071
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1072
+ case "decrypt":
1073
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1074
+ }
1075
+ }
1076
+ if (key.type === "private") {
1077
+ switch (usage) {
1078
+ case "verify":
1079
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1080
+ case "encrypt":
1081
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1082
+ }
1083
+ }
1084
+ };
1085
+ function checkKeyType(alg, key, usage) {
1086
+ switch (alg.substring(0, 2)) {
1087
+ case "A1":
1088
+ case "A2":
1089
+ case "di":
1090
+ case "HS":
1091
+ case "PB":
1092
+ symmetricTypeCheck(alg, key, usage);
1093
+ break;
1094
+ default:
1095
+ asymmetricTypeCheck(alg, key, usage);
1096
+ }
1097
+ }
1098
+
1099
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/key_to_jwk.js
1100
+ async function keyToJWK(key) {
1101
+ if (isKeyObject(key)) {
1102
+ if (key.type === "secret") {
1103
+ key = key.export();
1104
+ } else {
1105
+ return key.export({ format: "jwk" });
1106
+ }
1107
+ }
1108
+ if (key instanceof Uint8Array) {
1109
+ return {
1110
+ kty: "oct",
1111
+ k: encode2(key)
1112
+ };
1113
+ }
1114
+ if (!isCryptoKey(key)) {
1115
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
1116
+ }
1117
+ if (!key.extractable) {
1118
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
1119
+ }
1120
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
1121
+ if (jwk.kty === "AKP") {
1122
+ jwk.alg = alg;
1123
+ }
1124
+ return jwk;
1125
+ }
1126
+
1127
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/key/export.js
1128
+ async function exportSPKI(key) {
1129
+ return toSPKI(key);
1130
+ }
1131
+ async function exportPKCS8(key) {
1132
+ return toPKCS8(key);
1133
+ }
1134
+ async function exportJWK(key) {
1135
+ return keyToJWK(key);
1136
+ }
1137
+
1138
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/subtle_dsa.js
1139
+ function subtleAlgorithm(alg, algorithm) {
1140
+ const hash = `SHA-${alg.slice(-3)}`;
1141
+ switch (alg) {
1142
+ case "HS256":
1143
+ case "HS384":
1144
+ case "HS512":
1145
+ return { hash, name: "HMAC" };
1146
+ case "PS256":
1147
+ case "PS384":
1148
+ case "PS512":
1149
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
1150
+ case "RS256":
1151
+ case "RS384":
1152
+ case "RS512":
1153
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
1154
+ case "ES256":
1155
+ case "ES384":
1156
+ case "ES512":
1157
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
1158
+ case "Ed25519":
1159
+ case "EdDSA":
1160
+ return { name: "Ed25519" };
1161
+ case "ML-DSA-44":
1162
+ case "ML-DSA-65":
1163
+ case "ML-DSA-87":
1164
+ return { name: alg };
1165
+ default:
1166
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
1167
+ }
1168
+ }
1169
+
1170
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
1171
+ async function getSigKey(alg, key, usage) {
1172
+ if (key instanceof Uint8Array) {
1173
+ if (!alg.startsWith("HS")) {
1174
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1175
+ }
1176
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
1177
+ }
1178
+ checkSigCryptoKey(key, alg, usage);
1179
+ return key;
1180
+ }
1181
+
1182
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/verify.js
1183
+ async function verify(alg, key, signature, data) {
1184
+ const cryptoKey = await getSigKey(alg, key, "verify");
1185
+ checkKeyLength(alg, cryptoKey);
1186
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
1187
+ try {
1188
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
1189
+ } catch {
1190
+ return false;
1191
+ }
1192
+ }
1193
+
1194
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jws/flattened/verify.js
1195
+ async function flattenedVerify(jws, key, options) {
1196
+ if (!isObject(jws)) {
1197
+ throw new JWSInvalid("Flattened JWS must be an object");
1198
+ }
1199
+ if (jws.protected === undefined && jws.header === undefined) {
1200
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
1201
+ }
1202
+ if (jws.protected !== undefined && typeof jws.protected !== "string") {
1203
+ throw new JWSInvalid("JWS Protected Header incorrect type");
1204
+ }
1205
+ if (jws.payload === undefined) {
1206
+ throw new JWSInvalid("JWS Payload missing");
1207
+ }
1208
+ if (typeof jws.signature !== "string") {
1209
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
1210
+ }
1211
+ if (jws.header !== undefined && !isObject(jws.header)) {
1212
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
1213
+ }
1214
+ let parsedProt = {};
1215
+ if (jws.protected) {
1216
+ try {
1217
+ const protectedHeader = decode(jws.protected);
1218
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
1219
+ } catch {
1220
+ throw new JWSInvalid("JWS Protected Header is invalid");
1221
+ }
1222
+ }
1223
+ if (!isDisjoint(parsedProt, jws.header)) {
1224
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1225
+ }
1226
+ const joseHeader = {
1227
+ ...parsedProt,
1228
+ ...jws.header
1229
+ };
1230
+ const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
1231
+ let b64 = true;
1232
+ if (extensions.has("b64")) {
1233
+ b64 = parsedProt.b64;
1234
+ if (typeof b64 !== "boolean") {
1235
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1236
+ }
1237
+ }
1238
+ const { alg } = joseHeader;
1239
+ if (typeof alg !== "string" || !alg) {
1240
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1241
+ }
1242
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
1243
+ if (algorithms && !algorithms.has(alg)) {
1244
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
1245
+ }
1246
+ if (b64) {
1247
+ if (typeof jws.payload !== "string") {
1248
+ throw new JWSInvalid("JWS Payload must be a string");
1249
+ }
1250
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
1251
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
1252
+ }
1253
+ let resolvedKey = false;
1254
+ if (typeof key === "function") {
1255
+ key = await key(parsedProt, jws);
1256
+ resolvedKey = true;
1257
+ }
1258
+ checkKeyType(alg, key, "verify");
1259
+ const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array, encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
1260
+ let signature;
1261
+ try {
1262
+ signature = decode(jws.signature);
1263
+ } catch {
1264
+ throw new JWSInvalid("Failed to base64url decode the signature");
1265
+ }
1266
+ const k = await normalizeKey(key, alg);
1267
+ const verified = await verify(alg, k, signature, data);
1268
+ if (!verified) {
1269
+ throw new JWSSignatureVerificationFailed;
1270
+ }
1271
+ let payload;
1272
+ if (b64) {
1273
+ try {
1274
+ payload = decode(jws.payload);
1275
+ } catch {
1276
+ throw new JWSInvalid("Failed to base64url decode the payload");
1277
+ }
1278
+ } else if (typeof jws.payload === "string") {
1279
+ payload = encoder.encode(jws.payload);
1280
+ } else {
1281
+ payload = jws.payload;
1282
+ }
1283
+ const result = { payload };
1284
+ if (jws.protected !== undefined) {
1285
+ result.protectedHeader = parsedProt;
1286
+ }
1287
+ if (jws.header !== undefined) {
1288
+ result.unprotectedHeader = jws.header;
1289
+ }
1290
+ if (resolvedKey) {
1291
+ return { ...result, key: k };
1292
+ }
1293
+ return result;
1294
+ }
1295
+
1296
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jws/compact/verify.js
1297
+ async function compactVerify(jws, key, options) {
1298
+ if (jws instanceof Uint8Array) {
1299
+ jws = decoder.decode(jws);
1300
+ }
1301
+ if (typeof jws !== "string") {
1302
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
1303
+ }
1304
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
1305
+ if (length !== 3) {
1306
+ throw new JWSInvalid("Invalid Compact JWS");
1307
+ }
1308
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
1309
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
1310
+ if (typeof key === "function") {
1311
+ return { ...result, key: verified.key };
1312
+ }
1313
+ return result;
1314
+ }
1315
+
1316
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
1317
+ var epoch = (date) => Math.floor(date.getTime() / 1000);
1318
+ var minute = 60;
1319
+ var hour = minute * 60;
1320
+ var day = hour * 24;
1321
+ var week = day * 7;
1322
+ var year = day * 365.25;
1323
+ var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
1324
+ function secs(str) {
1325
+ const matched = REGEX.exec(str);
1326
+ if (!matched || matched[4] && matched[1]) {
1327
+ throw new TypeError("Invalid time period format");
1328
+ }
1329
+ const value = parseFloat(matched[2]);
1330
+ const unit = matched[3].toLowerCase();
1331
+ let numericDate;
1332
+ switch (unit) {
1333
+ case "sec":
1334
+ case "secs":
1335
+ case "second":
1336
+ case "seconds":
1337
+ case "s":
1338
+ numericDate = Math.round(value);
1339
+ break;
1340
+ case "minute":
1341
+ case "minutes":
1342
+ case "min":
1343
+ case "mins":
1344
+ case "m":
1345
+ numericDate = Math.round(value * minute);
1346
+ break;
1347
+ case "hour":
1348
+ case "hours":
1349
+ case "hr":
1350
+ case "hrs":
1351
+ case "h":
1352
+ numericDate = Math.round(value * hour);
1353
+ break;
1354
+ case "day":
1355
+ case "days":
1356
+ case "d":
1357
+ numericDate = Math.round(value * day);
1358
+ break;
1359
+ case "week":
1360
+ case "weeks":
1361
+ case "w":
1362
+ numericDate = Math.round(value * week);
1363
+ break;
1364
+ default:
1365
+ numericDate = Math.round(value * year);
1366
+ break;
1367
+ }
1368
+ if (matched[1] === "-" || matched[4] === "ago") {
1369
+ return -numericDate;
1370
+ }
1371
+ return numericDate;
1372
+ }
1373
+ function validateInput(label, input) {
1374
+ if (!Number.isFinite(input)) {
1375
+ throw new TypeError(`Invalid ${label} input`);
1376
+ }
1377
+ return input;
1378
+ }
1379
+ var normalizeTyp = (value) => {
1380
+ if (value.includes("/")) {
1381
+ return value.toLowerCase();
1382
+ }
1383
+ return `application/${value.toLowerCase()}`;
1384
+ };
1385
+ var checkAudiencePresence = (audPayload, audOption) => {
1386
+ if (typeof audPayload === "string") {
1387
+ return audOption.includes(audPayload);
1388
+ }
1389
+ if (Array.isArray(audPayload)) {
1390
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1391
+ }
1392
+ return false;
1393
+ };
1394
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1395
+ let payload;
1396
+ try {
1397
+ payload = JSON.parse(decoder.decode(encodedPayload));
1398
+ } catch {}
1399
+ if (!isObject(payload)) {
1400
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1401
+ }
1402
+ const { typ } = options;
1403
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
1404
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
1405
+ }
1406
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1407
+ const presenceCheck = [...requiredClaims];
1408
+ if (maxTokenAge !== undefined)
1409
+ presenceCheck.push("iat");
1410
+ if (audience !== undefined)
1411
+ presenceCheck.push("aud");
1412
+ if (subject !== undefined)
1413
+ presenceCheck.push("sub");
1414
+ if (issuer !== undefined)
1415
+ presenceCheck.push("iss");
1416
+ for (const claim of new Set(presenceCheck.reverse())) {
1417
+ if (!(claim in payload)) {
1418
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1419
+ }
1420
+ }
1421
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1422
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
1423
+ }
1424
+ if (subject && payload.sub !== subject) {
1425
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
1426
+ }
1427
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
1428
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
1429
+ }
1430
+ let tolerance;
1431
+ switch (typeof options.clockTolerance) {
1432
+ case "string":
1433
+ tolerance = secs(options.clockTolerance);
1434
+ break;
1435
+ case "number":
1436
+ tolerance = options.clockTolerance;
1437
+ break;
1438
+ case "undefined":
1439
+ tolerance = 0;
1440
+ break;
1441
+ default:
1442
+ throw new TypeError("Invalid clockTolerance option type");
1443
+ }
1444
+ const { currentDate } = options;
1445
+ const now = epoch(currentDate || new Date);
1446
+ if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== "number") {
1447
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
1448
+ }
1449
+ if (payload.nbf !== undefined) {
1450
+ if (typeof payload.nbf !== "number") {
1451
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
1452
+ }
1453
+ if (payload.nbf > now + tolerance) {
1454
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
1455
+ }
1456
+ }
1457
+ if (payload.exp !== undefined) {
1458
+ if (typeof payload.exp !== "number") {
1459
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
1460
+ }
1461
+ if (payload.exp <= now - tolerance) {
1462
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
1463
+ }
1464
+ }
1465
+ if (maxTokenAge) {
1466
+ const age = now - payload.iat;
1467
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1468
+ if (age - tolerance > max) {
1469
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
1470
+ }
1471
+ if (age < 0 - tolerance) {
1472
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
1473
+ }
1474
+ }
1475
+ return payload;
1476
+ }
1477
+
1478
+ class JWTClaimsBuilder {
1479
+ #payload;
1480
+ constructor(payload) {
1481
+ if (!isObject(payload)) {
1482
+ throw new TypeError("JWT Claims Set MUST be an object");
1483
+ }
1484
+ this.#payload = structuredClone(payload);
1485
+ }
1486
+ data() {
1487
+ return encoder.encode(JSON.stringify(this.#payload));
1488
+ }
1489
+ get iss() {
1490
+ return this.#payload.iss;
1491
+ }
1492
+ set iss(value) {
1493
+ this.#payload.iss = value;
1494
+ }
1495
+ get sub() {
1496
+ return this.#payload.sub;
1497
+ }
1498
+ set sub(value) {
1499
+ this.#payload.sub = value;
1500
+ }
1501
+ get aud() {
1502
+ return this.#payload.aud;
1503
+ }
1504
+ set aud(value) {
1505
+ this.#payload.aud = value;
1506
+ }
1507
+ set jti(value) {
1508
+ this.#payload.jti = value;
1509
+ }
1510
+ set nbf(value) {
1511
+ if (typeof value === "number") {
1512
+ this.#payload.nbf = validateInput("setNotBefore", value);
1513
+ } else if (value instanceof Date) {
1514
+ this.#payload.nbf = validateInput("setNotBefore", epoch(value));
1515
+ } else {
1516
+ this.#payload.nbf = epoch(new Date) + secs(value);
1517
+ }
1518
+ }
1519
+ set exp(value) {
1520
+ if (typeof value === "number") {
1521
+ this.#payload.exp = validateInput("setExpirationTime", value);
1522
+ } else if (value instanceof Date) {
1523
+ this.#payload.exp = validateInput("setExpirationTime", epoch(value));
1524
+ } else {
1525
+ this.#payload.exp = epoch(new Date) + secs(value);
1526
+ }
1527
+ }
1528
+ set iat(value) {
1529
+ if (value === undefined) {
1530
+ this.#payload.iat = epoch(new Date);
1531
+ } else if (value instanceof Date) {
1532
+ this.#payload.iat = validateInput("setIssuedAt", epoch(value));
1533
+ } else if (typeof value === "string") {
1534
+ this.#payload.iat = validateInput("setIssuedAt", epoch(new Date) + secs(value));
1535
+ } else {
1536
+ this.#payload.iat = validateInput("setIssuedAt", value);
1537
+ }
1538
+ }
1539
+ }
1540
+
1541
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jwt/verify.js
1542
+ async function jwtVerify(jwt, key, options) {
1543
+ const verified = await compactVerify(jwt, key, options);
1544
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1545
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1546
+ }
1547
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
1548
+ const result = { payload, protectedHeader: verified.protectedHeader };
1549
+ if (typeof key === "function") {
1550
+ return { ...result, key: verified.key };
1551
+ }
1552
+ return result;
1553
+ }
1554
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/lib/sign.js
1555
+ async function sign(alg, key, data) {
1556
+ const cryptoKey = await getSigKey(alg, key, "sign");
1557
+ checkKeyLength(alg, cryptoKey);
1558
+ const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
1559
+ return new Uint8Array(signature);
1560
+ }
1561
+
1562
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jws/flattened/sign.js
1563
+ class FlattenedSign {
1564
+ #payload;
1565
+ #protectedHeader;
1566
+ #unprotectedHeader;
1567
+ constructor(payload) {
1568
+ if (!(payload instanceof Uint8Array)) {
1569
+ throw new TypeError("payload must be an instance of Uint8Array");
1570
+ }
1571
+ this.#payload = payload;
1572
+ }
1573
+ setProtectedHeader(protectedHeader) {
1574
+ if (this.#protectedHeader) {
1575
+ throw new TypeError("setProtectedHeader can only be called once");
1576
+ }
1577
+ this.#protectedHeader = protectedHeader;
1578
+ return this;
1579
+ }
1580
+ setUnprotectedHeader(unprotectedHeader) {
1581
+ if (this.#unprotectedHeader) {
1582
+ throw new TypeError("setUnprotectedHeader can only be called once");
1583
+ }
1584
+ this.#unprotectedHeader = unprotectedHeader;
1585
+ return this;
1586
+ }
1587
+ async sign(key, options) {
1588
+ if (!this.#protectedHeader && !this.#unprotectedHeader) {
1589
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1590
+ }
1591
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
1592
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1593
+ }
1594
+ const joseHeader = {
1595
+ ...this.#protectedHeader,
1596
+ ...this.#unprotectedHeader
1597
+ };
1598
+ const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
1599
+ let b64 = true;
1600
+ if (extensions.has("b64")) {
1601
+ b64 = this.#protectedHeader.b64;
1602
+ if (typeof b64 !== "boolean") {
1603
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1604
+ }
1605
+ }
1606
+ const { alg } = joseHeader;
1607
+ if (typeof alg !== "string" || !alg) {
1608
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1609
+ }
1610
+ checkKeyType(alg, key, "sign");
1611
+ let payloadS;
1612
+ let payloadB;
1613
+ if (b64) {
1614
+ payloadS = encode2(this.#payload);
1615
+ payloadB = encode(payloadS);
1616
+ } else {
1617
+ payloadB = this.#payload;
1618
+ payloadS = "";
1619
+ }
1620
+ let protectedHeaderString;
1621
+ let protectedHeaderBytes;
1622
+ if (this.#protectedHeader) {
1623
+ protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
1624
+ protectedHeaderBytes = encode(protectedHeaderString);
1625
+ } else {
1626
+ protectedHeaderString = "";
1627
+ protectedHeaderBytes = new Uint8Array;
1628
+ }
1629
+ const data = concat(protectedHeaderBytes, encode("."), payloadB);
1630
+ const k = await normalizeKey(key, alg);
1631
+ const signature = await sign(alg, k, data);
1632
+ const jws = {
1633
+ signature: encode2(signature),
1634
+ payload: payloadS
1635
+ };
1636
+ if (this.#unprotectedHeader) {
1637
+ jws.header = this.#unprotectedHeader;
1638
+ }
1639
+ if (this.#protectedHeader) {
1640
+ jws.protected = protectedHeaderString;
1641
+ }
1642
+ return jws;
1643
+ }
1644
+ }
1645
+
1646
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jws/compact/sign.js
1647
+ class CompactSign {
1648
+ #flattened;
1649
+ constructor(payload) {
1650
+ this.#flattened = new FlattenedSign(payload);
1651
+ }
1652
+ setProtectedHeader(protectedHeader) {
1653
+ this.#flattened.setProtectedHeader(protectedHeader);
1654
+ return this;
1655
+ }
1656
+ async sign(key, options) {
1657
+ const jws = await this.#flattened.sign(key, options);
1658
+ if (jws.payload === undefined) {
1659
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
1660
+ }
1661
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
1662
+ }
1663
+ }
1664
+
1665
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jwt/sign.js
1666
+ class SignJWT {
1667
+ #protectedHeader;
1668
+ #jwt;
1669
+ constructor(payload = {}) {
1670
+ this.#jwt = new JWTClaimsBuilder(payload);
1671
+ }
1672
+ setIssuer(issuer) {
1673
+ this.#jwt.iss = issuer;
1674
+ return this;
1675
+ }
1676
+ setSubject(subject) {
1677
+ this.#jwt.sub = subject;
1678
+ return this;
1679
+ }
1680
+ setAudience(audience) {
1681
+ this.#jwt.aud = audience;
1682
+ return this;
1683
+ }
1684
+ setJti(jwtId) {
1685
+ this.#jwt.jti = jwtId;
1686
+ return this;
1687
+ }
1688
+ setNotBefore(input) {
1689
+ this.#jwt.nbf = input;
1690
+ return this;
1691
+ }
1692
+ setExpirationTime(input) {
1693
+ this.#jwt.exp = input;
1694
+ return this;
1695
+ }
1696
+ setIssuedAt(input) {
1697
+ this.#jwt.iat = input;
1698
+ return this;
1699
+ }
1700
+ setProtectedHeader(protectedHeader) {
1701
+ this.#protectedHeader = protectedHeader;
1702
+ return this;
1703
+ }
1704
+ async sign(key, options) {
1705
+ const sig = new CompactSign(this.#jwt.data());
1706
+ sig.setProtectedHeader(this.#protectedHeader);
1707
+ if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
1708
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1709
+ }
1710
+ return sig.sign(key, options);
1711
+ }
1712
+ }
1713
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/jwks/local.js
1714
+ function getKtyFromAlg(alg) {
1715
+ switch (typeof alg === "string" && alg.slice(0, 2)) {
1716
+ case "RS":
1717
+ case "PS":
1718
+ return "RSA";
1719
+ case "ES":
1720
+ return "EC";
1721
+ case "Ed":
1722
+ return "OKP";
1723
+ case "ML":
1724
+ return "AKP";
1725
+ default:
1726
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
1727
+ }
1728
+ }
1729
+ function isJWKSLike(jwks) {
1730
+ return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
1731
+ }
1732
+ function isJWKLike(key) {
1733
+ return isObject(key);
1734
+ }
1735
+
1736
+ class LocalJWKSet {
1737
+ #jwks;
1738
+ #cached = new WeakMap;
1739
+ constructor(jwks) {
1740
+ if (!isJWKSLike(jwks)) {
1741
+ throw new JWKSInvalid("JSON Web Key Set malformed");
1742
+ }
1743
+ this.#jwks = structuredClone(jwks);
1744
+ }
1745
+ jwks() {
1746
+ return this.#jwks;
1747
+ }
1748
+ async getKey(protectedHeader, token) {
1749
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
1750
+ const kty = getKtyFromAlg(alg);
1751
+ const candidates = this.#jwks.keys.filter((jwk2) => {
1752
+ let candidate = kty === jwk2.kty;
1753
+ if (candidate && typeof kid === "string") {
1754
+ candidate = kid === jwk2.kid;
1755
+ }
1756
+ if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) {
1757
+ candidate = alg === jwk2.alg;
1758
+ }
1759
+ if (candidate && typeof jwk2.use === "string") {
1760
+ candidate = jwk2.use === "sig";
1761
+ }
1762
+ if (candidate && Array.isArray(jwk2.key_ops)) {
1763
+ candidate = jwk2.key_ops.includes("verify");
1764
+ }
1765
+ if (candidate) {
1766
+ switch (alg) {
1767
+ case "ES256":
1768
+ candidate = jwk2.crv === "P-256";
1769
+ break;
1770
+ case "ES384":
1771
+ candidate = jwk2.crv === "P-384";
1772
+ break;
1773
+ case "ES512":
1774
+ candidate = jwk2.crv === "P-521";
1775
+ break;
1776
+ case "Ed25519":
1777
+ case "EdDSA":
1778
+ candidate = jwk2.crv === "Ed25519";
1779
+ break;
1780
+ }
1781
+ }
1782
+ return candidate;
1783
+ });
1784
+ const { 0: jwk, length } = candidates;
1785
+ if (length === 0) {
1786
+ throw new JWKSNoMatchingKey;
1787
+ }
1788
+ if (length !== 1) {
1789
+ const error = new JWKSMultipleMatchingKeys;
1790
+ const _cached = this.#cached;
1791
+ error[Symbol.asyncIterator] = async function* () {
1792
+ for (const jwk2 of candidates) {
1793
+ try {
1794
+ yield await importWithAlgCache(_cached, jwk2, alg);
1795
+ } catch {}
1796
+ }
1797
+ };
1798
+ throw error;
1799
+ }
1800
+ return importWithAlgCache(this.#cached, jwk, alg);
1801
+ }
1802
+ }
1803
+ async function importWithAlgCache(cache2, jwk, alg) {
1804
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
1805
+ if (cached[alg] === undefined) {
1806
+ const key = await importJWK({ ...jwk, ext: true }, alg);
1807
+ if (key instanceof Uint8Array || key.type !== "public") {
1808
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
1809
+ }
1810
+ cached[alg] = key;
1811
+ }
1812
+ return cached[alg];
1813
+ }
1814
+ function createLocalJWKSet(jwks) {
1815
+ const set = new LocalJWKSet(jwks);
1816
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1817
+ Object.defineProperties(localJWKSet, {
1818
+ jwks: {
1819
+ value: () => structuredClone(set.jwks()),
1820
+ enumerable: false,
1821
+ configurable: false,
1822
+ writable: false
1823
+ }
1824
+ });
1825
+ return localJWKSet;
1826
+ }
1827
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/util/decode_jwt.js
1828
+ function decodeJwt(jwt) {
1829
+ if (typeof jwt !== "string")
1830
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
1831
+ const { 1: payload, length } = jwt.split(".");
1832
+ if (length === 5)
1833
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
1834
+ if (length !== 3)
1835
+ throw new JWTInvalid("Invalid JWT");
1836
+ if (!payload)
1837
+ throw new JWTInvalid("JWTs must contain a payload");
1838
+ let decoded;
1839
+ try {
1840
+ decoded = decode(payload);
1841
+ } catch {
1842
+ throw new JWTInvalid("Failed to base64url decode the payload");
1843
+ }
1844
+ let result;
1845
+ try {
1846
+ result = JSON.parse(decoder.decode(decoded));
1847
+ } catch {
1848
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
1849
+ }
1850
+ if (!isObject(result))
1851
+ throw new JWTInvalid("Invalid JWT Claims Set");
1852
+ return result;
1853
+ }
1854
+ // node_modules/.pnpm/jose@6.1.3/node_modules/jose/dist/webapi/key/generate_key_pair.js
1855
+ function getModulusLengthOption(options) {
1856
+ const modulusLength = options?.modulusLength ?? 2048;
1857
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
1858
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
1859
+ }
1860
+ return modulusLength;
1861
+ }
1862
+ async function generateKeyPair(alg, options) {
1863
+ let algorithm;
1864
+ let keyUsages;
1865
+ switch (alg) {
1866
+ case "PS256":
1867
+ case "PS384":
1868
+ case "PS512":
1869
+ algorithm = {
1870
+ name: "RSA-PSS",
1871
+ hash: `SHA-${alg.slice(-3)}`,
1872
+ publicExponent: Uint8Array.of(1, 0, 1),
1873
+ modulusLength: getModulusLengthOption(options)
1874
+ };
1875
+ keyUsages = ["sign", "verify"];
1876
+ break;
1877
+ case "RS256":
1878
+ case "RS384":
1879
+ case "RS512":
1880
+ algorithm = {
1881
+ name: "RSASSA-PKCS1-v1_5",
1882
+ hash: `SHA-${alg.slice(-3)}`,
1883
+ publicExponent: Uint8Array.of(1, 0, 1),
1884
+ modulusLength: getModulusLengthOption(options)
1885
+ };
1886
+ keyUsages = ["sign", "verify"];
1887
+ break;
1888
+ case "RSA-OAEP":
1889
+ case "RSA-OAEP-256":
1890
+ case "RSA-OAEP-384":
1891
+ case "RSA-OAEP-512":
1892
+ algorithm = {
1893
+ name: "RSA-OAEP",
1894
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
1895
+ publicExponent: Uint8Array.of(1, 0, 1),
1896
+ modulusLength: getModulusLengthOption(options)
1897
+ };
1898
+ keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
1899
+ break;
1900
+ case "ES256":
1901
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
1902
+ keyUsages = ["sign", "verify"];
1903
+ break;
1904
+ case "ES384":
1905
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
1906
+ keyUsages = ["sign", "verify"];
1907
+ break;
1908
+ case "ES512":
1909
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
1910
+ keyUsages = ["sign", "verify"];
1911
+ break;
1912
+ case "Ed25519":
1913
+ case "EdDSA": {
1914
+ keyUsages = ["sign", "verify"];
1915
+ algorithm = { name: "Ed25519" };
1916
+ break;
1917
+ }
1918
+ case "ML-DSA-44":
1919
+ case "ML-DSA-65":
1920
+ case "ML-DSA-87": {
1921
+ keyUsages = ["sign", "verify"];
1922
+ algorithm = { name: alg };
1923
+ break;
1924
+ }
1925
+ case "ECDH-ES":
1926
+ case "ECDH-ES+A128KW":
1927
+ case "ECDH-ES+A192KW":
1928
+ case "ECDH-ES+A256KW": {
1929
+ keyUsages = ["deriveBits"];
1930
+ const crv = options?.crv ?? "P-256";
1931
+ switch (crv) {
1932
+ case "P-256":
1933
+ case "P-384":
1934
+ case "P-521": {
1935
+ algorithm = { name: "ECDH", namedCurve: crv };
1936
+ break;
1937
+ }
1938
+ case "X25519":
1939
+ algorithm = { name: "X25519" };
1940
+ break;
1941
+ default:
1942
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
1943
+ }
1944
+ break;
1945
+ }
1946
+ default:
1947
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1948
+ }
1949
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
1950
+ }
1951
+ // src/auth.ts
1952
+ async function verifyJWT(token, publicKey) {
1953
+ try {
1954
+ let key;
1955
+ if (typeof publicKey === "string") {
1956
+ key = await importSPKI(publicKey, "RS256");
1957
+ } else if (typeof publicKey === "object" && publicKey !== null && "keys" in publicKey) {
1958
+ key = createLocalJWKSet(publicKey);
1959
+ } else {
1960
+ key = publicKey;
1961
+ }
1962
+ const { payload } = await jwtVerify(token, key, {
1963
+ algorithms: ["RS256"]
1964
+ });
1965
+ return payload;
1966
+ } catch (error) {
1967
+ if (error instanceof exports_errors.JWTExpired) {
1968
+ console.error("JWT has expired:");
1969
+ throw new Error("Token has expired");
1970
+ }
1971
+ console.error("JWT verification failed:", error);
1972
+ throw new Error("Invalid token");
1973
+ }
1974
+ }
1975
+ async function signJWT(payload, privateKey) {
1976
+ const expirationTime = Math.floor(Date.now() / 1000) + 2 * 60 * 60;
1977
+ if (!payload.exp) {
1978
+ payload.exp = expirationTime;
1979
+ }
1980
+ let cryptoKey;
1981
+ if (typeof privateKey === "string") {
1982
+ cryptoKey = await importPKCS8(privateKey, "RS256");
1983
+ } else if (typeof privateKey === "object" && privateKey !== null && "kty" in privateKey) {
1984
+ cryptoKey = await importJWK(privateKey, "RS256");
1985
+ } else {
1986
+ cryptoKey = privateKey;
1987
+ }
1988
+ const iss = payload.iss || "https://convex.kevisual.cn";
1989
+ if (!payload.iss) {
1990
+ payload.iss = iss;
1991
+ }
1992
+ if (!payload.iat) {
1993
+ payload.iat = Math.floor(Date.now() / 1000);
1994
+ }
1995
+ if (!payload.aud) {
1996
+ payload.aud = "convex-app";
1997
+ }
1998
+ const token = await new SignJWT(payload).setProtectedHeader({
1999
+ alg: "RS256",
2000
+ typ: "JWT",
2001
+ kid: "kid-key-1"
2002
+ }).setIssuedAt().setExpirationTime(payload.exp).setIssuer(iss).setSubject(payload.sub || "").sign(cryptoKey);
2003
+ return token;
2004
+ }
2005
+ var decodeJWT = (token) => {
2006
+ try {
2007
+ const decoded = decodeJwt(token);
2008
+ return decoded;
2009
+ } catch (error) {
2010
+ throw new Error("Invalid token");
2011
+ }
2012
+ };
2013
+ // src/generate.ts
2014
+ async function generateKeyPair2() {
2015
+ const { privateKey, publicKey } = await generateKeyPair("RS256", {
2016
+ modulusLength: 2048,
2017
+ extractable: true
2018
+ });
2019
+ return { privateKey, publicKey };
2020
+ }
2021
+ async function createJWKS(publicKey, kid) {
2022
+ const jwk = await exportJWK(publicKey);
2023
+ jwk.kid = kid || "kid-key-1";
2024
+ const jwks = {
2025
+ keys: [jwk]
2026
+ };
2027
+ return jwks;
2028
+ }
2029
+ var generate = async (opts = {}) => {
2030
+ const { privateKey, publicKey } = await generateKeyPair2();
2031
+ const jwks = await createJWKS(publicKey, opts.kid);
2032
+ const privateJWK = await exportJWK(privateKey);
2033
+ const privatePEM = await exportPKCS8(privateKey);
2034
+ const publicPEM = await exportSPKI(publicKey);
2035
+ return {
2036
+ jwks,
2037
+ privateJWK,
2038
+ privatePEM,
2039
+ publicPEM
2040
+ };
2041
+ };
2042
+ // node_modules/.pnpm/@kevisual+query@0.0.38/node_modules/@kevisual/query/dist/query.js
2043
+ var isTextForContentType = (contentType) => {
2044
+ if (!contentType)
2045
+ return false;
2046
+ const textTypes = ["text/", "xml", "html", "javascript", "css", "csv", "plain", "x-www-form-urlencoded", "md"];
2047
+ return textTypes.some((type) => contentType.includes(type));
2048
+ };
2049
+ var adapter = async (opts = {}, overloadOpts) => {
2050
+ const controller = new AbortController;
2051
+ const signal = controller.signal;
2052
+ const isPostFile = opts.isPostFile || false;
2053
+ let responseType = opts.responseType || "json";
2054
+ if (opts.isBlob) {
2055
+ responseType = "blob";
2056
+ } else if (opts.isText) {
2057
+ responseType = "text";
2058
+ }
2059
+ const timeout = opts.timeout || 60000 * 3;
2060
+ const timer = setTimeout(() => {
2061
+ controller.abort();
2062
+ }, timeout);
2063
+ let method = overloadOpts?.method || opts?.method || "POST";
2064
+ let headers = { ...opts?.headers, ...overloadOpts?.headers };
2065
+ let origin = "";
2066
+ let url;
2067
+ if (opts?.url?.startsWith("http")) {
2068
+ url = new URL(opts.url);
2069
+ } else {
2070
+ origin = window?.location?.origin || "http://localhost:51515";
2071
+ url = new URL(opts.url, origin);
2072
+ }
2073
+ const isGet = method === "GET";
2074
+ if (isGet) {
2075
+ let searchParams = new URLSearchParams(opts.body);
2076
+ url.search = searchParams.toString();
2077
+ } else {
2078
+ const params = opts.params || {};
2079
+ const searchParams = new URLSearchParams(params);
2080
+ if (typeof opts.body === "object" && opts.body !== null) {
2081
+ let body2 = opts.body || {};
2082
+ if (!params.path && body2?.path) {
2083
+ searchParams.set("path", body2.path);
2084
+ if (body2?.key) {
2085
+ searchParams.set("key", body2.key);
2086
+ }
2087
+ }
2088
+ }
2089
+ url.search = searchParams.toString();
2090
+ }
2091
+ let body = undefined;
2092
+ if (isGet) {
2093
+ body = undefined;
2094
+ } else if (isPostFile) {
2095
+ body = opts.body;
2096
+ } else {
2097
+ headers = {
2098
+ "Content-Type": "application/json",
2099
+ ...headers
2100
+ };
2101
+ body = JSON.stringify(opts.body);
2102
+ }
2103
+ return fetch(url, {
2104
+ method: method.toUpperCase(),
2105
+ signal,
2106
+ body,
2107
+ ...overloadOpts,
2108
+ headers
2109
+ }).then(async (response) => {
2110
+ const contentType = response.headers.get("Content-Type");
2111
+ if (responseType === "blob") {
2112
+ return await response.blob();
2113
+ }
2114
+ const isText = responseType === "text";
2115
+ const isJson = contentType && contentType.includes("application/json");
2116
+ if (isJson && !isText) {
2117
+ return await response.json();
2118
+ } else if (isTextForContentType(contentType)) {
2119
+ return {
2120
+ code: response.status,
2121
+ status: response.status,
2122
+ data: await response.text()
2123
+ };
2124
+ } else {
2125
+ return response;
2126
+ }
2127
+ }).catch((err) => {
2128
+ if (err.name === "AbortError") {
2129
+ return {
2130
+ code: 408,
2131
+ message: "请求超时"
2132
+ };
2133
+ }
2134
+ return {
2135
+ code: 500,
2136
+ message: err.message || "网络错误"
2137
+ };
2138
+ }).finally(() => {
2139
+ clearTimeout(timer);
2140
+ });
2141
+ };
2142
+ var wrapperError = ({ code, message: message2 }) => {
2143
+ const result = {
2144
+ code: code || 500,
2145
+ success: false,
2146
+ message: message2 || "api request error",
2147
+ showError: (fn) => {},
2148
+ noMsg: true
2149
+ };
2150
+ return result;
2151
+ };
2152
+
2153
+ class Query {
2154
+ adapter;
2155
+ url;
2156
+ beforeRequest;
2157
+ afterResponse;
2158
+ headers;
2159
+ timeout;
2160
+ stop;
2161
+ qws;
2162
+ isClient = false;
2163
+ constructor(opts) {
2164
+ this.adapter = opts?.adapter || adapter;
2165
+ const defaultURL = opts?.isClient ? "/client/router" : "/api/router";
2166
+ this.url = opts?.url || defaultURL;
2167
+ this.headers = opts?.headers || {
2168
+ "Content-Type": "application/json"
2169
+ };
2170
+ this.timeout = opts?.timeout || 60000 * 3;
2171
+ if (opts.beforeRequest) {
2172
+ this.beforeRequest = opts.beforeRequest;
2173
+ } else {
2174
+ this.beforeRequest = async (opts2) => {
2175
+ const token = globalThis?.localStorage?.getItem("token");
2176
+ if (token) {
2177
+ opts2.headers = {
2178
+ ...opts2.headers,
2179
+ Authorization: `Bearer ${token}`
2180
+ };
2181
+ }
2182
+ return opts2;
2183
+ };
2184
+ }
2185
+ }
2186
+ setQueryWs(qws) {
2187
+ this.qws = qws;
2188
+ }
2189
+ setStop(stop) {
2190
+ this.stop = stop;
2191
+ }
2192
+ async get(params, options) {
2193
+ return this.post(params, options);
2194
+ }
2195
+ async post(body, options) {
2196
+ const url = options?.url || this.url;
2197
+ const { headers, adapter: adapter2, beforeRequest, afterResponse, timeout, ...rest } = options || {};
2198
+ const _headers = { ...this.headers, ...headers };
2199
+ const _adapter = adapter2 || this.adapter;
2200
+ const _beforeRequest = beforeRequest || this.beforeRequest;
2201
+ const _afterResponse = afterResponse || this.afterResponse;
2202
+ const _timeout = timeout || this.timeout;
2203
+ const req = {
2204
+ url,
2205
+ headers: _headers,
2206
+ body,
2207
+ timeout: _timeout,
2208
+ ...rest
2209
+ };
2210
+ try {
2211
+ if (_beforeRequest) {
2212
+ const res = await _beforeRequest(req);
2213
+ if (res === false) {
2214
+ return wrapperError({
2215
+ code: 500,
2216
+ message: "request is cancel",
2217
+ req
2218
+ });
2219
+ }
2220
+ }
2221
+ } catch (e) {
2222
+ console.error("request beforeFn error", e, req);
2223
+ return wrapperError({
2224
+ code: 500,
2225
+ message: "api request beforeFn error"
2226
+ });
2227
+ }
2228
+ if (this.stop && !options?.noStop) {
2229
+ const that = this;
2230
+ await new Promise((resolve) => {
2231
+ let timer = 0;
2232
+ const detect = setInterval(() => {
2233
+ if (!that.stop) {
2234
+ clearInterval(detect);
2235
+ resolve(true);
2236
+ }
2237
+ timer++;
2238
+ if (timer > 30) {
2239
+ console.error("request stop: timeout", req.url, timer);
2240
+ }
2241
+ }, 1000);
2242
+ });
2243
+ }
2244
+ return _adapter(req).then(async (res) => {
2245
+ try {
2246
+ if (_afterResponse) {
2247
+ return await _afterResponse(res, {
2248
+ req,
2249
+ res,
2250
+ fetch: adapter2
2251
+ });
2252
+ }
2253
+ return res;
2254
+ } catch (e) {
2255
+ console.error("request afterFn error", e, req);
2256
+ return wrapperError({
2257
+ code: 500,
2258
+ message: "api request afterFn error"
2259
+ });
2260
+ }
2261
+ });
2262
+ }
2263
+ before(fn) {
2264
+ this.beforeRequest = fn;
2265
+ }
2266
+ after(fn) {
2267
+ this.afterResponse = fn;
2268
+ }
2269
+ async fetchText(urlOrOptions, options) {
2270
+ let _options = { ...options };
2271
+ if (typeof urlOrOptions === "string" && !_options.url) {
2272
+ _options.url = urlOrOptions;
2273
+ }
2274
+ if (typeof urlOrOptions === "object") {
2275
+ _options = { ...urlOrOptions, ..._options };
2276
+ }
2277
+ const res = await adapter({
2278
+ method: "GET",
2279
+ ..._options,
2280
+ headers: {
2281
+ ...this.headers,
2282
+ ..._options?.headers || {}
2283
+ }
2284
+ });
2285
+ if (res && !res.code) {
2286
+ return {
2287
+ code: 200,
2288
+ data: res
2289
+ };
2290
+ }
2291
+ return res;
2292
+ }
2293
+ }
2294
+
2295
+ // node_modules/.pnpm/lru-cache@11.2.4/node_modules/lru-cache/dist/esm/index.js
2296
+ var defaultPerf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
2297
+ var warned = new Set;
2298
+ var PROCESS = typeof process === "object" && !!process ? process : {};
2299
+ var emitWarning = (msg, type, code, fn) => {
2300
+ typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
2301
+ };
2302
+ var AC = globalThis.AbortController;
2303
+ var AS = globalThis.AbortSignal;
2304
+ if (typeof AC === "undefined") {
2305
+ AS = class AbortSignal {
2306
+ onabort;
2307
+ _onabort = [];
2308
+ reason;
2309
+ aborted = false;
2310
+ addEventListener(_, fn) {
2311
+ this._onabort.push(fn);
2312
+ }
2313
+ };
2314
+ AC = class AbortController2 {
2315
+ constructor() {
2316
+ warnACPolyfill();
2317
+ }
2318
+ signal = new AS;
2319
+ abort(reason) {
2320
+ if (this.signal.aborted)
2321
+ return;
2322
+ this.signal.reason = reason;
2323
+ this.signal.aborted = true;
2324
+ for (const fn of this.signal._onabort) {
2325
+ fn(reason);
2326
+ }
2327
+ this.signal.onabort?.(reason);
2328
+ }
2329
+ };
2330
+ let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
2331
+ const warnACPolyfill = () => {
2332
+ if (!printACPolyfillWarning)
2333
+ return;
2334
+ printACPolyfillWarning = false;
2335
+ emitWarning("AbortController is not defined. If using lru-cache in " + "node 14, load an AbortController polyfill from the " + "`node-abort-controller` package. A minimal polyfill is " + "provided for use by LRUCache.fetch(), but it should not be " + "relied upon in other contexts (eg, passing it to other APIs that " + "use AbortController/AbortSignal might have undesirable effects). " + "You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
2336
+ };
2337
+ }
2338
+ var shouldWarn = (code) => !warned.has(code);
2339
+ var TYPE = Symbol("type");
2340
+ var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
2341
+ var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
2342
+
2343
+ class ZeroArray extends Array {
2344
+ constructor(size) {
2345
+ super(size);
2346
+ this.fill(0);
2347
+ }
2348
+ }
2349
+
2350
+ class Stack {
2351
+ heap;
2352
+ length;
2353
+ static #constructing = false;
2354
+ static create(max) {
2355
+ const HeapCls = getUintArray(max);
2356
+ if (!HeapCls)
2357
+ return [];
2358
+ Stack.#constructing = true;
2359
+ const s = new Stack(max, HeapCls);
2360
+ Stack.#constructing = false;
2361
+ return s;
2362
+ }
2363
+ constructor(max, HeapCls) {
2364
+ if (!Stack.#constructing) {
2365
+ throw new TypeError("instantiate Stack using Stack.create(n)");
2366
+ }
2367
+ this.heap = new HeapCls(max);
2368
+ this.length = 0;
2369
+ }
2370
+ push(n) {
2371
+ this.heap[this.length++] = n;
2372
+ }
2373
+ pop() {
2374
+ return this.heap[--this.length];
2375
+ }
2376
+ }
2377
+
2378
+ class LRUCache {
2379
+ #max;
2380
+ #maxSize;
2381
+ #dispose;
2382
+ #onInsert;
2383
+ #disposeAfter;
2384
+ #fetchMethod;
2385
+ #memoMethod;
2386
+ #perf;
2387
+ get perf() {
2388
+ return this.#perf;
2389
+ }
2390
+ ttl;
2391
+ ttlResolution;
2392
+ ttlAutopurge;
2393
+ updateAgeOnGet;
2394
+ updateAgeOnHas;
2395
+ allowStale;
2396
+ noDisposeOnSet;
2397
+ noUpdateTTL;
2398
+ maxEntrySize;
2399
+ sizeCalculation;
2400
+ noDeleteOnFetchRejection;
2401
+ noDeleteOnStaleGet;
2402
+ allowStaleOnFetchAbort;
2403
+ allowStaleOnFetchRejection;
2404
+ ignoreFetchAbort;
2405
+ #size;
2406
+ #calculatedSize;
2407
+ #keyMap;
2408
+ #keyList;
2409
+ #valList;
2410
+ #next;
2411
+ #prev;
2412
+ #head;
2413
+ #tail;
2414
+ #free;
2415
+ #disposed;
2416
+ #sizes;
2417
+ #starts;
2418
+ #ttls;
2419
+ #autopurgeTimers;
2420
+ #hasDispose;
2421
+ #hasFetchMethod;
2422
+ #hasDisposeAfter;
2423
+ #hasOnInsert;
2424
+ static unsafeExposeInternals(c) {
2425
+ return {
2426
+ starts: c.#starts,
2427
+ ttls: c.#ttls,
2428
+ autopurgeTimers: c.#autopurgeTimers,
2429
+ sizes: c.#sizes,
2430
+ keyMap: c.#keyMap,
2431
+ keyList: c.#keyList,
2432
+ valList: c.#valList,
2433
+ next: c.#next,
2434
+ prev: c.#prev,
2435
+ get head() {
2436
+ return c.#head;
2437
+ },
2438
+ get tail() {
2439
+ return c.#tail;
2440
+ },
2441
+ free: c.#free,
2442
+ isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
2443
+ backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
2444
+ moveToTail: (index) => c.#moveToTail(index),
2445
+ indexes: (options) => c.#indexes(options),
2446
+ rindexes: (options) => c.#rindexes(options),
2447
+ isStale: (index) => c.#isStale(index)
2448
+ };
2449
+ }
2450
+ get max() {
2451
+ return this.#max;
2452
+ }
2453
+ get maxSize() {
2454
+ return this.#maxSize;
2455
+ }
2456
+ get calculatedSize() {
2457
+ return this.#calculatedSize;
2458
+ }
2459
+ get size() {
2460
+ return this.#size;
2461
+ }
2462
+ get fetchMethod() {
2463
+ return this.#fetchMethod;
2464
+ }
2465
+ get memoMethod() {
2466
+ return this.#memoMethod;
2467
+ }
2468
+ get dispose() {
2469
+ return this.#dispose;
2470
+ }
2471
+ get onInsert() {
2472
+ return this.#onInsert;
2473
+ }
2474
+ get disposeAfter() {
2475
+ return this.#disposeAfter;
2476
+ }
2477
+ constructor(options) {
2478
+ const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, perf } = options;
2479
+ if (perf !== undefined) {
2480
+ if (typeof perf?.now !== "function") {
2481
+ throw new TypeError("perf option must have a now() method if specified");
2482
+ }
2483
+ }
2484
+ this.#perf = perf ?? defaultPerf;
2485
+ if (max !== 0 && !isPosInt(max)) {
2486
+ throw new TypeError("max option must be a nonnegative integer");
2487
+ }
2488
+ const UintArray = max ? getUintArray(max) : Array;
2489
+ if (!UintArray) {
2490
+ throw new Error("invalid max value: " + max);
2491
+ }
2492
+ this.#max = max;
2493
+ this.#maxSize = maxSize;
2494
+ this.maxEntrySize = maxEntrySize || this.#maxSize;
2495
+ this.sizeCalculation = sizeCalculation;
2496
+ if (this.sizeCalculation) {
2497
+ if (!this.#maxSize && !this.maxEntrySize) {
2498
+ throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
2499
+ }
2500
+ if (typeof this.sizeCalculation !== "function") {
2501
+ throw new TypeError("sizeCalculation set to non-function");
2502
+ }
2503
+ }
2504
+ if (memoMethod !== undefined && typeof memoMethod !== "function") {
2505
+ throw new TypeError("memoMethod must be a function if defined");
2506
+ }
2507
+ this.#memoMethod = memoMethod;
2508
+ if (fetchMethod !== undefined && typeof fetchMethod !== "function") {
2509
+ throw new TypeError("fetchMethod must be a function if specified");
2510
+ }
2511
+ this.#fetchMethod = fetchMethod;
2512
+ this.#hasFetchMethod = !!fetchMethod;
2513
+ this.#keyMap = new Map;
2514
+ this.#keyList = new Array(max).fill(undefined);
2515
+ this.#valList = new Array(max).fill(undefined);
2516
+ this.#next = new UintArray(max);
2517
+ this.#prev = new UintArray(max);
2518
+ this.#head = 0;
2519
+ this.#tail = 0;
2520
+ this.#free = Stack.create(max);
2521
+ this.#size = 0;
2522
+ this.#calculatedSize = 0;
2523
+ if (typeof dispose === "function") {
2524
+ this.#dispose = dispose;
2525
+ }
2526
+ if (typeof onInsert === "function") {
2527
+ this.#onInsert = onInsert;
2528
+ }
2529
+ if (typeof disposeAfter === "function") {
2530
+ this.#disposeAfter = disposeAfter;
2531
+ this.#disposed = [];
2532
+ } else {
2533
+ this.#disposeAfter = undefined;
2534
+ this.#disposed = undefined;
2535
+ }
2536
+ this.#hasDispose = !!this.#dispose;
2537
+ this.#hasOnInsert = !!this.#onInsert;
2538
+ this.#hasDisposeAfter = !!this.#disposeAfter;
2539
+ this.noDisposeOnSet = !!noDisposeOnSet;
2540
+ this.noUpdateTTL = !!noUpdateTTL;
2541
+ this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
2542
+ this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
2543
+ this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
2544
+ this.ignoreFetchAbort = !!ignoreFetchAbort;
2545
+ if (this.maxEntrySize !== 0) {
2546
+ if (this.#maxSize !== 0) {
2547
+ if (!isPosInt(this.#maxSize)) {
2548
+ throw new TypeError("maxSize must be a positive integer if specified");
2549
+ }
2550
+ }
2551
+ if (!isPosInt(this.maxEntrySize)) {
2552
+ throw new TypeError("maxEntrySize must be a positive integer if specified");
2553
+ }
2554
+ this.#initializeSizeTracking();
2555
+ }
2556
+ this.allowStale = !!allowStale;
2557
+ this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
2558
+ this.updateAgeOnGet = !!updateAgeOnGet;
2559
+ this.updateAgeOnHas = !!updateAgeOnHas;
2560
+ this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
2561
+ this.ttlAutopurge = !!ttlAutopurge;
2562
+ this.ttl = ttl || 0;
2563
+ if (this.ttl) {
2564
+ if (!isPosInt(this.ttl)) {
2565
+ throw new TypeError("ttl must be a positive integer if specified");
2566
+ }
2567
+ this.#initializeTTLTracking();
2568
+ }
2569
+ if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
2570
+ throw new TypeError("At least one of max, maxSize, or ttl is required");
2571
+ }
2572
+ if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
2573
+ const code = "LRU_CACHE_UNBOUNDED";
2574
+ if (shouldWarn(code)) {
2575
+ warned.add(code);
2576
+ const msg = "TTL caching without ttlAutopurge, max, or maxSize can " + "result in unbounded memory consumption.";
2577
+ emitWarning(msg, "UnboundedCacheWarning", code, LRUCache);
2578
+ }
2579
+ }
2580
+ }
2581
+ getRemainingTTL(key) {
2582
+ return this.#keyMap.has(key) ? Infinity : 0;
2583
+ }
2584
+ #initializeTTLTracking() {
2585
+ const ttls = new ZeroArray(this.#max);
2586
+ const starts = new ZeroArray(this.#max);
2587
+ this.#ttls = ttls;
2588
+ this.#starts = starts;
2589
+ const purgeTimers = this.ttlAutopurge ? new Array(this.#max) : undefined;
2590
+ this.#autopurgeTimers = purgeTimers;
2591
+ this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
2592
+ starts[index] = ttl !== 0 ? start : 0;
2593
+ ttls[index] = ttl;
2594
+ if (purgeTimers?.[index]) {
2595
+ clearTimeout(purgeTimers[index]);
2596
+ purgeTimers[index] = undefined;
2597
+ }
2598
+ if (ttl !== 0 && purgeTimers) {
2599
+ const t = setTimeout(() => {
2600
+ if (this.#isStale(index)) {
2601
+ this.#delete(this.#keyList[index], "expire");
2602
+ }
2603
+ }, ttl + 1);
2604
+ if (t.unref) {
2605
+ t.unref();
2606
+ }
2607
+ purgeTimers[index] = t;
2608
+ }
2609
+ };
2610
+ this.#updateItemAge = (index) => {
2611
+ starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0;
2612
+ };
2613
+ this.#statusTTL = (status, index) => {
2614
+ if (ttls[index]) {
2615
+ const ttl = ttls[index];
2616
+ const start = starts[index];
2617
+ if (!ttl || !start)
2618
+ return;
2619
+ status.ttl = ttl;
2620
+ status.start = start;
2621
+ status.now = cachedNow || getNow();
2622
+ const age = status.now - start;
2623
+ status.remainingTTL = ttl - age;
2624
+ }
2625
+ };
2626
+ let cachedNow = 0;
2627
+ const getNow = () => {
2628
+ const n = this.#perf.now();
2629
+ if (this.ttlResolution > 0) {
2630
+ cachedNow = n;
2631
+ const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
2632
+ if (t.unref) {
2633
+ t.unref();
2634
+ }
2635
+ }
2636
+ return n;
2637
+ };
2638
+ this.getRemainingTTL = (key) => {
2639
+ const index = this.#keyMap.get(key);
2640
+ if (index === undefined) {
2641
+ return 0;
2642
+ }
2643
+ const ttl = ttls[index];
2644
+ const start = starts[index];
2645
+ if (!ttl || !start) {
2646
+ return Infinity;
2647
+ }
2648
+ const age = (cachedNow || getNow()) - start;
2649
+ return ttl - age;
2650
+ };
2651
+ this.#isStale = (index) => {
2652
+ const s = starts[index];
2653
+ const t = ttls[index];
2654
+ return !!t && !!s && (cachedNow || getNow()) - s > t;
2655
+ };
2656
+ }
2657
+ #updateItemAge = () => {};
2658
+ #statusTTL = () => {};
2659
+ #setItemTTL = () => {};
2660
+ #isStale = () => false;
2661
+ #initializeSizeTracking() {
2662
+ const sizes = new ZeroArray(this.#max);
2663
+ this.#calculatedSize = 0;
2664
+ this.#sizes = sizes;
2665
+ this.#removeItemSize = (index) => {
2666
+ this.#calculatedSize -= sizes[index];
2667
+ sizes[index] = 0;
2668
+ };
2669
+ this.#requireSize = (k, v, size, sizeCalculation) => {
2670
+ if (this.#isBackgroundFetch(v)) {
2671
+ return 0;
2672
+ }
2673
+ if (!isPosInt(size)) {
2674
+ if (sizeCalculation) {
2675
+ if (typeof sizeCalculation !== "function") {
2676
+ throw new TypeError("sizeCalculation must be a function");
2677
+ }
2678
+ size = sizeCalculation(v, k);
2679
+ if (!isPosInt(size)) {
2680
+ throw new TypeError("sizeCalculation return invalid (expect positive integer)");
2681
+ }
2682
+ } else {
2683
+ throw new TypeError("invalid size value (must be positive integer). " + "When maxSize or maxEntrySize is used, sizeCalculation " + "or size must be set.");
2684
+ }
2685
+ }
2686
+ return size;
2687
+ };
2688
+ this.#addItemSize = (index, size, status) => {
2689
+ sizes[index] = size;
2690
+ if (this.#maxSize) {
2691
+ const maxSize = this.#maxSize - sizes[index];
2692
+ while (this.#calculatedSize > maxSize) {
2693
+ this.#evict(true);
2694
+ }
2695
+ }
2696
+ this.#calculatedSize += sizes[index];
2697
+ if (status) {
2698
+ status.entrySize = size;
2699
+ status.totalCalculatedSize = this.#calculatedSize;
2700
+ }
2701
+ };
2702
+ }
2703
+ #removeItemSize = (_i) => {};
2704
+ #addItemSize = (_i, _s, _st) => {};
2705
+ #requireSize = (_k, _v, size, sizeCalculation) => {
2706
+ if (size || sizeCalculation) {
2707
+ throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
2708
+ }
2709
+ return 0;
2710
+ };
2711
+ *#indexes({ allowStale = this.allowStale } = {}) {
2712
+ if (this.#size) {
2713
+ for (let i = this.#tail;; ) {
2714
+ if (!this.#isValidIndex(i)) {
2715
+ break;
2716
+ }
2717
+ if (allowStale || !this.#isStale(i)) {
2718
+ yield i;
2719
+ }
2720
+ if (i === this.#head) {
2721
+ break;
2722
+ } else {
2723
+ i = this.#prev[i];
2724
+ }
2725
+ }
2726
+ }
2727
+ }
2728
+ *#rindexes({ allowStale = this.allowStale } = {}) {
2729
+ if (this.#size) {
2730
+ for (let i = this.#head;; ) {
2731
+ if (!this.#isValidIndex(i)) {
2732
+ break;
2733
+ }
2734
+ if (allowStale || !this.#isStale(i)) {
2735
+ yield i;
2736
+ }
2737
+ if (i === this.#tail) {
2738
+ break;
2739
+ } else {
2740
+ i = this.#next[i];
2741
+ }
2742
+ }
2743
+ }
2744
+ }
2745
+ #isValidIndex(index) {
2746
+ return index !== undefined && this.#keyMap.get(this.#keyList[index]) === index;
2747
+ }
2748
+ *entries() {
2749
+ for (const i of this.#indexes()) {
2750
+ if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2751
+ yield [this.#keyList[i], this.#valList[i]];
2752
+ }
2753
+ }
2754
+ }
2755
+ *rentries() {
2756
+ for (const i of this.#rindexes()) {
2757
+ if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2758
+ yield [this.#keyList[i], this.#valList[i]];
2759
+ }
2760
+ }
2761
+ }
2762
+ *keys() {
2763
+ for (const i of this.#indexes()) {
2764
+ const k = this.#keyList[i];
2765
+ if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2766
+ yield k;
2767
+ }
2768
+ }
2769
+ }
2770
+ *rkeys() {
2771
+ for (const i of this.#rindexes()) {
2772
+ const k = this.#keyList[i];
2773
+ if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2774
+ yield k;
2775
+ }
2776
+ }
2777
+ }
2778
+ *values() {
2779
+ for (const i of this.#indexes()) {
2780
+ const v = this.#valList[i];
2781
+ if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2782
+ yield this.#valList[i];
2783
+ }
2784
+ }
2785
+ }
2786
+ *rvalues() {
2787
+ for (const i of this.#rindexes()) {
2788
+ const v = this.#valList[i];
2789
+ if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
2790
+ yield this.#valList[i];
2791
+ }
2792
+ }
2793
+ }
2794
+ [Symbol.iterator]() {
2795
+ return this.entries();
2796
+ }
2797
+ [Symbol.toStringTag] = "LRUCache";
2798
+ find(fn, getOptions = {}) {
2799
+ for (const i of this.#indexes()) {
2800
+ const v = this.#valList[i];
2801
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
2802
+ if (value === undefined)
2803
+ continue;
2804
+ if (fn(value, this.#keyList[i], this)) {
2805
+ return this.get(this.#keyList[i], getOptions);
2806
+ }
2807
+ }
2808
+ }
2809
+ forEach(fn, thisp = this) {
2810
+ for (const i of this.#indexes()) {
2811
+ const v = this.#valList[i];
2812
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
2813
+ if (value === undefined)
2814
+ continue;
2815
+ fn.call(thisp, value, this.#keyList[i], this);
2816
+ }
2817
+ }
2818
+ rforEach(fn, thisp = this) {
2819
+ for (const i of this.#rindexes()) {
2820
+ const v = this.#valList[i];
2821
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
2822
+ if (value === undefined)
2823
+ continue;
2824
+ fn.call(thisp, value, this.#keyList[i], this);
2825
+ }
2826
+ }
2827
+ purgeStale() {
2828
+ let deleted = false;
2829
+ for (const i of this.#rindexes({ allowStale: true })) {
2830
+ if (this.#isStale(i)) {
2831
+ this.#delete(this.#keyList[i], "expire");
2832
+ deleted = true;
2833
+ }
2834
+ }
2835
+ return deleted;
2836
+ }
2837
+ info(key) {
2838
+ const i = this.#keyMap.get(key);
2839
+ if (i === undefined)
2840
+ return;
2841
+ const v = this.#valList[i];
2842
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
2843
+ if (value === undefined)
2844
+ return;
2845
+ const entry = { value };
2846
+ if (this.#ttls && this.#starts) {
2847
+ const ttl = this.#ttls[i];
2848
+ const start = this.#starts[i];
2849
+ if (ttl && start) {
2850
+ const remain = ttl - (this.#perf.now() - start);
2851
+ entry.ttl = remain;
2852
+ entry.start = Date.now();
2853
+ }
2854
+ }
2855
+ if (this.#sizes) {
2856
+ entry.size = this.#sizes[i];
2857
+ }
2858
+ return entry;
2859
+ }
2860
+ dump() {
2861
+ const arr = [];
2862
+ for (const i of this.#indexes({ allowStale: true })) {
2863
+ const key = this.#keyList[i];
2864
+ const v = this.#valList[i];
2865
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
2866
+ if (value === undefined || key === undefined)
2867
+ continue;
2868
+ const entry = { value };
2869
+ if (this.#ttls && this.#starts) {
2870
+ entry.ttl = this.#ttls[i];
2871
+ const age = this.#perf.now() - this.#starts[i];
2872
+ entry.start = Math.floor(Date.now() - age);
2873
+ }
2874
+ if (this.#sizes) {
2875
+ entry.size = this.#sizes[i];
2876
+ }
2877
+ arr.unshift([key, entry]);
2878
+ }
2879
+ return arr;
2880
+ }
2881
+ load(arr) {
2882
+ this.clear();
2883
+ for (const [key, entry] of arr) {
2884
+ if (entry.start) {
2885
+ const age = Date.now() - entry.start;
2886
+ entry.start = this.#perf.now() - age;
2887
+ }
2888
+ this.set(key, entry.value, entry);
2889
+ }
2890
+ }
2891
+ set(k, v, setOptions = {}) {
2892
+ if (v === undefined) {
2893
+ this.delete(k);
2894
+ return this;
2895
+ }
2896
+ const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
2897
+ let { noUpdateTTL = this.noUpdateTTL } = setOptions;
2898
+ const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
2899
+ if (this.maxEntrySize && size > this.maxEntrySize) {
2900
+ if (status) {
2901
+ status.set = "miss";
2902
+ status.maxEntrySizeExceeded = true;
2903
+ }
2904
+ this.#delete(k, "set");
2905
+ return this;
2906
+ }
2907
+ let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
2908
+ if (index === undefined) {
2909
+ index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
2910
+ this.#keyList[index] = k;
2911
+ this.#valList[index] = v;
2912
+ this.#keyMap.set(k, index);
2913
+ this.#next[this.#tail] = index;
2914
+ this.#prev[index] = this.#tail;
2915
+ this.#tail = index;
2916
+ this.#size++;
2917
+ this.#addItemSize(index, size, status);
2918
+ if (status)
2919
+ status.set = "add";
2920
+ noUpdateTTL = false;
2921
+ if (this.#hasOnInsert) {
2922
+ this.#onInsert?.(v, k, "add");
2923
+ }
2924
+ } else {
2925
+ this.#moveToTail(index);
2926
+ const oldVal = this.#valList[index];
2927
+ if (v !== oldVal) {
2928
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
2929
+ oldVal.__abortController.abort(new Error("replaced"));
2930
+ const { __staleWhileFetching: s } = oldVal;
2931
+ if (s !== undefined && !noDisposeOnSet) {
2932
+ if (this.#hasDispose) {
2933
+ this.#dispose?.(s, k, "set");
2934
+ }
2935
+ if (this.#hasDisposeAfter) {
2936
+ this.#disposed?.push([s, k, "set"]);
2937
+ }
2938
+ }
2939
+ } else if (!noDisposeOnSet) {
2940
+ if (this.#hasDispose) {
2941
+ this.#dispose?.(oldVal, k, "set");
2942
+ }
2943
+ if (this.#hasDisposeAfter) {
2944
+ this.#disposed?.push([oldVal, k, "set"]);
2945
+ }
2946
+ }
2947
+ this.#removeItemSize(index);
2948
+ this.#addItemSize(index, size, status);
2949
+ this.#valList[index] = v;
2950
+ if (status) {
2951
+ status.set = "replace";
2952
+ const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
2953
+ if (oldValue !== undefined)
2954
+ status.oldValue = oldValue;
2955
+ }
2956
+ } else if (status) {
2957
+ status.set = "update";
2958
+ }
2959
+ if (this.#hasOnInsert) {
2960
+ this.onInsert?.(v, k, v === oldVal ? "update" : "replace");
2961
+ }
2962
+ }
2963
+ if (ttl !== 0 && !this.#ttls) {
2964
+ this.#initializeTTLTracking();
2965
+ }
2966
+ if (this.#ttls) {
2967
+ if (!noUpdateTTL) {
2968
+ this.#setItemTTL(index, ttl, start);
2969
+ }
2970
+ if (status)
2971
+ this.#statusTTL(status, index);
2972
+ }
2973
+ if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
2974
+ const dt = this.#disposed;
2975
+ let task;
2976
+ while (task = dt?.shift()) {
2977
+ this.#disposeAfter?.(...task);
2978
+ }
2979
+ }
2980
+ return this;
2981
+ }
2982
+ pop() {
2983
+ try {
2984
+ while (this.#size) {
2985
+ const val = this.#valList[this.#head];
2986
+ this.#evict(true);
2987
+ if (this.#isBackgroundFetch(val)) {
2988
+ if (val.__staleWhileFetching) {
2989
+ return val.__staleWhileFetching;
2990
+ }
2991
+ } else if (val !== undefined) {
2992
+ return val;
2993
+ }
2994
+ }
2995
+ } finally {
2996
+ if (this.#hasDisposeAfter && this.#disposed) {
2997
+ const dt = this.#disposed;
2998
+ let task;
2999
+ while (task = dt?.shift()) {
3000
+ this.#disposeAfter?.(...task);
3001
+ }
3002
+ }
3003
+ }
3004
+ }
3005
+ #evict(free) {
3006
+ const head = this.#head;
3007
+ const k = this.#keyList[head];
3008
+ const v = this.#valList[head];
3009
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
3010
+ v.__abortController.abort(new Error("evicted"));
3011
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
3012
+ if (this.#hasDispose) {
3013
+ this.#dispose?.(v, k, "evict");
3014
+ }
3015
+ if (this.#hasDisposeAfter) {
3016
+ this.#disposed?.push([v, k, "evict"]);
3017
+ }
3018
+ }
3019
+ this.#removeItemSize(head);
3020
+ if (this.#autopurgeTimers?.[head]) {
3021
+ clearTimeout(this.#autopurgeTimers[head]);
3022
+ this.#autopurgeTimers[head] = undefined;
3023
+ }
3024
+ if (free) {
3025
+ this.#keyList[head] = undefined;
3026
+ this.#valList[head] = undefined;
3027
+ this.#free.push(head);
3028
+ }
3029
+ if (this.#size === 1) {
3030
+ this.#head = this.#tail = 0;
3031
+ this.#free.length = 0;
3032
+ } else {
3033
+ this.#head = this.#next[head];
3034
+ }
3035
+ this.#keyMap.delete(k);
3036
+ this.#size--;
3037
+ return head;
3038
+ }
3039
+ has(k, hasOptions = {}) {
3040
+ const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
3041
+ const index = this.#keyMap.get(k);
3042
+ if (index !== undefined) {
3043
+ const v = this.#valList[index];
3044
+ if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) {
3045
+ return false;
3046
+ }
3047
+ if (!this.#isStale(index)) {
3048
+ if (updateAgeOnHas) {
3049
+ this.#updateItemAge(index);
3050
+ }
3051
+ if (status) {
3052
+ status.has = "hit";
3053
+ this.#statusTTL(status, index);
3054
+ }
3055
+ return true;
3056
+ } else if (status) {
3057
+ status.has = "stale";
3058
+ this.#statusTTL(status, index);
3059
+ }
3060
+ } else if (status) {
3061
+ status.has = "miss";
3062
+ }
3063
+ return false;
3064
+ }
3065
+ peek(k, peekOptions = {}) {
3066
+ const { allowStale = this.allowStale } = peekOptions;
3067
+ const index = this.#keyMap.get(k);
3068
+ if (index === undefined || !allowStale && this.#isStale(index)) {
3069
+ return;
3070
+ }
3071
+ const v = this.#valList[index];
3072
+ return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
3073
+ }
3074
+ #backgroundFetch(k, index, options, context) {
3075
+ const v = index === undefined ? undefined : this.#valList[index];
3076
+ if (this.#isBackgroundFetch(v)) {
3077
+ return v;
3078
+ }
3079
+ const ac = new AC;
3080
+ const { signal } = options;
3081
+ signal?.addEventListener("abort", () => ac.abort(signal.reason), {
3082
+ signal: ac.signal
3083
+ });
3084
+ const fetchOpts = {
3085
+ signal: ac.signal,
3086
+ options,
3087
+ context
3088
+ };
3089
+ const cb = (v2, updateCache = false) => {
3090
+ const { aborted } = ac.signal;
3091
+ const ignoreAbort = options.ignoreFetchAbort && v2 !== undefined;
3092
+ if (options.status) {
3093
+ if (aborted && !updateCache) {
3094
+ options.status.fetchAborted = true;
3095
+ options.status.fetchError = ac.signal.reason;
3096
+ if (ignoreAbort)
3097
+ options.status.fetchAbortIgnored = true;
3098
+ } else {
3099
+ options.status.fetchResolved = true;
3100
+ }
3101
+ }
3102
+ if (aborted && !ignoreAbort && !updateCache) {
3103
+ return fetchFail(ac.signal.reason);
3104
+ }
3105
+ const bf2 = p;
3106
+ const vl = this.#valList[index];
3107
+ if (vl === p || ignoreAbort && updateCache && vl === undefined) {
3108
+ if (v2 === undefined) {
3109
+ if (bf2.__staleWhileFetching !== undefined) {
3110
+ this.#valList[index] = bf2.__staleWhileFetching;
3111
+ } else {
3112
+ this.#delete(k, "fetch");
3113
+ }
3114
+ } else {
3115
+ if (options.status)
3116
+ options.status.fetchUpdated = true;
3117
+ this.set(k, v2, fetchOpts.options);
3118
+ }
3119
+ }
3120
+ return v2;
3121
+ };
3122
+ const eb = (er) => {
3123
+ if (options.status) {
3124
+ options.status.fetchRejected = true;
3125
+ options.status.fetchError = er;
3126
+ }
3127
+ return fetchFail(er);
3128
+ };
3129
+ const fetchFail = (er) => {
3130
+ const { aborted } = ac.signal;
3131
+ const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
3132
+ const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
3133
+ const noDelete = allowStale || options.noDeleteOnFetchRejection;
3134
+ const bf2 = p;
3135
+ if (this.#valList[index] === p) {
3136
+ const del = !noDelete || bf2.__staleWhileFetching === undefined;
3137
+ if (del) {
3138
+ this.#delete(k, "fetch");
3139
+ } else if (!allowStaleAborted) {
3140
+ this.#valList[index] = bf2.__staleWhileFetching;
3141
+ }
3142
+ }
3143
+ if (allowStale) {
3144
+ if (options.status && bf2.__staleWhileFetching !== undefined) {
3145
+ options.status.returnedStale = true;
3146
+ }
3147
+ return bf2.__staleWhileFetching;
3148
+ } else if (bf2.__returned === bf2) {
3149
+ throw er;
3150
+ }
3151
+ };
3152
+ const pcall = (res, rej) => {
3153
+ const fmp = this.#fetchMethod?.(k, v, fetchOpts);
3154
+ if (fmp && fmp instanceof Promise) {
3155
+ fmp.then((v2) => res(v2 === undefined ? undefined : v2), rej);
3156
+ }
3157
+ ac.signal.addEventListener("abort", () => {
3158
+ if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
3159
+ res(undefined);
3160
+ if (options.allowStaleOnFetchAbort) {
3161
+ res = (v2) => cb(v2, true);
3162
+ }
3163
+ }
3164
+ });
3165
+ };
3166
+ if (options.status)
3167
+ options.status.fetchDispatched = true;
3168
+ const p = new Promise(pcall).then(cb, eb);
3169
+ const bf = Object.assign(p, {
3170
+ __abortController: ac,
3171
+ __staleWhileFetching: v,
3172
+ __returned: undefined
3173
+ });
3174
+ if (index === undefined) {
3175
+ this.set(k, bf, { ...fetchOpts.options, status: undefined });
3176
+ index = this.#keyMap.get(k);
3177
+ } else {
3178
+ this.#valList[index] = bf;
3179
+ }
3180
+ return bf;
3181
+ }
3182
+ #isBackgroundFetch(p) {
3183
+ if (!this.#hasFetchMethod)
3184
+ return false;
3185
+ const b = p;
3186
+ return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
3187
+ }
3188
+ async fetch(k, fetchOptions = {}) {
3189
+ const {
3190
+ allowStale = this.allowStale,
3191
+ updateAgeOnGet = this.updateAgeOnGet,
3192
+ noDeleteOnStaleGet = this.noDeleteOnStaleGet,
3193
+ ttl = this.ttl,
3194
+ noDisposeOnSet = this.noDisposeOnSet,
3195
+ size = 0,
3196
+ sizeCalculation = this.sizeCalculation,
3197
+ noUpdateTTL = this.noUpdateTTL,
3198
+ noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
3199
+ allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
3200
+ ignoreFetchAbort = this.ignoreFetchAbort,
3201
+ allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
3202
+ context,
3203
+ forceRefresh = false,
3204
+ status,
3205
+ signal
3206
+ } = fetchOptions;
3207
+ if (!this.#hasFetchMethod) {
3208
+ if (status)
3209
+ status.fetch = "get";
3210
+ return this.get(k, {
3211
+ allowStale,
3212
+ updateAgeOnGet,
3213
+ noDeleteOnStaleGet,
3214
+ status
3215
+ });
3216
+ }
3217
+ const options = {
3218
+ allowStale,
3219
+ updateAgeOnGet,
3220
+ noDeleteOnStaleGet,
3221
+ ttl,
3222
+ noDisposeOnSet,
3223
+ size,
3224
+ sizeCalculation,
3225
+ noUpdateTTL,
3226
+ noDeleteOnFetchRejection,
3227
+ allowStaleOnFetchRejection,
3228
+ allowStaleOnFetchAbort,
3229
+ ignoreFetchAbort,
3230
+ status,
3231
+ signal
3232
+ };
3233
+ let index = this.#keyMap.get(k);
3234
+ if (index === undefined) {
3235
+ if (status)
3236
+ status.fetch = "miss";
3237
+ const p = this.#backgroundFetch(k, index, options, context);
3238
+ return p.__returned = p;
3239
+ } else {
3240
+ const v = this.#valList[index];
3241
+ if (this.#isBackgroundFetch(v)) {
3242
+ const stale = allowStale && v.__staleWhileFetching !== undefined;
3243
+ if (status) {
3244
+ status.fetch = "inflight";
3245
+ if (stale)
3246
+ status.returnedStale = true;
3247
+ }
3248
+ return stale ? v.__staleWhileFetching : v.__returned = v;
3249
+ }
3250
+ const isStale = this.#isStale(index);
3251
+ if (!forceRefresh && !isStale) {
3252
+ if (status)
3253
+ status.fetch = "hit";
3254
+ this.#moveToTail(index);
3255
+ if (updateAgeOnGet) {
3256
+ this.#updateItemAge(index);
3257
+ }
3258
+ if (status)
3259
+ this.#statusTTL(status, index);
3260
+ return v;
3261
+ }
3262
+ const p = this.#backgroundFetch(k, index, options, context);
3263
+ const hasStale = p.__staleWhileFetching !== undefined;
3264
+ const staleVal = hasStale && allowStale;
3265
+ if (status) {
3266
+ status.fetch = isStale ? "stale" : "refresh";
3267
+ if (staleVal && isStale)
3268
+ status.returnedStale = true;
3269
+ }
3270
+ return staleVal ? p.__staleWhileFetching : p.__returned = p;
3271
+ }
3272
+ }
3273
+ async forceFetch(k, fetchOptions = {}) {
3274
+ const v = await this.fetch(k, fetchOptions);
3275
+ if (v === undefined)
3276
+ throw new Error("fetch() returned undefined");
3277
+ return v;
3278
+ }
3279
+ memo(k, memoOptions = {}) {
3280
+ const memoMethod = this.#memoMethod;
3281
+ if (!memoMethod) {
3282
+ throw new Error("no memoMethod provided to constructor");
3283
+ }
3284
+ const { context, forceRefresh, ...options } = memoOptions;
3285
+ const v = this.get(k, options);
3286
+ if (!forceRefresh && v !== undefined)
3287
+ return v;
3288
+ const vv = memoMethod(k, v, {
3289
+ options,
3290
+ context
3291
+ });
3292
+ this.set(k, vv, options);
3293
+ return vv;
3294
+ }
3295
+ get(k, getOptions = {}) {
3296
+ const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
3297
+ const index = this.#keyMap.get(k);
3298
+ if (index !== undefined) {
3299
+ const value = this.#valList[index];
3300
+ const fetching = this.#isBackgroundFetch(value);
3301
+ if (status)
3302
+ this.#statusTTL(status, index);
3303
+ if (this.#isStale(index)) {
3304
+ if (status)
3305
+ status.get = "stale";
3306
+ if (!fetching) {
3307
+ if (!noDeleteOnStaleGet) {
3308
+ this.#delete(k, "expire");
3309
+ }
3310
+ if (status && allowStale)
3311
+ status.returnedStale = true;
3312
+ return allowStale ? value : undefined;
3313
+ } else {
3314
+ if (status && allowStale && value.__staleWhileFetching !== undefined) {
3315
+ status.returnedStale = true;
3316
+ }
3317
+ return allowStale ? value.__staleWhileFetching : undefined;
3318
+ }
3319
+ } else {
3320
+ if (status)
3321
+ status.get = "hit";
3322
+ if (fetching) {
3323
+ return value.__staleWhileFetching;
3324
+ }
3325
+ this.#moveToTail(index);
3326
+ if (updateAgeOnGet) {
3327
+ this.#updateItemAge(index);
3328
+ }
3329
+ return value;
3330
+ }
3331
+ } else if (status) {
3332
+ status.get = "miss";
3333
+ }
3334
+ }
3335
+ #connect(p, n) {
3336
+ this.#prev[n] = p;
3337
+ this.#next[p] = n;
3338
+ }
3339
+ #moveToTail(index) {
3340
+ if (index !== this.#tail) {
3341
+ if (index === this.#head) {
3342
+ this.#head = this.#next[index];
3343
+ } else {
3344
+ this.#connect(this.#prev[index], this.#next[index]);
3345
+ }
3346
+ this.#connect(this.#tail, index);
3347
+ this.#tail = index;
3348
+ }
3349
+ }
3350
+ delete(k) {
3351
+ return this.#delete(k, "delete");
3352
+ }
3353
+ #delete(k, reason) {
3354
+ let deleted = false;
3355
+ if (this.#size !== 0) {
3356
+ const index = this.#keyMap.get(k);
3357
+ if (index !== undefined) {
3358
+ if (this.#autopurgeTimers?.[index]) {
3359
+ clearTimeout(this.#autopurgeTimers?.[index]);
3360
+ this.#autopurgeTimers[index] = undefined;
3361
+ }
3362
+ deleted = true;
3363
+ if (this.#size === 1) {
3364
+ this.#clear(reason);
3365
+ } else {
3366
+ this.#removeItemSize(index);
3367
+ const v = this.#valList[index];
3368
+ if (this.#isBackgroundFetch(v)) {
3369
+ v.__abortController.abort(new Error("deleted"));
3370
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
3371
+ if (this.#hasDispose) {
3372
+ this.#dispose?.(v, k, reason);
3373
+ }
3374
+ if (this.#hasDisposeAfter) {
3375
+ this.#disposed?.push([v, k, reason]);
3376
+ }
3377
+ }
3378
+ this.#keyMap.delete(k);
3379
+ this.#keyList[index] = undefined;
3380
+ this.#valList[index] = undefined;
3381
+ if (index === this.#tail) {
3382
+ this.#tail = this.#prev[index];
3383
+ } else if (index === this.#head) {
3384
+ this.#head = this.#next[index];
3385
+ } else {
3386
+ const pi = this.#prev[index];
3387
+ this.#next[pi] = this.#next[index];
3388
+ const ni = this.#next[index];
3389
+ this.#prev[ni] = this.#prev[index];
3390
+ }
3391
+ this.#size--;
3392
+ this.#free.push(index);
3393
+ }
3394
+ }
3395
+ }
3396
+ if (this.#hasDisposeAfter && this.#disposed?.length) {
3397
+ const dt = this.#disposed;
3398
+ let task;
3399
+ while (task = dt?.shift()) {
3400
+ this.#disposeAfter?.(...task);
3401
+ }
3402
+ }
3403
+ return deleted;
3404
+ }
3405
+ clear() {
3406
+ return this.#clear("delete");
3407
+ }
3408
+ #clear(reason) {
3409
+ for (const index of this.#rindexes({ allowStale: true })) {
3410
+ const v = this.#valList[index];
3411
+ if (this.#isBackgroundFetch(v)) {
3412
+ v.__abortController.abort(new Error("deleted"));
3413
+ } else {
3414
+ const k = this.#keyList[index];
3415
+ if (this.#hasDispose) {
3416
+ this.#dispose?.(v, k, reason);
3417
+ }
3418
+ if (this.#hasDisposeAfter) {
3419
+ this.#disposed?.push([v, k, reason]);
3420
+ }
3421
+ }
3422
+ }
3423
+ this.#keyMap.clear();
3424
+ this.#valList.fill(undefined);
3425
+ this.#keyList.fill(undefined);
3426
+ if (this.#ttls && this.#starts) {
3427
+ this.#ttls.fill(0);
3428
+ this.#starts.fill(0);
3429
+ for (const t of this.#autopurgeTimers ?? []) {
3430
+ if (t !== undefined)
3431
+ clearTimeout(t);
3432
+ }
3433
+ this.#autopurgeTimers?.fill(undefined);
3434
+ }
3435
+ if (this.#sizes) {
3436
+ this.#sizes.fill(0);
3437
+ }
3438
+ this.#head = 0;
3439
+ this.#tail = 0;
3440
+ this.#free.length = 0;
3441
+ this.#calculatedSize = 0;
3442
+ this.#size = 0;
3443
+ if (this.#hasDisposeAfter && this.#disposed) {
3444
+ const dt = this.#disposed;
3445
+ let task;
3446
+ while (task = dt?.shift()) {
3447
+ this.#disposeAfter?.(...task);
3448
+ }
3449
+ }
3450
+ }
3451
+ }
3452
+
3453
+ // src/query.ts
3454
+ class AuthQuery extends Query {
3455
+ cache;
3456
+ constructor(opts = {}) {
3457
+ if (!opts.url) {
3458
+ opts.url = "https://kevisual.cn/api/router/";
3459
+ }
3460
+ super(opts);
3461
+ this.cache = new LRUCache({
3462
+ max: 1e4,
3463
+ ttl: 1000 * 60 * 60 * 2
3464
+ });
3465
+ }
3466
+ getTokenUser = async (token) => {
3467
+ const res = await this.post({
3468
+ path: "user",
3469
+ key: "me",
3470
+ token
3471
+ });
3472
+ return res;
3473
+ };
3474
+ getTokenUserCache = async (token) => {
3475
+ const tokenUser = await this.cache.get(token);
3476
+ if (tokenUser) {
3477
+ return {
3478
+ code: 200,
3479
+ data: tokenUser
3480
+ };
3481
+ }
3482
+ const res = await this.getTokenUser(token);
3483
+ if (res.code === 200) {
3484
+ this.cache.set(token, res.data);
3485
+ }
3486
+ return res;
3487
+ };
3488
+ }
3489
+ export {
3490
+ verifyJWT,
3491
+ signJWT,
3492
+ generate,
3493
+ decodeJWT,
3494
+ AuthQuery
3495
+ };