houdini 1.2.9 → 1.2.11

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.
Files changed (37) hide show
  1. package/build/cmd-cjs/index.js +14968 -150
  2. package/build/cmd-esm/index.js +14970 -152
  3. package/build/codegen-cjs/index.js +14887 -72
  4. package/build/codegen-esm/index.js +14889 -74
  5. package/build/lib/config.d.ts +1 -0
  6. package/build/lib/index.d.ts +1 -0
  7. package/build/lib/types.d.ts +14 -3
  8. package/build/lib-cjs/index.js +15484 -87
  9. package/build/lib-esm/index.js +15481 -89
  10. package/build/router/conventions.d.ts +25 -0
  11. package/build/router/index.d.ts +8 -0
  12. package/build/router/manifest.d.ts +45 -0
  13. package/build/router/types.d.ts +9 -0
  14. package/build/router-cjs/index.js +72353 -0
  15. package/build/router-cjs/package.json +1 -0
  16. package/build/router-esm/index.js +72345 -0
  17. package/build/router-esm/package.json +1 -0
  18. package/build/runtime/router/cookies.d.ts +41 -0
  19. package/build/runtime/router/jwt.d.ts +117 -0
  20. package/build/runtime/router/server.d.ts +25 -0
  21. package/build/runtime-cjs/router/cookies.d.ts +41 -0
  22. package/build/runtime-cjs/router/cookies.js +168 -0
  23. package/build/runtime-cjs/router/jwt.d.ts +117 -0
  24. package/build/runtime-cjs/router/jwt.js +181 -0
  25. package/build/runtime-cjs/router/server.d.ts +25 -0
  26. package/build/runtime-cjs/router/server.js +78 -0
  27. package/build/runtime-esm/router/cookies.d.ts +41 -0
  28. package/build/runtime-esm/router/cookies.js +143 -0
  29. package/build/runtime-esm/router/jwt.d.ts +117 -0
  30. package/build/runtime-esm/router/jwt.js +155 -0
  31. package/build/runtime-esm/router/server.d.ts +25 -0
  32. package/build/runtime-esm/router/server.js +53 -0
  33. package/build/test-cjs/index.js +14891 -73
  34. package/build/test-esm/index.js +14893 -75
  35. package/build/vite-cjs/index.js +15105 -101
  36. package/build/vite-esm/index.js +15107 -103
  37. package/package.json +10 -1
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,41 @@
1
+ /*!
2
+ * cookie
3
+ * Copyright(c) 2012-2014 Roman Shtylman
4
+ * Copyright(c) 2015 Douglas Christopher Wilson
5
+ * MIT Licensed
6
+ */
7
+ /**
8
+ * Parse a cookie header.
9
+ *
10
+ * Parse the given cookie header string into an object
11
+ * The object has the various cookies as keys(names) => values
12
+ *
13
+ * @param {string} str
14
+ * @param {object} [options]
15
+ * @return {object}
16
+ * @public
17
+ */
18
+ export declare function parse(str: string, options?: {
19
+ decode?: (val: string) => string;
20
+ }): Record<string, string>;
21
+ /**
22
+ * Serialize data into a cookie header.
23
+ *
24
+ * Serialize the a name value pair into a cookie string suitable for
25
+ * http headers. An optional options object specified cookie parameters.
26
+ *
27
+ * serialize('foo', 'bar', { httpOnly: true })
28
+ * => "foo=bar; httpOnly"
29
+ *
30
+ */
31
+ export declare function serialize(name: string, val: string, options: {
32
+ encode: boolean;
33
+ maxAge: number;
34
+ domain: string;
35
+ path: string;
36
+ expires: Date;
37
+ httpOnly: boolean;
38
+ priority: string | number;
39
+ secure: boolean;
40
+ sameSite: string | boolean;
41
+ }): string;
@@ -0,0 +1,117 @@
1
+ type SubtleCryptoImportKeyAlgorithm = any;
2
+ /**
3
+ * @typedef JwtAlgorithm
4
+ * @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
5
+ */
6
+ export type JwtAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512';
7
+ /**
8
+ * @typedef JwtAlgorithms
9
+ */
10
+ export interface JwtAlgorithms {
11
+ [key: string]: SubtleCryptoImportKeyAlgorithm;
12
+ }
13
+ /**
14
+ * @typedef JwtHeader
15
+ * @prop {string} [typ] Type
16
+ */
17
+ export interface JwtHeader {
18
+ /**
19
+ * Type (default: `"JWT"`)
20
+ *
21
+ * @default "JWT"
22
+ */
23
+ typ?: string;
24
+ [key: string]: any;
25
+ }
26
+ /**
27
+ * @typedef JwtPayload
28
+ * @prop {string} [iss] Issuer
29
+ * @prop {string} [sub] Subject
30
+ * @prop {string | string[]} [aud] Audience
31
+ * @prop {string} [exp] Expiration Time
32
+ * @prop {string} [nbf] Not Before
33
+ * @prop {string} [iat] Issued At
34
+ * @prop {string} [jti] JWT ID
35
+ */
36
+ export interface JwtPayload {
37
+ /** Issuer */
38
+ iss?: string;
39
+ /** Subject */
40
+ sub?: string;
41
+ /** Audience */
42
+ aud?: string | string[];
43
+ /** Expiration Time */
44
+ exp?: number;
45
+ /** Not Before */
46
+ nbf?: number;
47
+ /** Issued At */
48
+ iat?: number;
49
+ /** JWT ID */
50
+ jti?: string;
51
+ [key: string]: any;
52
+ }
53
+ /**
54
+ * @typedef JwtOptions
55
+ * @prop {JwtAlgorithm | string} algorithm
56
+ */
57
+ export interface JwtOptions {
58
+ algorithm?: JwtAlgorithm | string;
59
+ }
60
+ /**
61
+ * @typedef JwtSignOptions
62
+ * @extends JwtOptions
63
+ * @prop {JwtHeader} [header]
64
+ */
65
+ export interface JwtSignOptions extends JwtOptions {
66
+ header?: JwtHeader;
67
+ }
68
+ /**
69
+ * @typedef JwtVerifyOptions
70
+ * @extends JwtOptions
71
+ * @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
72
+ */
73
+ export interface JwtVerifyOptions extends JwtOptions {
74
+ /**
75
+ * If `true` throw error if checks fail. (default: `false`)
76
+ *
77
+ * @default false
78
+ */
79
+ throwError?: boolean;
80
+ }
81
+ /**
82
+ * @typedef JwtData
83
+ * @prop {JwtHeader} header
84
+ * @prop {JwtPayload} payload
85
+ */
86
+ export interface JwtData {
87
+ header: JwtHeader;
88
+ payload: JwtPayload;
89
+ }
90
+ /**
91
+ * Signs a payload and returns the token
92
+ *
93
+ * @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
94
+ * @param {string | JsonWebKey} secret A string which is used to sign the payload.
95
+ * @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
96
+ * @throws {Error} If there's a validation issue.
97
+ * @returns {Promise<string>} Returns token as a `string`.
98
+ */
99
+ export declare function encode(payload: JwtPayload, secret: string | JsonWebKey, options?: JwtSignOptions | JwtAlgorithm): Promise<string>;
100
+ /**
101
+ * Verifies the integrity of the token and returns a boolean value.
102
+ *
103
+ * @param {string} token The token string generated by `jwt.sign()`.
104
+ * @param {string | JsonWebKey} secret The string which was used to sign the payload.
105
+ * @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
106
+ * @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
107
+ * @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
108
+ */
109
+ export declare function verify(token: string, secret: string | JsonWebKey, options?: JwtVerifyOptions | JwtAlgorithm): Promise<boolean>;
110
+ /**
111
+ * Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
112
+ *
113
+ * @param {string} token The token string generated by `jwt.sign()`.
114
+ * @returns {JwtData} Returns an `object` containing `header` and `payload`.
115
+ */
116
+ export declare function decode(token: string): JwtData;
117
+ export {};
@@ -0,0 +1,25 @@
1
+ import type { ConfigFile } from '../lib';
2
+ type ServerHandlerArgs = {
3
+ url: string;
4
+ config: ConfigFile;
5
+ session_keys: string[];
6
+ set_header: (key: string, value: string | number | string[]) => void;
7
+ get_header: (key: string) => string | number | string[] | undefined;
8
+ redirect: (code: number, url: string) => void;
9
+ next: () => void;
10
+ };
11
+ export declare function handle_request(args: ServerHandlerArgs): Promise<void>;
12
+ export type Server = {
13
+ use(fn: ServerMiddleware): void;
14
+ };
15
+ export type ServerMiddleware = (req: IncomingRequest, res: ServerResponse, next: () => void) => void;
16
+ export type IncomingRequest = {
17
+ url?: string;
18
+ headers: Headers;
19
+ };
20
+ export type ServerResponse = {
21
+ redirect(url: string, status?: number): void;
22
+ set_header(name: string, value: string): void;
23
+ };
24
+ export declare function get_session(req: Headers, secrets: string[]): Promise<App.Session>;
25
+ export {};
@@ -0,0 +1,41 @@
1
+ /*!
2
+ * cookie
3
+ * Copyright(c) 2012-2014 Roman Shtylman
4
+ * Copyright(c) 2015 Douglas Christopher Wilson
5
+ * MIT Licensed
6
+ */
7
+ /**
8
+ * Parse a cookie header.
9
+ *
10
+ * Parse the given cookie header string into an object
11
+ * The object has the various cookies as keys(names) => values
12
+ *
13
+ * @param {string} str
14
+ * @param {object} [options]
15
+ * @return {object}
16
+ * @public
17
+ */
18
+ export declare function parse(str: string, options?: {
19
+ decode?: (val: string) => string;
20
+ }): Record<string, string>;
21
+ /**
22
+ * Serialize data into a cookie header.
23
+ *
24
+ * Serialize the a name value pair into a cookie string suitable for
25
+ * http headers. An optional options object specified cookie parameters.
26
+ *
27
+ * serialize('foo', 'bar', { httpOnly: true })
28
+ * => "foo=bar; httpOnly"
29
+ *
30
+ */
31
+ export declare function serialize(name: string, val: string, options: {
32
+ encode: boolean;
33
+ maxAge: number;
34
+ domain: string;
35
+ path: string;
36
+ expires: Date;
37
+ httpOnly: boolean;
38
+ priority: string | number;
39
+ secure: boolean;
40
+ sameSite: string | boolean;
41
+ }): string;
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var cookies_exports = {};
20
+ __export(cookies_exports, {
21
+ parse: () => parse,
22
+ serialize: () => serialize
23
+ });
24
+ module.exports = __toCommonJS(cookies_exports);
25
+ /*!
26
+ * cookie
27
+ * Copyright(c) 2012-2014 Roman Shtylman
28
+ * Copyright(c) 2015 Douglas Christopher Wilson
29
+ * MIT Licensed
30
+ */
31
+ let __toString = Object.prototype.toString;
32
+ let fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
33
+ function parse(str, options) {
34
+ if (typeof str !== "string") {
35
+ throw new TypeError("argument str must be a string");
36
+ }
37
+ let obj = {};
38
+ let opt = options || {};
39
+ let dec = opt.decode || decode;
40
+ let index = 0;
41
+ while (index < str.length) {
42
+ let eqIdx = str.indexOf("=", index);
43
+ if (eqIdx === -1) {
44
+ break;
45
+ }
46
+ let endIdx = str.indexOf(";", index);
47
+ if (endIdx === -1) {
48
+ endIdx = str.length;
49
+ } else if (endIdx < eqIdx) {
50
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
51
+ continue;
52
+ }
53
+ let key = str.slice(index, eqIdx).trim();
54
+ if (void 0 === obj[key]) {
55
+ let val = str.slice(eqIdx + 1, endIdx).trim();
56
+ if (val.charCodeAt(0) === 34) {
57
+ val = val.slice(1, -1);
58
+ }
59
+ obj[key] = tryDecode(val, dec);
60
+ }
61
+ index = endIdx + 1;
62
+ }
63
+ return obj;
64
+ }
65
+ function serialize(name, val, options) {
66
+ let opt = options || {};
67
+ let enc = opt.encode || encode;
68
+ if (typeof enc !== "function") {
69
+ throw new TypeError("option encode is invalid");
70
+ }
71
+ if (!fieldContentRegExp.test(name)) {
72
+ throw new TypeError("argument name is invalid");
73
+ }
74
+ let value = enc(val);
75
+ if (value && !fieldContentRegExp.test(value)) {
76
+ throw new TypeError("argument val is invalid");
77
+ }
78
+ let str = name + "=" + value;
79
+ if (opt.maxAge !== null) {
80
+ let maxAge = opt.maxAge - 0;
81
+ if (Number.isNaN(maxAge) || !isFinite(maxAge)) {
82
+ throw new TypeError("option maxAge is invalid");
83
+ }
84
+ str += "; Max-Age=" + Math.floor(maxAge);
85
+ }
86
+ if (opt.domain) {
87
+ if (!fieldContentRegExp.test(opt.domain)) {
88
+ throw new TypeError("option domain is invalid");
89
+ }
90
+ str += "; Domain=" + opt.domain;
91
+ }
92
+ if (opt.path) {
93
+ if (!fieldContentRegExp.test(opt.path)) {
94
+ throw new TypeError("option path is invalid");
95
+ }
96
+ str += "; Path=" + opt.path;
97
+ }
98
+ if (opt.expires) {
99
+ let expires = opt.expires;
100
+ if (!isDate(expires) || Number.isNaN(expires.valueOf())) {
101
+ throw new TypeError("option expires is invalid");
102
+ }
103
+ str += "; Expires=" + expires.toUTCString();
104
+ }
105
+ if (opt.httpOnly) {
106
+ str += "; HttpOnly";
107
+ }
108
+ if (opt.secure) {
109
+ str += "; Secure";
110
+ }
111
+ if (opt.priority) {
112
+ let priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
113
+ switch (priority) {
114
+ case "low":
115
+ str += "; Priority=Low";
116
+ break;
117
+ case "medium":
118
+ str += "; Priority=Medium";
119
+ break;
120
+ case "high":
121
+ str += "; Priority=High";
122
+ break;
123
+ default:
124
+ throw new TypeError("option priority is invalid");
125
+ }
126
+ }
127
+ if (opt.sameSite) {
128
+ let sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
129
+ switch (sameSite) {
130
+ case true:
131
+ str += "; SameSite=Strict";
132
+ break;
133
+ case "lax":
134
+ str += "; SameSite=Lax";
135
+ break;
136
+ case "strict":
137
+ str += "; SameSite=Strict";
138
+ break;
139
+ case "none":
140
+ str += "; SameSite=None";
141
+ break;
142
+ default:
143
+ throw new TypeError("option sameSite is invalid");
144
+ }
145
+ }
146
+ return str;
147
+ }
148
+ function decode(str) {
149
+ return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
150
+ }
151
+ function encode(val) {
152
+ return encodeURIComponent(val);
153
+ }
154
+ function isDate(val) {
155
+ return __toString.call(val) === "[object Date]" || val instanceof Date;
156
+ }
157
+ function tryDecode(str, decode2) {
158
+ try {
159
+ return decode2(str);
160
+ } catch (e) {
161
+ return str;
162
+ }
163
+ }
164
+ // Annotate the CommonJS export names for ESM import in node:
165
+ 0 && (module.exports = {
166
+ parse,
167
+ serialize
168
+ });
@@ -0,0 +1,117 @@
1
+ type SubtleCryptoImportKeyAlgorithm = any;
2
+ /**
3
+ * @typedef JwtAlgorithm
4
+ * @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
5
+ */
6
+ export type JwtAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512';
7
+ /**
8
+ * @typedef JwtAlgorithms
9
+ */
10
+ export interface JwtAlgorithms {
11
+ [key: string]: SubtleCryptoImportKeyAlgorithm;
12
+ }
13
+ /**
14
+ * @typedef JwtHeader
15
+ * @prop {string} [typ] Type
16
+ */
17
+ export interface JwtHeader {
18
+ /**
19
+ * Type (default: `"JWT"`)
20
+ *
21
+ * @default "JWT"
22
+ */
23
+ typ?: string;
24
+ [key: string]: any;
25
+ }
26
+ /**
27
+ * @typedef JwtPayload
28
+ * @prop {string} [iss] Issuer
29
+ * @prop {string} [sub] Subject
30
+ * @prop {string | string[]} [aud] Audience
31
+ * @prop {string} [exp] Expiration Time
32
+ * @prop {string} [nbf] Not Before
33
+ * @prop {string} [iat] Issued At
34
+ * @prop {string} [jti] JWT ID
35
+ */
36
+ export interface JwtPayload {
37
+ /** Issuer */
38
+ iss?: string;
39
+ /** Subject */
40
+ sub?: string;
41
+ /** Audience */
42
+ aud?: string | string[];
43
+ /** Expiration Time */
44
+ exp?: number;
45
+ /** Not Before */
46
+ nbf?: number;
47
+ /** Issued At */
48
+ iat?: number;
49
+ /** JWT ID */
50
+ jti?: string;
51
+ [key: string]: any;
52
+ }
53
+ /**
54
+ * @typedef JwtOptions
55
+ * @prop {JwtAlgorithm | string} algorithm
56
+ */
57
+ export interface JwtOptions {
58
+ algorithm?: JwtAlgorithm | string;
59
+ }
60
+ /**
61
+ * @typedef JwtSignOptions
62
+ * @extends JwtOptions
63
+ * @prop {JwtHeader} [header]
64
+ */
65
+ export interface JwtSignOptions extends JwtOptions {
66
+ header?: JwtHeader;
67
+ }
68
+ /**
69
+ * @typedef JwtVerifyOptions
70
+ * @extends JwtOptions
71
+ * @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
72
+ */
73
+ export interface JwtVerifyOptions extends JwtOptions {
74
+ /**
75
+ * If `true` throw error if checks fail. (default: `false`)
76
+ *
77
+ * @default false
78
+ */
79
+ throwError?: boolean;
80
+ }
81
+ /**
82
+ * @typedef JwtData
83
+ * @prop {JwtHeader} header
84
+ * @prop {JwtPayload} payload
85
+ */
86
+ export interface JwtData {
87
+ header: JwtHeader;
88
+ payload: JwtPayload;
89
+ }
90
+ /**
91
+ * Signs a payload and returns the token
92
+ *
93
+ * @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
94
+ * @param {string | JsonWebKey} secret A string which is used to sign the payload.
95
+ * @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
96
+ * @throws {Error} If there's a validation issue.
97
+ * @returns {Promise<string>} Returns token as a `string`.
98
+ */
99
+ export declare function encode(payload: JwtPayload, secret: string | JsonWebKey, options?: JwtSignOptions | JwtAlgorithm): Promise<string>;
100
+ /**
101
+ * Verifies the integrity of the token and returns a boolean value.
102
+ *
103
+ * @param {string} token The token string generated by `jwt.sign()`.
104
+ * @param {string | JsonWebKey} secret The string which was used to sign the payload.
105
+ * @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
106
+ * @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
107
+ * @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
108
+ */
109
+ export declare function verify(token: string, secret: string | JsonWebKey, options?: JwtVerifyOptions | JwtAlgorithm): Promise<boolean>;
110
+ /**
111
+ * Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
112
+ *
113
+ * @param {string} token The token string generated by `jwt.sign()`.
114
+ * @returns {JwtData} Returns an `object` containing `header` and `payload`.
115
+ */
116
+ export declare function decode(token: string): JwtData;
117
+ export {};
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var jwt_exports = {};
20
+ __export(jwt_exports, {
21
+ decode: () => decode,
22
+ encode: () => encode,
23
+ verify: () => verify
24
+ });
25
+ module.exports = __toCommonJS(jwt_exports);
26
+ function base64UrlParse(s) {
27
+ return new Uint8Array(
28
+ Array.prototype.map.call(
29
+ atob(s.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "")),
30
+ (c) => c.charCodeAt(0)
31
+ )
32
+ );
33
+ }
34
+ function base64UrlStringify(a) {
35
+ return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
36
+ }
37
+ const algorithms = {
38
+ ES256: { name: "ECDSA", namedCurve: "P-256", hash: { name: "SHA-256" } },
39
+ ES384: { name: "ECDSA", namedCurve: "P-384", hash: { name: "SHA-384" } },
40
+ ES512: { name: "ECDSA", namedCurve: "P-521", hash: { name: "SHA-512" } },
41
+ HS256: { name: "HMAC", hash: { name: "SHA-256" } },
42
+ HS384: { name: "HMAC", hash: { name: "SHA-384" } },
43
+ HS512: { name: "HMAC", hash: { name: "SHA-512" } },
44
+ RS256: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
45
+ RS384: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" } },
46
+ RS512: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" } }
47
+ };
48
+ function _utf8ToUint8Array(str) {
49
+ return base64UrlParse(btoa(unescape(encodeURIComponent(str))));
50
+ }
51
+ function _str2ab(str) {
52
+ str = atob(str);
53
+ const buf = new ArrayBuffer(str.length);
54
+ const bufView = new Uint8Array(buf);
55
+ for (let i = 0, strLen = str.length; i < strLen; i++) {
56
+ bufView[i] = str.charCodeAt(i);
57
+ }
58
+ return buf;
59
+ }
60
+ function _decodePayload(raw) {
61
+ switch (raw.length % 4) {
62
+ case 0:
63
+ break;
64
+ case 2:
65
+ raw += "==";
66
+ break;
67
+ case 3:
68
+ raw += "=";
69
+ break;
70
+ default:
71
+ throw new Error("Illegal base64url string!");
72
+ }
73
+ try {
74
+ return JSON.parse(decodeURIComponent(escape(atob(raw))));
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ async function encode(payload, secret, options = { algorithm: "HS256", header: { typ: "JWT" } }) {
80
+ if (typeof options === "string")
81
+ options = { algorithm: options, header: { typ: "JWT" } };
82
+ options = { algorithm: "HS256", header: { typ: "JWT" }, ...options };
83
+ if (payload === null || typeof payload !== "object")
84
+ throw new Error("payload must be an object");
85
+ if (typeof secret !== "string" && typeof secret !== "object")
86
+ throw new Error("secret must be a string or a JWK object");
87
+ if (typeof options.algorithm !== "string")
88
+ throw new Error("options.algorithm must be a string");
89
+ const algorithm = algorithms[options.algorithm];
90
+ if (!algorithm)
91
+ throw new Error("algorithm not found");
92
+ if (!payload.iat)
93
+ payload.iat = Math.floor(Date.now() / 1e3);
94
+ const payloadAsJSON = JSON.stringify(payload);
95
+ const partialToken = `${base64UrlStringify(
96
+ _utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm }))
97
+ )}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`;
98
+ let keyFormat = "raw";
99
+ let keyData;
100
+ if (typeof secret === "object") {
101
+ keyFormat = "jwk";
102
+ keyData = secret;
103
+ } else if (typeof secret === "string" && secret.startsWith("-----BEGIN")) {
104
+ keyFormat = "pkcs8";
105
+ keyData = _str2ab(
106
+ secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, "")
107
+ );
108
+ } else
109
+ keyData = _utf8ToUint8Array(secret);
110
+ const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ["sign"]);
111
+ const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken));
112
+ return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`;
113
+ }
114
+ async function verify(token, secret, options = { algorithm: "HS256", throwError: false }) {
115
+ if (typeof options === "string")
116
+ options = { algorithm: options, throwError: false };
117
+ options = { algorithm: "HS256", throwError: false, ...options };
118
+ if (typeof token !== "string")
119
+ throw new Error("token must be a string");
120
+ if (typeof secret !== "string" && typeof secret !== "object")
121
+ throw new Error("secret must be a string or a JWK object");
122
+ if (typeof options.algorithm !== "string")
123
+ throw new Error("options.algorithm must be a string");
124
+ const tokenParts = token.split(".");
125
+ if (tokenParts.length !== 3)
126
+ throw new Error("token must consist of 3 parts");
127
+ const algorithm = algorithms[options.algorithm];
128
+ if (!algorithm)
129
+ throw new Error("algorithm not found");
130
+ const { payload } = decode(token);
131
+ if (!payload) {
132
+ if (options.throwError)
133
+ throw "PARSE_ERROR";
134
+ return false;
135
+ }
136
+ if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1e3)) {
137
+ if (options.throwError)
138
+ throw "NOT_YET_VALID";
139
+ return false;
140
+ }
141
+ if (payload.exp && payload.exp <= Math.floor(Date.now() / 1e3)) {
142
+ if (options.throwError)
143
+ throw "EXPIRED";
144
+ return false;
145
+ }
146
+ let keyFormat = "raw";
147
+ let keyData;
148
+ if (typeof secret === "object") {
149
+ keyFormat = "jwk";
150
+ keyData = secret;
151
+ } else if (typeof secret === "string" && secret.startsWith("-----BEGIN")) {
152
+ keyFormat = "spki";
153
+ keyData = _str2ab(
154
+ secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, "")
155
+ );
156
+ } else
157
+ keyData = _utf8ToUint8Array(secret);
158
+ const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ["verify"]);
159
+ return await crypto.subtle.verify(
160
+ algorithm,
161
+ key,
162
+ base64UrlParse(tokenParts[2]),
163
+ _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`)
164
+ );
165
+ }
166
+ function decode(token) {
167
+ return {
168
+ header: _decodePayload(
169
+ token.split(".")[0].replace(/-/g, "+").replace(/_/g, "/")
170
+ ),
171
+ payload: _decodePayload(
172
+ token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")
173
+ )
174
+ };
175
+ }
176
+ // Annotate the CommonJS export names for ESM import in node:
177
+ 0 && (module.exports = {
178
+ decode,
179
+ encode,
180
+ verify
181
+ });