experimental-ash 0.24.0 → 0.24.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/CHANGELOG.md +19 -0
- package/dist/src/chunks/authored-module-loader-DcCfCiBm.js +4 -0
- package/dist/src/chunks/client-DLHAGI2g.js +4 -0
- package/dist/src/chunks/dev-authored-source-watcher-CBID_Dwh.js +1 -0
- package/dist/src/chunks/{errors-DsO9xmQL.js → errors-HYWjHxV6.js} +1 -1
- package/dist/src/chunks/{gray-matter-BxS7ZG-J.js → gray-matter-D-9jHwOT.js} +4 -4
- package/dist/src/chunks/host-zBy9FyyX.js +70 -0
- package/dist/src/chunks/{jsdist-M7JFZoA4.js → jsdist-BkeWZ7EZ.js} +61 -61
- package/dist/src/chunks/package-HUaeub_D.js +1 -0
- package/dist/src/chunks/paths-CebY5GCi.js +89 -0
- package/dist/src/chunks/{picocolors-Bq-tZK9u.js → picocolors-aAkqW4On.js} +1 -1
- package/dist/src/chunks/token-D98SQdvs.js +1 -0
- package/dist/src/chunks/{url-BVRhVE2O.js → url-JdCGA634.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/environment.d.ts +16 -2
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/input-requests.js +1 -1
- package/dist/src/cli/dev/repl.js +3 -3
- package/dist/src/cli/dev/url.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/cli/ui/output.js +1 -1
- package/dist/src/client/index.d.ts +1 -0
- package/dist/src/client/index.js +1 -0
- package/dist/src/compiled/.vendor-stamp.json +7 -6
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/google/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@chat-adapter/slack/_slack-web-api.d.ts +7 -0
- package/dist/src/compiled/@chat-adapter/slack/index.d.ts +418 -109
- package/dist/src/compiled/@chat-adapter/slack/index.js +31 -27
- package/dist/src/compiled/@chat-adapter/slack/package.json +1 -1
- package/dist/src/compiled/@chat-adapter/state-memory/index.d.ts +8 -2
- package/dist/src/compiled/@chat-adapter/state-memory/index.js +1 -1
- package/dist/src/compiled/@chat-adapter/state-memory/package.json +1 -1
- package/dist/src/compiled/@opentelemetry/api/index.js +1 -1
- package/dist/src/compiled/@vercel/sandbox/index.js +19 -17
- package/dist/src/compiled/@vercel/sandbox/package.json +1 -1
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime.js +22 -22
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/_chunks/node/auth-ZhCJAHxl.js +2 -0
- package/dist/src/compiled/_chunks/node/{dist-BdWHjlRQ.js → dist-BQYUcBqu.js} +31 -31
- package/dist/src/compiled/_chunks/node/{chunk-Dd2tEFlW.js → dist-BdTs18CF.js} +1 -1
- package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +1 -0
- package/dist/src/compiled/_chunks/node/token-CoIbMZkq.js +1 -0
- package/dist/src/compiled/_chunks/node/{version-BMyZn3Y2.js → version-D4IYmfaS.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/coerce-BhzIW-Hm.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{compat-CIROS3w4.js → compat-DcEvieoj.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{core-DOVmxHH8.js → core-XWIi7wKc.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/{dist-C7wPwOI9.js → dist-DO14ZaQj.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-CpUQh3NH.js → dist-DZZY3Zyp.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-DOMbNs-S.js +51 -0
- package/dist/src/compiled/_chunks/workflow/{schemas-DFZoEyCn.js → schemas-DmgDnhW3.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/sleep-CRjce49s.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{src-ClRYdO4-.js → src-B54rYDvB.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/symbols-D8paKc8P.js +9 -0
- package/dist/src/compiled/_chunks/workflow/{token-CsNmv7KW.js → token-D9z1dMB6.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-j5Cl4rrs.js → token-DV7rQw_t.js} +1 -1
- package/dist/src/compiled/chat/index.d.ts +6 -3143
- package/dist/src/compiled/chat/index.js +1 -1
- package/dist/src/compiled/chat/{jsx-runtime-DxGwoLu2.d.ts → jsx-runtime-CFq1K_Ve.d.ts} +1 -1
- package/dist/src/compiled/chat/package.json +1 -1
- package/dist/src/compiled/jose/index.js +2 -2
- package/dist/src/compiled/jsonc-parser/LICENSE.md +21 -0
- package/dist/src/compiled/jsonc-parser/index.d.ts +13 -0
- package/dist/src/compiled/jsonc-parser/index.js +15 -0
- package/dist/src/compiled/jsonc-parser/package.json +7 -0
- package/dist/src/compiled/just-bash/index.js +773 -773
- package/dist/src/compiled/just-bash/package.json +1 -1
- package/dist/src/compiled/turndown/index.js +1 -1
- package/dist/src/compiled/zod/index.js +1 -1
- package/dist/src/compiled/zod-validation-error/index.js +1 -1
- package/dist/src/compiler/manifest.d.ts +36 -3
- package/dist/src/compiler/manifest.js +5 -1
- package/dist/src/compiler/module-map.js +8 -0
- package/dist/src/compiler/normalize-manifest.js +1 -0
- package/dist/src/compiler/normalize-subagent.d.ts +3 -2
- package/dist/src/compiler/normalize-subagent.js +112 -3
- package/dist/src/compiler/remote-agent-node.d.ts +20 -0
- package/dist/src/compiler/remote-agent-node.js +19 -0
- package/dist/src/discover/discover-subagent.js +35 -2
- package/dist/src/discover/grammar.d.ts +1 -0
- package/dist/src/discover/grammar.js +5 -0
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/evals/loaders/yaml.js +1 -1
- package/dist/src/evals/runner/discover.js +1 -1
- package/dist/src/evals/runner/execute-suite.js +1 -1
- package/dist/src/evals/runner/reporters/console.js +1 -1
- package/dist/src/evals/scorers/autoevals-client.js +1 -1
- package/dist/src/evals/scorers/autoevals.js +1 -1
- package/dist/src/evals/scorers/json.js +1 -1
- package/dist/src/evals/scorers/run.js +1 -1
- package/dist/src/evals/scorers/sql.js +1 -1
- package/dist/src/evals/scorers/text.js +1 -1
- package/dist/src/execution/connection-auth-steps.js +2 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-asset-import-plugin.d.ts +5 -0
- package/dist/src/internal/authored-asset-import-plugin.js +141 -0
- package/dist/src/internal/authored-module-bundle.d.ts +4 -0
- package/dist/src/internal/authored-module-bundle.js +19 -0
- package/dist/src/internal/authored-module-loader.d.ts +6 -0
- package/dist/src/internal/authored-module-loader.js +114 -125
- package/dist/src/internal/authored-package-tsconfig-paths.d.ts +9 -0
- package/dist/src/internal/authored-package-tsconfig-paths.js +209 -0
- package/dist/src/internal/nitro/host/channel-routes.d.ts +9 -2
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +12 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +19 -3
- package/dist/src/internal/nitro/host/schedule-task-routes.d.ts +7 -3
- package/dist/src/internal/nitro/host/start-development-server.js +2 -0
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -33
- package/dist/src/public/agents/auth.d.ts +30 -0
- package/dist/src/public/agents/auth.js +37 -0
- package/dist/src/public/definitions/remote-agent.d.ts +25 -0
- package/dist/src/public/definitions/remote-agent.js +11 -0
- package/dist/src/public/index.d.ts +1 -0
- package/dist/src/public/index.js +1 -0
- package/dist/src/public/next/index.d.ts +4 -4
- package/dist/src/public/next/index.js +16 -25
- package/dist/src/runtime/connections/mcp-client.js +3 -2
- package/dist/src/runtime/connections/types.d.ts +24 -0
- package/dist/src/runtime/resolve-agent-graph.js +57 -0
- package/dist/src/runtime/sessions/turn.d.ts +17 -5
- package/dist/src/runtime/subagents/registry.d.ts +6 -6
- package/dist/src/runtime/subagents/registry.js +1 -1
- package/dist/src/runtime/types.d.ts +20 -0
- package/package.json +22 -17
- package/dist/src/chunks/authored-module-loader-XcFLnl49.js +0 -2
- package/dist/src/chunks/client-nshDsWNF.js +0 -4
- package/dist/src/chunks/dev-authored-source-watcher-B4PaZGUr.js +0 -7
- package/dist/src/chunks/host-DsW72Q-w.js +0 -65
- package/dist/src/chunks/package-DmsQgn4v.js +0 -1
- package/dist/src/chunks/paths-OknjaYR8.js +0 -89
- package/dist/src/chunks/prewarm-B4YblQ5m.js +0 -6
- package/dist/src/chunks/token-DtoyQZy2.js +0 -1
- package/dist/src/chunks/token-util-CHjOk3A7.js +0 -1
- package/dist/src/compiled/_chunks/node/auth-vbe4XEEK.js +0 -2
- package/dist/src/compiled/_chunks/node/dist-DMSq2ehP.js +0 -1
- package/dist/src/compiled/_chunks/node/retry-BOcy5BbJ.js +0 -1
- package/dist/src/compiled/_chunks/node/token-D-BTJHoU.js +0 -1
- package/dist/src/compiled/_chunks/workflow/coerce-Dh0wa7P9.js +0 -1
- package/dist/src/compiled/_chunks/workflow/context-errors-Bbvvp-li.js +0 -6
- package/dist/src/compiled/_chunks/workflow/dist-C_oiE-l7.js +0 -40
- package/dist/src/compiled/_chunks/workflow/resume-hook-C3VWUPii.js +0 -12
- package/dist/src/compiled/_chunks/workflow/sleep-QTkC1VFe.js +0 -1
- package/dist/src/compiled/_chunks/workflow/symbols-QezhMuLg.js +0 -4
- package/dist/src/compiled/chat/_workflow-serde.d.ts +0 -5
- /package/dist/src/chunks/{chunk-8L7ocgPr.js → chunk-DSjMdhoD.js} +0 -0
- /package/dist/src/chunks/{guards-CjJ3lmju.js → guards-26p6sOw3.js} +0 -0
- /package/dist/src/chunks/{input-requests-BsBi7_5K.js → input-requests-DJiy6dG9.js} +0 -0
- /package/dist/src/chunks/{runtime-model-BWu6M_hq.js → runtime-model-Dh0Nz64z.js} +0 -0
- /package/dist/src/chunks/{types-MZUhN0Zy.js → types-DDA2QUED.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{chunk-DHhdAPOb.js → chunk-DSjMdhoD.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as y,Nt as b,O as x,Ot as S,P as C,Q as w,R as T,S as E,St as D,T as O,Tt as k,U as A,V as j,W as M,X as N,Y as P,Z as F,_ as I,_t as L,a as R,at as z,b as B,bt as V,c as H,ct as U,d as W,dt as G,et as K,f as q,ft as J,g as Y,gt as X,h as Z,ht as Q,i as $,it as ee,j as te,jt as ne,k as re,kt as ie,l as ae,lt as oe,m as se,mt as ce,n as le,nt as ue,o as de,ot as fe,p as pe,pt as me,q as he,r as ge,rt as _e,s as ve,st as ye,t as be,tt as xe,u as Se,ut as Ce,v as we,vt as Te,w as Ee,wt as De,x as Oe,xt as ke,y as Ae,yt as je,z as Me}from"../_chunks/node/dist-
|
|
1
|
+
import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as y,Nt as b,O as x,Ot as S,P as C,Q as w,R as T,S as E,St as D,T as O,Tt as k,U as A,V as j,W as M,X as N,Y as P,Z as F,_ as I,_t as L,a as R,at as z,b as B,bt as V,c as H,ct as U,d as W,dt as G,et as K,f as q,ft as J,g as Y,gt as X,h as Z,ht as Q,i as $,it as ee,j as te,jt as ne,k as re,kt as ie,l as ae,lt as oe,m as se,mt as ce,n as le,nt as ue,o as de,ot as fe,p as pe,pt as me,q as he,r as ge,rt as _e,s as ve,st as ye,t as be,tt as xe,u as Se,ut as Ce,v as we,vt as Te,w as Ee,wt as De,x as Oe,xt as ke,y as Ae,yt as je,z as Me}from"../_chunks/node/dist-BQYUcBqu.js";export{be as Actions,K as BaseFormatConverter,le as Button,ge as Card,$ as CardLink,R as CardText,de as ChannelImpl,ve as Chat,H as ChatError,ae as ConsoleLogger,Se as DEFAULT_EMOJI_MAP,W as Divider,q as EmojiResolver,pe as ExternalSelect,se as Field,Z as Fields,Y as Image,I as LinkButton,we as LockError,Ae as Message,B as MessageHistoryCache,Oe as Modal,E as NotImplementedError,i as Plan,Ee as RadioSelect,O as RateLimitError,c as Section,o as Select,x as SelectOption,re as StreamingMarkdownRenderer,t as StreamingPlan,te as THREAD_STATE_TTL_MS,_ as Table,y as TextInput,C as ThreadHistoryCache,u as ThreadImpl,xe as blockquote,p as cardChildToFallbackText,ue as codeBlock,g as convertEmojiPlaceholders,T as createEmoji,Me as defaultEmojiResolver,r as deriveChannelId,j as emoji,_e as emphasis,f as fromFullStream,A as fromReactElement,M as fromReactModalElement,d as getEmoji,ee as getNodeChildren,z as getNodeValue,fe as inlineCode,ye as isBlockquoteNode,h as isCardElement,U as isCodeNode,oe as isDeleteNode,Ce as isEmphasisNode,G as isInlineCodeNode,he as isJSX,J as isLinkNode,me as isListItemNode,ce as isListNode,m as isModalElement,Q as isParagraphNode,P as isPostableObject,X as isStrongNode,L as isTableCellNode,Te as isTableNode,je as isTableRowNode,V as isTextNode,ke as link,D as markdownToPlainText,a as paragraph,De as parseMarkdown,N as reviver,k as root,l as strikethrough,s as stringifyMarkdown,S as strong,ie as tableElementToAscii,n as tableToAscii,ne as text,e as toAiMessages,F as toCardElement,w as toModalElement,v as toPlainText,b as walkAst};
|
|
@@ -779,4 +779,4 @@ declare namespace JSX {
|
|
|
779
779
|
}
|
|
780
780
|
}
|
|
781
781
|
|
|
782
|
-
export { type
|
|
782
|
+
export { type DividerProps as $, type ActionsComponent as A, type ButtonComponent as B, type CardElement as C, type DividerComponent as D, type ExternalSelectComponent as E, type FieldComponent as F, type LinkButtonOptions as G, type LinkElement as H, type ImageComponent as I, type SectionElement as J, type TableAlignment as K, type LinkButtonComponent as L, type ModalComponent as M, type TableElement as N, type TableOptions as O, type TextElement as P, type TextStyle as Q, type RadioSelectComponent as R, type SectionComponent as S, type TextComponent as T, type ButtonProps as U, type CardJSXElement as V, type CardJSXProps as W, type CardLinkProps as X, type CardProps as Y, type ChatElement as Z, type ContainerProps as _, type CardChild as a, type ExternalSelectProps as a0, type FieldProps as a1, type ImageProps as a2, type LinkButtonProps as a3, type ModalProps as a4, type SelectOptionProps as a5, type SelectProps as a6, type TextInputProps as a7, type TextProps as a8, type ExternalSelectElement as a9, type ExternalSelectOptions as aa, type ModalChild as ab, type ModalElement as ac, type ModalOptions as ad, type RadioSelectElement as ae, type RadioSelectOptions as af, type SelectElement as ag, type SelectOptionElement as ah, type SelectOptions as ai, type TextInputElement as aj, type TextInputOptions as ak, type TableProps as al, type TableComponent as am, isCardLinkProps as an, jsx as ao, jsxs as ap, jsxDEV as aq, Fragment as ar, JSX as as, type CardComponent as b, cardChildToFallbackText as c, type CardLinkComponent as d, type FieldsComponent as e, fromReactElement as f, isJSX as g, Table as h, isCardElement as i, toModalElement as j, fromReactModalElement as k, isModalElement as l, type SelectComponent as m, type SelectOptionComponent as n, type TextInputComponent as o, type ActionsElement as p, type ButtonElement as q, type ButtonOptions as r, type ButtonStyle as s, toCardElement as t, type CardOptions as u, type DividerElement as v, type FieldElement as w, type FieldsElement as x, type ImageElement as y, type LinkButtonElement as z };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../_chunks/workflow/chunk-DHhdAPOb.js";const t=new TextEncoder,n=new TextDecoder,r=2**32;function i(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function a(e,t,n){if(t<0||t>=r)throw RangeError(`value must be >= 0 and <= ${r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function o(e){let t=Math.floor(e/r),n=e%r,i=new Uint8Array(8);return a(i,t,0),a(i,n,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function l(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function u(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var d=e({decode:()=>f,encode:()=>p});function f(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:n.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=n.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return u(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function p(e){let n=e;return typeof n==`string`&&(n=t.encode(n)),Uint8Array.prototype.toBase64?n.toBase64({alphabet:`base64url`,omitPadding:!0}):l(n).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const m=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),h=(e,t)=>e.name===t;function g(e){return parseInt(e.name.slice(4),10)}function _(e,t){if(g(e.hash)!==t)throw m(`SHA-${t}`,`algorithm.hash`)}function v(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function y(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ee(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!h(e.algorithm,`HMAC`))throw m(`HMAC`);_(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!h(e.algorithm,`RSASSA-PKCS1-v1_5`))throw m(`RSASSA-PKCS1-v1_5`);_(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!h(e.algorithm,`RSA-PSS`))throw m(`RSA-PSS`);_(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!h(e.algorithm,`Ed25519`))throw m(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!h(e.algorithm,t))throw m(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!h(e.algorithm,`ECDSA`))throw m(`ECDSA`);let n=v(t);if(e.algorithm.namedCurve!==n)throw m(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!h(e.algorithm,`AES-GCM`))throw m(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!h(e.algorithm,`AES-KW`))throw m(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw m(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!h(e.algorithm,`PBKDF2`))throw m(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!h(e.algorithm,`RSA-OAEP`))throw m(`RSA-OAEP`);_(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function x(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const S=(e,...t)=>x(`Key must be `,e,...t),te=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var ne=e({JOSEAlgNotAllowed:()=>T,JOSEError:()=>C,JOSENotSupported:()=>E,JWEDecryptionFailed:()=>D,JWEInvalid:()=>O,JWKInvalid:()=>ie,JWKSInvalid:()=>ae,JWKSMultipleMatchingKeys:()=>se,JWKSNoMatchingKey:()=>oe,JWKSTimeout:()=>ce,JWSInvalid:()=>k,JWSSignatureVerificationFailed:()=>le,JWTClaimValidationFailed:()=>w,JWTExpired:()=>re,JWTInvalid:()=>A}),C=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},w=class extends C{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},re=class extends C{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},T=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},E=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},D=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},O=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},k=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},A=class extends C{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},ie=class extends C{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},ae=class extends C{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},oe=class extends C{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},se=class extends C{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},ce=class extends C{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},le=class extends C{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function j(e){if(!M(e))throw Error(`CryptoKey instance expected`)}const M=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},N=e=>e?.[Symbol.toStringTag]===`KeyObject`,ue=e=>M(e)||N(e);function de(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new E(`Unsupported JWE Algorithm: ${e}`)}}const P=e=>crypto.getRandomValues(new Uint8Array(de(e)>>3));function F(e,t){let n=e.byteLength<<3;if(n!==t)throw new O(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function fe(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new E(`Unsupported JWE Algorithm: ${e}`)}}const pe=e=>crypto.getRandomValues(new Uint8Array(fe(e)>>3));function me(e,t){if(t.length<<3!==fe(e))throw new O(`Invalid Initialization Vector length`)}async function he(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(S(t,`Uint8Array`));let r=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),macKey:await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),keySize:r}}async function ge(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function _e(e,t,n,r,a){let{encKey:s,macKey:c,keySize:l}=await he(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},s,t));return{ciphertext:u,tag:await ge(c,i(a,r,u,o(a.length<<3)),l),iv:r}}async function ve(e,t){if(!(e instanceof Uint8Array))throw TypeError(`First argument must be a buffer`);if(!(t instanceof Uint8Array))throw TypeError(`Second argument must be a buffer`);let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`]),i=new Uint8Array(await crypto.subtle.sign(n,r,e)),a=new Uint8Array(await crypto.subtle.sign(n,r,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return o===0}async function ye(e,t,n,r,a,s){let{encKey:c,macKey:l,keySize:u}=await he(e,t,`decrypt`),d=await ge(l,i(s,r,n,o(s.length<<3)),u),f;try{f=await ve(a,d)}catch{}if(!f)throw new D;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new D;return p}async function be(e,t,n,r,i){let a;n instanceof Uint8Array?a=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(b(n,e,`encrypt`),a=n);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function xe(e,t,n,r,a,o){let s;t instanceof Uint8Array?s=await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(b(t,e,`decrypt`),s=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,i(n,a)))}catch{throw new D}}const Se=`Unsupported JWE Content Encryption Algorithm`;async function Ce(e,t,n,r,i){if(!M(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?me(e,r):r=pe(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&F(n,parseInt(e.slice(-3),10)),_e(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&F(n,parseInt(e.slice(1,4),10)),be(e,t,n,r,i);default:throw new E(Se)}}async function we(e,t,n,r,i,a){if(!M(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new O(`JWE Initialization Vector missing`);if(!i)throw new O(`JWE Authentication Tag missing`);switch(me(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&F(t,parseInt(e.slice(-3),10)),ye(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&F(t,parseInt(e.slice(1,4),10)),xe(e,t,n,r,i,a);default:throw new E(Se)}}const Te=Symbol();function I(e,t){if(e)throw TypeError(`${t} can only be called once`)}function L(e,t,n){try{return f(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function Ee(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const De=e=>typeof e==`object`&&!!e;function R(e){if(!De(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function z(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const Oe=e=>R(e)&&typeof e.kty==`string`,ke=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Ae=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,je=e=>e.kty===`oct`&&typeof e.k==`string`;function Me(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Ne(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Pe(e,t,n){let r=await Ne(t,e,`wrapKey`);Me(r,e);let i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Fe(e,t,n){let r=await Ne(t,e,`unwrapKey`);Me(r,e);let i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Ie(e){return i(s(e.length),e)}async function Le(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=new Uint8Array(4+e.length+n.length);r.set(s(t),0),r.set(e,4),r.set(n,4+e.length);let i=await Ee(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Re(e,t,n,r,a=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let l=i(Ie(c(n)),Ie(a),Ie(o),s(r),new Uint8Array);return Le(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,ze(e))),r,l)}function ze(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function Be(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ve(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const He=(e,t)=>i(c(e),Uint8Array.of(0),t);async function Ue(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new O(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new O(`PBES2 Count Input must be a positive integer`);let i=He(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ve(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function We(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ue(i,e,r,t);return{encryptedKey:await Pe(e.slice(-6),a,n),p2c:r,p2s:p(i)}}async function Ge(e,t,n,r,i){let a=await Ue(i,e,r,t);return Fe(e.slice(-6),a,n)}function Ke(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function qe(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Je(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ee(t,e,n),t}async function Ye(e,t,n){let r=await Je(e,t,`sign`);Ke(e,r);let i=await crypto.subtle.sign(qe(e,r.algorithm),r,n);return new Uint8Array(i)}async function Xe(e,t,n,r){let i=await Je(e,t,`verify`);Ke(e,i);let a=qe(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Ze=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function Qe(e,t,n){return b(t,e,`encrypt`),Ke(e,t),new Uint8Array(await crypto.subtle.encrypt(Ze(e),t,n))}async function $e(e,t,n){return b(t,e,`decrypt`),Ke(e,t),new Uint8Array(await crypto.subtle.decrypt(Ze(e),t,n))}const et=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function tt(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new E(et)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new E(et)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new E(et)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new E(et)}break;default:throw new E(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function nt(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=tt(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const B=`given KeyObject instance cannot be used for this algorithm`;let V;const rt=async(e,t,n,r=!1)=>{V||=new WeakMap;let i=V.get(e);if(i?.[n])return i[n];let a=await nt({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:V.set(e,{[n]:a}),a},it=(e,t)=>{V||=new WeakMap;let n=V.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(B)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(B);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(B);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(B)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(B);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(B);return n?n[t]=a:V.set(e,{[t]:a}),a};async function H(e,t){if(e instanceof Uint8Array||M(e))return e;if(N(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return it(e,t)}catch(e){if(e instanceof TypeError)throw e}return rt(e,e.export({format:`jwk`}),t)}if(Oe(e))return e.k?f(e.k):rt(e,e,t,!0);throw Error(`unreachable`)}const at=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(`
|
|
2
|
-
`)}\n-----END ${t}-----`,ot=async(e,t,n)=>{if(N(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!M(n))throw TypeError(S(n,`CryptoKey`,`KeyObject`));if(!n.extractable)throw TypeError(`CryptoKey is not extractable`);if(n.type!==e)throw TypeError(`key is not a ${e} key`);return at(l(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},st=e=>ot(`public`,`spki`,e),ct=e=>ot(`private`,`pkcs8`,e),lt=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},ut=e=>({data:e,pos:0}),U=e=>{let t=e.data[e.pos++];if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},dt=(e,t=1)=>{if(t<=0)return;e.pos++;let n=U(e);e.pos+=n,t>1&&dt(e,t-1)},W=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},ft=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},pt=e=>(W(e,6,`Expected algorithm OID`),ft(e,U(e)));function mt(e){W(e,48,`Invalid PKCS#8 structure`),U(e),W(e,2,`Expected version field`);let t=U(e);e.pos+=t,W(e,48,`Expected algorithm identifier`);let n=U(e);return{algIdStart:e.pos,algIdLength:n}}function ht(e){W(e,48,`Invalid SPKI structure`),U(e),W(e,48,`Expected algorithm identifier`);let t=U(e);return{algIdStart:e.pos,algIdLength:t}}const gt=e=>{let t=pt(e);if(lt(t,[43,101,110]))return`X25519`;if(!lt(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);W(e,6,`Expected curve OID`);let n=ft(e,U(e));for(let{name:e,oid:t}of[{name:`P-256`,oid:[42,134,72,206,61,3,1,7]},{name:`P-384`,oid:[43,129,4,0,34]},{name:`P-521`,oid:[43,129,4,0,35]}])if(lt(n,t))return e;throw Error(`Unsupported named curve`)},_t=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`],c=()=>o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c();break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new E(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new E(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},vt=(e,t)=>u(e.replace(t,``)),yt=(e,t,n)=>{let r=vt(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=ut(e);return mt(t),gt(t)}),_t(`pkcs8`,r,t,i)},bt=(e,t,n)=>{let r=vt(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=ut(e);return ht(t),gt(t)}),_t(`spki`,r,t,i)};function xt(e){let t=ut(e);W(t,48,`Invalid certificate structure`),U(t),W(t,48,`Invalid tbsCertificate structure`),U(t),e[t.pos]===160?dt(t,6):dt(t,5);let n=t.pos;W(t,48,`Invalid SPKI structure`);let r=U(t);return e.subarray(n,n+r+(t.pos-n))}function St(e){return xt(vt(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}const Ct=(e,t,n)=>{let r;try{r=St(e)}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return bt(at(l(r),`PUBLIC KEY`),t,n)};async function wt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return bt(e,t,n)}async function Tt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return Ct(e,t,n)}async function Et(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return yt(e,t,n)}async function G(e,t,n){if(!R(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return f(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new E(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return nt({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return nt({...e,ext:r});case`EC`:case`OKP`:return nt({...e,alg:t,ext:r});default:throw new E(`Unsupported "kty" (Key Type) Parameter value`)}}async function Dt(e){if(N(e))if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`});if(e instanceof Uint8Array)return{kty:`oct`,k:p(e)};if(!M(e))throw TypeError(S(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await crypto.subtle.exportKey(`jwk`,e);return a.kty===`AKP`&&(a.alg=r),a}async function Ot(e){return st(e)}async function kt(e){return ct(e)}async function At(e){return Dt(e)}async function jt(e,t,n,r){let i=await Ce(e.slice(0,7),n,t,r,new Uint8Array);return{encryptedKey:i.ciphertext,iv:p(i.iv),tag:p(i.tag)}}async function Mt(e,t,n,r,i){return we(e.slice(0,7),t,n,r,i,new Uint8Array)}const Nt=`Invalid or unsupported "alg" (JWE Algorithm) header value`;function K(e){if(e===void 0)throw new O(`JWE Encrypted Key missing`)}async function Pt(e,t,n,r,i){switch(e){case`dir`:if(n!==void 0)throw new O(`Encountered unexpected JWE Encrypted Key`);return t;case`ECDH-ES`:if(n!==void 0)throw new O(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!R(r.epk))throw new O(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(j(t),!Be(t))throw new E(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let i=await G(r.epk,e);j(i);let a,o;if(r.apu!==void 0){if(typeof r.apu!=`string`)throw new O(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);a=L(r.apu,`apu`,O)}if(r.apv!==void 0){if(typeof r.apv!=`string`)throw new O(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);o=L(r.apv,`apv`,O)}let s=await Re(i,t,e===`ECDH-ES`?r.enc:e,e===`ECDH-ES`?de(r.enc):parseInt(e.slice(-5,-2),10),a,o);return e===`ECDH-ES`?s:(K(n),Fe(e.slice(-6),s,n))}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return K(n),j(t),$e(e,t,n);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(K(n),typeof r.p2c!=`number`)throw new O(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let a=i?.maxPBES2Count||1e4;if(r.p2c>a)throw new O(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof r.p2s!=`string`)throw new O(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o;return o=L(r.p2s,`p2s`,O),Ge(e,t,n,r.p2c,o)}case`A128KW`:case`A192KW`:case`A256KW`:return K(n),Fe(e,t,n);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(K(n),typeof r.iv!=`string`)throw new O(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof r.tag!=`string`)throw new O(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let i;i=L(r.iv,`iv`,O);let a;return a=L(r.tag,`tag`,O),Mt(e,t,n,i,a)}default:throw new E(Nt)}}async function Ft(e,t,n,r,i={}){let a,o,s;switch(e){case`dir`:s=n;break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(j(n),!Be(n))throw new E(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let{apu:c,apv:l}=i,u;u=i.epk?await H(i.epk,e):(await crypto.subtle.generateKey(n.algorithm,!0,[`deriveBits`])).privateKey;let{x:d,y:f,crv:m,kty:h}=await At(u),g=await Re(n,u,e===`ECDH-ES`?t:e,e===`ECDH-ES`?de(t):parseInt(e.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:m,kty:h}},h===`EC`&&(o.epk.y=f),c&&(o.apu=p(c)),l&&(o.apv=p(l)),e===`ECDH-ES`){s=g;break}s=r||P(t),a=await Pe(e.slice(-6),g,s);break}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:s=r||P(t),j(n),a=await Qe(e,n,s);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{s=r||P(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await We(e,n,s,c,l));break}case`A128KW`:case`A192KW`:case`A256KW`:s=r||P(t),a=await Pe(e,n,s);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{s=r||P(t);let{iv:c}=i;({encryptedKey:a,...o}=await jt(e,n,s,c));break}default:throw new E(Nt)}return{cek:s,encryptedKey:a,parameters:o}}function q(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new E(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function It(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const J=e=>e?.[Symbol.toStringTag],Lt=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Rt=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(Oe(t)){if(je(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!ue(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},zt=(e,t,n)=>{if(Oe(t))switch(n){case`decrypt`:case`sign`:if(ke(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Ae(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!ue(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Y(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Rt(e,t,n);break;default:zt(e,t,n)}}function Bt(e){if(globalThis[e]===void 0)throw new E(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Vt(e){Bt(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],a=t.readable.getReader();for(;;){let{value:e,done:t}=await a.read();if(t)break;r.push(e)}return i(...r)}async function Ht(e,t){Bt(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let a=[],o=0,s=n.readable.getReader();for(;;){let{value:e,done:n}=await s.read();if(n)break;if(a.push(e),o+=e.byteLength,t!==1/0&&o>t)throw new O(`Decompressed plaintext exceeded the configured limit`)}return i(...a)}async function Ut(e,t,r){if(!R(e))throw new O(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new O(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new O(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new O(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new O(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new O(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new O(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new O(`JWE AAD incorrect type`);if(e.header!==void 0&&!R(e.header))throw new O(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!R(e.unprotected))throw new O(`JWE Per-Recipient Unprotected Header incorrect type`);let a;if(e.protected)try{let t=f(e.protected);a=JSON.parse(n.decode(t))}catch{throw new O(`JWE Protected Header is invalid`)}if(!z(a,e.header,e.unprotected))throw new O(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let o={...a,...e.header,...e.unprotected};if(q(O,new Map,r?.crit,a,o),o.zip!==void 0&&o.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(o.zip!==void 0&&!a?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:s,enc:l}=o;if(typeof s!=`string`||!s)throw new O(`missing JWE Algorithm (alg) in JWE Header`);if(typeof l!=`string`||!l)throw new O(`missing JWE Encryption Algorithm (enc) in JWE Header`);let u=r&&It(`keyManagementAlgorithms`,r.keyManagementAlgorithms),d=r&&It(`contentEncryptionAlgorithms`,r.contentEncryptionAlgorithms);if(u&&!u.has(s)||!u&&s.startsWith(`PBES2`))throw new T(`"alg" (Algorithm) Header Parameter value not allowed`);if(d&&!d.has(l))throw new T(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let p;e.encrypted_key!==void 0&&(p=L(e.encrypted_key,`encrypted_key`,O));let m=!1;typeof t==`function`&&(t=await t(a,e),m=!0),Y(s===`dir`?l:s,t,`decrypt`);let h=await H(t,s),g;try{g=await Pt(s,h,p,o,r)}catch(e){if(e instanceof TypeError||e instanceof O||e instanceof E)throw e;g=P(l)}let _,v;e.iv!==void 0&&(_=L(e.iv,`iv`,O)),e.tag!==void 0&&(v=L(e.tag,`tag`,O));let y=e.protected===void 0?new Uint8Array:c(e.protected),ee;ee=e.aad===void 0?y:i(y,c(`.`),c(e.aad));let b=L(e.ciphertext,`ciphertext`,O),x=await we(l,g,b,_,v,ee),S={plaintext:x};if(o.zip===`DEF`){let e=r?.maxDecompressedLength??25e4;if(e===0)throw new E(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);S.plaintext=await Ht(x,e).catch(e=>{throw e instanceof O?e:new O(`Failed to decompress plaintext`,{cause:e})})}return e.protected!==void 0&&(S.protectedHeader=a),e.aad!==void 0&&(S.additionalAuthenticatedData=L(e.aad,`aad`,O)),e.unprotected!==void 0&&(S.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(S.unprotectedHeader=e.header),m?{...S,key:h}:S}async function Wt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new O(`Compact JWE must be a string or Uint8Array`);let{0:i,1:a,2:o,3:s,4:c,length:l}=e.split(`.`);if(l!==5)throw new O(`Invalid Compact JWE`);let u=await Ut({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,r),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t==`function`?{...d,key:u.key}:d}async function Gt(e,t,n){if(!R(e))throw new O(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(R))throw new O(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new O(`JWE Recipients has no members`);for(let r of e.recipients)try{return await Ut({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,n)}catch{}throw new D}var Kt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this.#e=e}setKeyManagementParameters(e){return I(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return I(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return I(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return I(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return I(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return I(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new O(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!z(this.#t,this.#r,this.#n))throw new O(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let n={...this.#t,...this.#r,...this.#n};if(q(O,new Map,t?.crit,this.#t,n),n.zip!==void 0&&n.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(n.zip!==void 0&&!this.#t?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:r,enc:a}=n;if(typeof r!=`string`||!r)throw new O(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof a!=`string`||!a)throw new O(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);let o;if(this.#a&&(r===`dir`||r===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${r}`);Y(r===`dir`?a:r,e,`encrypt`);let s;{let n,i=await H(e,r);({cek:s,encryptedKey:o,parameters:n}=await Ft(r,a,i,this.#a,this.#s)),n&&(t&&Te in t?this.#r?this.#r={...this.#r,...n}:this.setUnprotectedHeader(n):this.#t?this.#t={...this.#t,...n}:this.setProtectedHeader(n))}let l,u,d,f;if(this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array),this.#i){f=p(this.#i);let e=c(f);l=i(d,c(`.`),e)}else l=d;let m=this.#e;n.zip===`DEF`&&(m=await Vt(m).catch(e=>{throw new O(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:h,tag:g,iv:_}=await Ce(a,m,s,this.#o,l),v={ciphertext:p(h)};return _&&(v.iv=p(_)),g&&(v.tag=p(g)),o&&(v.encrypted_key=p(o)),f&&(v.aad=f),this.#t&&(v.protected=u),this.#n&&(v.unprotected=this.#n),this.#r&&(v.header=this.#r),v}},qt=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setUnprotectedHeader(e){return I(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}setKeyManagementParameters(e){return I(this.keyManagementParameters,`setKeyManagementParameters`),this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Jt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new qt(this,e,{crit:t?.crit});return this.#t.push(n),n}setProtectedHeader(e){return I(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return I(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new O(`at least one recipient must be added`);if(this.#t.length===1){let[e]=this.#t,t=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),n={ciphertext:t.ciphertext,iv:t.iv,recipients:[{}],tag:t.tag};return t.aad&&(n.aad=t.aad),t.protected&&(n.protected=t.protected),t.unprotected&&(n.unprotected=t.unprotected),t.encrypted_key&&(n.recipients[0].encrypted_key=t.encrypted_key),t.header&&(n.recipients[0].header=t.header),n}let e;for(let t=0;t<this.#t.length;t++){let n=this.#t[t];if(!z(this.#n,this.#r,n.unprotectedHeader))throw new O(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let r={...this.#n,...this.#r,...n.unprotectedHeader},{alg:i}=r;if(typeof i!=`string`||!i)throw new O(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(i===`dir`||i===`ECDH-ES`)throw new O(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof r.enc!=`string`||!r.enc)throw new O(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=r.enc;else if(e!==r.enc)throw new O(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if(q(O,new Map,n.options.crit,this.#n,r),r.zip!==void 0&&r.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(r.zip!==void 0&&!this.#n?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}let t=P(e),n={ciphertext:``,recipients:[]};for(let r=0;r<this.#t.length;r++){let i=this.#t[r],a={};if(n.recipients.push(a),r===0){let e=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters(i.keyManagementParameters).encrypt(i.key,{...i.options,[Te]:!0});n.ciphertext=e.ciphertext,n.iv=e.iv,n.tag=e.tag,e.aad&&(n.aad=e.aad),e.protected&&(n.protected=e.protected),e.unprotected&&(n.unprotected=e.unprotected),a.encrypted_key=e.encrypted_key,e.header&&(a.header=e.header);continue}let o=i.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;Y(o===`dir`?e:o,i.key,`encrypt`);let s=await H(i.key,o),{encryptedKey:c,parameters:l}=await Ft(o,e,s,t,i.keyManagementParameters);a.encrypted_key=p(c),(i.unprotectedHeader||l)&&(a.header={...i.unprotectedHeader,...l})}return n}};async function Yt(e,r,a){if(!R(e))throw new k(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new k(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new k(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new k(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new k(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!R(e.header))throw new k(`JWS Unprotected Header incorrect type`);let o={};if(e.protected)try{let t=f(e.protected);o=JSON.parse(n.decode(t))}catch{throw new k(`JWS Protected Header is invalid`)}if(!z(o,e.header))throw new k(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let s={...o,...e.header},l=q(k,new Map([[`b64`,!0]]),a?.crit,o,s),u=!0;if(l.has(`b64`)&&(u=o.b64,typeof u!=`boolean`))throw new k(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:d}=s;if(typeof d!=`string`||!d)throw new k(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let p=a&&It(`algorithms`,a.algorithms);if(p&&!p.has(d))throw new T(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof e.payload!=`string`)throw new k(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new k(`JWS Payload must be a string or an Uint8Array instance`);let m=!1;typeof r==`function`&&(r=await r(o,e),m=!0),Y(d,r,`verify`);let h=i(e.protected===void 0?new Uint8Array:c(e.protected),c(`.`),typeof e.payload==`string`?u?c(e.payload):t.encode(e.payload):e.payload),g=L(e.signature,`signature`,k),_=await H(r,d);if(!await Xe(d,_,g,h))throw new le;let v;v=u?L(e.payload,`payload`,k):typeof e.payload==`string`?t.encode(e.payload):e.payload;let y={payload:v};return e.protected!==void 0&&(y.protectedHeader=o),e.header!==void 0&&(y.unprotectedHeader=e.header),m?{...y,key:_}:y}async function Xt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new k(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new k(`Invalid Compact JWS`);let c=await Yt({payload:a,protected:i,signature:o},t,r),l={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t==`function`?{...l,key:c.key}:l}async function Zt(e,t,n){if(!R(e))throw new k(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(R))throw new k(`JWS Signatures missing or incorrect type`);for(let r of e.signatures)try{return await Yt({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,n)}catch{}throw new le}const X=e=>Math.floor(e.getTime()/1e3),Qt=3600,$t=Qt*24;$t*7,$t*365.25;const en=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Z(e){let t=en.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*Qt);break;case`day`:case`days`:case`d`:i=Math.round(n*$t);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}function Q(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const tn=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,nn=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function rn(e,t,r={}){let i;try{i=JSON.parse(n.decode(t))}catch{}if(!R(i))throw new A(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=r;if(a&&(typeof e.typ!=`string`||tn(e.typ)!==tn(a)))throw new w(`unexpected "typ" JWT header value`,i,`typ`,`check_failed`);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=r,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!(e in i))throw new w(`missing required "${e}" claim`,i,e,`missing`);if(s&&!(Array.isArray(s)?s:[s]).includes(i.iss))throw new w(`unexpected "iss" claim value`,i,`iss`,`check_failed`);if(c&&i.sub!==c)throw new w(`unexpected "sub" claim value`,i,`sub`,`check_failed`);if(l&&!nn(i.aud,typeof l==`string`?[l]:l))throw new w(`unexpected "aud" claim value`,i,`aud`,`check_failed`);let f;switch(typeof r.clockTolerance){case`string`:f=Z(r.clockTolerance);break;case`number`:f=r.clockTolerance;break;case`undefined`:f=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:p}=r,m=X(p||new Date);if((i.iat!==void 0||u)&&typeof i.iat!=`number`)throw new w(`"iat" claim must be a number`,i,`iat`,`invalid`);if(i.nbf!==void 0){if(typeof i.nbf!=`number`)throw new w(`"nbf" claim must be a number`,i,`nbf`,`invalid`);if(i.nbf>m+f)throw new w(`"nbf" claim timestamp check failed`,i,`nbf`,`check_failed`)}if(i.exp!==void 0){if(typeof i.exp!=`number`)throw new w(`"exp" claim must be a number`,i,`exp`,`invalid`);if(i.exp<=m-f)throw new re(`"exp" claim timestamp check failed`,i,`exp`,`check_failed`)}if(u){let e=m-i.iat,t=typeof u==`number`?u:Z(u);if(e-f>t)throw new re(`"iat" claim timestamp check failed (too far in the past)`,i,`iat`,`check_failed`);if(e<0-f)throw new w(`"iat" claim timestamp check failed (it should be in the past)`,i,`iat`,`check_failed`)}return i}var an=class{#e;constructor(e){if(!R(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return t.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e==`number`?this.#e.nbf=Q(`setNotBefore`,e):e instanceof Date?this.#e.nbf=Q(`setNotBefore`,X(e)):this.#e.nbf=X(new Date)+Z(e)}set exp(e){typeof e==`number`?this.#e.exp=Q(`setExpirationTime`,e):e instanceof Date?this.#e.exp=Q(`setExpirationTime`,X(e)):this.#e.exp=X(new Date)+Z(e)}set iat(e){e===void 0?this.#e.iat=X(new Date):e instanceof Date?this.#e.iat=Q(`setIssuedAt`,X(e)):typeof e==`string`?this.#e.iat=Q(`setIssuedAt`,X(new Date)+Z(e)):this.#e.iat=Q(`setIssuedAt`,e)}};async function on(e,t,n){let r=await Xt(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new A(`JWTs MUST NOT use unencoded payload`);let i={payload:rn(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function sn(e,t,n){let r=await Wt(e,t,n),i=rn(r.protectedHeader,r.plaintext,n),{protectedHeader:a}=r;if(a.iss!==void 0&&a.iss!==i.iss)throw new w(`replicated "iss" claim header parameter mismatch`,i,`iss`,`mismatch`);if(a.sub!==void 0&&a.sub!==i.sub)throw new w(`replicated "sub" claim header parameter mismatch`,i,`sub`,`mismatch`);if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new w(`replicated "aud" claim header parameter mismatch`,i,`aud`,`mismatch`);let o={payload:i,protectedHeader:a};return typeof t==`function`?{...o,key:r.key}:o}var cn=class{#e;constructor(e){this.#e=new Kt(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this.#e.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}},ln=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return I(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return I(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new k(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!z(this.#t,this.#n))throw new k(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this.#t,...this.#n},r=q(k,new Map([[`b64`,!0]]),t?.crit,this.#t,n),a=!0;if(r.has(`b64`)&&(a=this.#t.b64,typeof a!=`boolean`))throw new k(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:o}=n;if(typeof o!=`string`||!o)throw new k(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);Y(o,e,`sign`);let s,l;a?(s=p(this.#e),l=c(s)):(l=this.#e,s=``);let u,d;this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array);let f=i(d,c(`.`),l),m={signature:p(await Ye(o,await H(e,o),f)),payload:s};return this.#n&&(m.header=this.#n),this.#t&&(m.protected=u),m}},un=class{#e;constructor(e){this.#e=new ln(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){let n=await this.#e.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}},dn=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setProtectedHeader(e){return I(this.protectedHeader,`setProtectedHeader`),this.protectedHeader=e,this}setUnprotectedHeader(e){return I(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}addSignature(...e){return this.#e.addSignature(...e)}sign(...e){return this.#e.sign(...e)}done(){return this.#e}},fn=class{#e;#t=[];constructor(e){this.#e=e}addSignature(e,t){let n=new dn(this,e,t);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new k(`at least one signature must be added`);let e={signatures:[],payload:``};for(let t=0;t<this.#t.length;t++){let n=this.#t[t],r=new ln(this.#e);r.setProtectedHeader(n.protectedHeader),r.setUnprotectedHeader(n.unprotectedHeader);let{payload:i,...a}=await r.sign(n.key,n.options);if(t===0)e.payload=i;else if(e.payload!==i)throw new k(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(a)}return e}},pn=class{#e;#t;constructor(e={}){this.#t=new an(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new un(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes(`b64`)&&this.#e.b64===!1)throw new A(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}},mn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#s=new an(e)}setIssuer(e){return this.#s.iss=e,this}setSubject(e){return this.#s.sub=e,this}setAudience(e){return this.#s.aud=e,this}setJti(e){return this.#s.jti=e,this}setNotBefore(e){return this.#s.nbf=e,this}setExpirationTime(e){return this.#s.exp=e,this}setIssuedAt(e){return this.#s.iat=e,this}setProtectedHeader(e){return I(this.#r,`setProtectedHeader`),this.#r=e,this}setKeyManagementParameters(e){return I(this.#n,`setKeyManagementParameters`),this.#n=e,this}setContentEncryptionKey(e){return I(this.#e,`setContentEncryptionKey`),this.#e=e,this}setInitializationVector(e){return I(this.#t,`setInitializationVector`),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(e,t){let n=new cn(this.#s.data());return this.#r&&(this.#i||this.#a||this.#o)&&(this.#r={...this.#r,iss:this.#i?this.#s.iss:void 0,sub:this.#a?this.#s.sub:void 0,aud:this.#o?this.#s.aud:void 0}),n.setProtectedHeader(this.#r),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#n&&n.setKeyManagementParameters(this.#n),n.encrypt(e,t)}};const $=(e,t)=>{if(typeof e!=`string`||!e)throw new ie(`${t} missing or invalid`)};async function hn(e,t){let n;if(Oe(e))n=e;else if(ue(e))n=await At(e);else throw TypeError(S(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$(n.alg,`"alg" (Algorithm) Parameter`),$(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$(n.crv,`"crv" (Curve) Parameter`),$(n.x,`"x" (X Coordinate) Parameter`),$(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$(n.e,`"e" (Exponent) Parameter`),$(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:$(n.k,`"k" (Key Value) Parameter`),r={k:n.k,kty:n.kty};break;default:throw new E(`"kty" (Key Type) Parameter missing or unsupported`)}let i=c(JSON.stringify(r));return p(await Ee(t,i))}async function gn(e,t){t??=`sha256`;let n=await hn(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}async function _n(e,t){let n={...e,...t?.header};if(!R(n.jwk))throw new k(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let r=await G({...n.jwk,ext:!0},n.alg);if(r instanceof Uint8Array||r.type!==`public`)throw new k(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return r}function vn(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new E(`Unsupported "alg" value for a JSON Web Key Set`)}}function yn(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(bn)}function bn(e){return R(e)}var xn=class{#e;#t=new WeakMap;constructor(e){if(!yn(e))throw new ae(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=vn(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new oe;if(s!==1){let e=new se,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Sn(t,e,n)}catch{}},e}return Sn(this.#t,o,n)}};async function Sn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await G({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new ae(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Cn(e){let t=new xn(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function wn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Tn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Tn=`jose/v6.2.3`);const En=Symbol();async function Dn(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new ce:e});if(i.status!==200)throw new C(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new C(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const On=Symbol();function kn(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!R(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,R))}var An=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Tn&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Tn),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[En],t?.[On]!==void 0&&(this.#l=t?.[On],kn(t?.[On],this.#r)&&(this.#i=this.#l.uat,this.#c=Cn(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof oe&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&wn()&&(this.#a=void 0),this.#a||=Dn(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Cn(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function jn(e,t){let n=new An(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}var Mn=class{#e;constructor(e={}){this.#e=new an(e)}encode(){return`${p(JSON.stringify({alg:`none`}))}.${p(this.#e.data())}.`}setIssuer(e){return this.#e.iss=e,this}setSubject(e){return this.#e.sub=e,this}setAudience(e){return this.#e.aud=e,this}setJti(e){return this.#e.jti=e,this}setNotBefore(e){return this.#e.nbf=e,this}setExpirationTime(e){return this.#e.exp=e,this}setIssuedAt(e){return this.#e.iat=e,this}static decode(e,t){if(typeof e!=`string`)throw new A(`Unsecured JWT must be a string`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3||a!==``)throw new A(`Invalid Unsecured JWT`);let s;try{if(s=JSON.parse(n.decode(f(r))),s.alg!==`none`)throw Error()}catch{throw new A(`Invalid Unsecured JWT`)}return{payload:rn(s,f(i),t),header:s}}};function Nn(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e)if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`);try{if(typeof t!=`string`||!t)throw Error();let e=JSON.parse(n.decode(f(t)));if(!R(e))throw Error();return e}catch{throw TypeError(`Invalid Token or Protected Header formatting`)}}function Pn(e){if(typeof e!=`string`)throw new A(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:r}=e.split(`.`);if(r===5)throw new A(`Only JWTs using Compact JWS serialization can be decoded`);if(r!==3)throw new A(`Invalid JWT`);if(!t)throw new A(`JWTs must contain a payload`);let i;try{i=f(t)}catch{throw new A(`Failed to base64url decode the payload`)}let a;try{a=JSON.parse(n.decode(i))}catch{throw new A(`Failed to parse the decoded payload as JSON`)}if(!R(a))throw new A(`Invalid JWT Claims Set`);return a}function Fn(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new E(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function In(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Fn(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Fn(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Fn(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:case`EdDSA`:r=[`sign`,`verify`],n={name:`Ed25519`};break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:r=[`sign`,`verify`],n={name:e};break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:n={name:`X25519`};break;default:throw new E(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`)}break}default:throw new E(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(n,t?.extractable??!1,r)}async function Ln(e,t){let n,r,i;switch(e){case`HS256`:case`HS384`:case`HS512`:n=parseInt(e.slice(-3),10),r={name:`HMAC`,hash:`SHA-${n}`,length:n},i=[`sign`,`verify`];break;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(n>>3));case`A128KW`:case`A192KW`:case`A256KW`:n=parseInt(e.slice(1,4),10),r={name:`AES-KW`,length:n},i=[`wrapKey`,`unwrapKey`];break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:n=parseInt(e.slice(1,4),10),r={name:`AES-GCM`,length:n},i=[`encrypt`,`decrypt`];break;default:throw new E(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(r,t?.extractable??!1,i)}const Rn=`WebCryptoAPI`;export{cn as CompactEncrypt,un as CompactSign,_n as EmbeddedJWK,mn as EncryptJWT,Kt as FlattenedEncrypt,ln as FlattenedSign,Jt as GeneralEncrypt,fn as GeneralSign,pn as SignJWT,Mn as UnsecuredJWT,d as base64url,hn as calculateJwkThumbprint,gn as calculateJwkThumbprintUri,Wt as compactDecrypt,Xt as compactVerify,Cn as createLocalJWKSet,jn as createRemoteJWKSet,Rn as cryptoRuntime,En as customFetch,Pn as decodeJwt,Nn as decodeProtectedHeader,ne as errors,At as exportJWK,kt as exportPKCS8,Ot as exportSPKI,Ut as flattenedDecrypt,Yt as flattenedVerify,Gt as generalDecrypt,Zt as generalVerify,In as generateKeyPair,Ln as generateSecret,G as importJWK,Et as importPKCS8,wt as importSPKI,Tt as importX509,On as jwksCache,sn as jwtDecrypt,on as jwtVerify};
|
|
1
|
+
import{n as e}from"../_chunks/workflow/chunk-DSjMdhoD.js";const t=new TextEncoder,n=new TextDecoder,r=2**32;function i(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function a(e,t,n){if(t<0||t>=r)throw RangeError(`value must be >= 0 and <= ${r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function o(e){let t=Math.floor(e/r),n=e%r,i=new Uint8Array(8);return a(i,t,0),a(i,n,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function l(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function u(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var d=e({decode:()=>f,encode:()=>p});function f(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:n.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=n.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return u(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function p(e){let n=e;return typeof n==`string`&&(n=t.encode(n)),Uint8Array.prototype.toBase64?n.toBase64({alphabet:`base64url`,omitPadding:!0}):l(n).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const m=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),h=(e,t)=>e.name===t;function g(e){return parseInt(e.name.slice(4),10)}function _(e,t){if(g(e.hash)!==t)throw m(`SHA-${t}`,`algorithm.hash`)}function v(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function y(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ee(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!h(e.algorithm,`HMAC`))throw m(`HMAC`);_(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!h(e.algorithm,`RSASSA-PKCS1-v1_5`))throw m(`RSASSA-PKCS1-v1_5`);_(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!h(e.algorithm,`RSA-PSS`))throw m(`RSA-PSS`);_(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!h(e.algorithm,`Ed25519`))throw m(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!h(e.algorithm,t))throw m(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!h(e.algorithm,`ECDSA`))throw m(`ECDSA`);let n=v(t);if(e.algorithm.namedCurve!==n)throw m(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!h(e.algorithm,`AES-GCM`))throw m(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!h(e.algorithm,`AES-KW`))throw m(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw m(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!h(e.algorithm,`PBKDF2`))throw m(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!h(e.algorithm,`RSA-OAEP`))throw m(`RSA-OAEP`);_(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function x(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const S=(e,...t)=>x(`Key must be `,e,...t),te=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var ne=e({JOSEAlgNotAllowed:()=>ie,JOSEError:()=>C,JOSENotSupported:()=>T,JWEDecryptionFailed:()=>E,JWEInvalid:()=>D,JWKInvalid:()=>ae,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>ce,JWKSNoMatchingKey:()=>se,JWKSTimeout:()=>le,JWSInvalid:()=>O,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>w,JWTExpired:()=>re,JWTInvalid:()=>k}),C=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},w=class extends C{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},re=class extends C{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ie=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},T=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},E=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},D=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},O=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},k=class extends C{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},ae=class extends C{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},oe=class extends C{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},se=class extends C{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},ce=class extends C{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},le=class extends C{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},ue=class extends C{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function A(e){if(!j(e))throw Error(`CryptoKey instance expected`)}const j=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},de=e=>e?.[Symbol.toStringTag]===`KeyObject`,fe=e=>j(e)||de(e);function pe(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const M=e=>crypto.getRandomValues(new Uint8Array(pe(e)>>3));function me(e,t){let n=e.byteLength<<3;if(n!==t)throw new D(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function he(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const ge=e=>crypto.getRandomValues(new Uint8Array(he(e)>>3));function _e(e,t){if(t.length<<3!==he(e))throw new D(`Invalid Initialization Vector length`)}async function ve(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(S(t,`Uint8Array`));let r=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),macKey:await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),keySize:r}}async function ye(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function be(e,t,n,r,a){let{encKey:s,macKey:c,keySize:l}=await ve(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},s,t));return{ciphertext:u,tag:await ye(c,i(a,r,u,o(a.length<<3)),l),iv:r}}async function xe(e,t){if(!(e instanceof Uint8Array))throw TypeError(`First argument must be a buffer`);if(!(t instanceof Uint8Array))throw TypeError(`Second argument must be a buffer`);let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`]),i=new Uint8Array(await crypto.subtle.sign(n,r,e)),a=new Uint8Array(await crypto.subtle.sign(n,r,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return o===0}async function Se(e,t,n,r,a,s){let{encKey:c,macKey:l,keySize:u}=await ve(e,t,`decrypt`),d=await ye(l,i(s,r,n,o(s.length<<3)),u),f;try{f=await xe(a,d)}catch{}if(!f)throw new E;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new E;return p}async function Ce(e,t,n,r,i){let a;n instanceof Uint8Array?a=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(b(n,e,`encrypt`),a=n);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function we(e,t,n,r,a,o){let s;t instanceof Uint8Array?s=await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(b(t,e,`decrypt`),s=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,i(n,a)))}catch{throw new E}}const Te=`Unsupported JWE Content Encryption Algorithm`;async function Ee(e,t,n,r,i){if(!j(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?_e(e,r):r=ge(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(-3),10)),be(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(1,4),10)),Ce(e,t,n,r,i);default:throw new T(Te)}}async function De(e,t,n,r,i,a){if(!j(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new D(`JWE Initialization Vector missing`);if(!i)throw new D(`JWE Authentication Tag missing`);switch(_e(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(-3),10)),Se(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(1,4),10)),we(e,t,n,r,i,a);default:throw new T(Te)}}const Oe=Symbol();function N(e,t){if(e)throw TypeError(`${t} can only be called once`)}function P(e,t,n){try{return f(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function ke(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const Ae=e=>typeof e==`object`&&!!e;function F(e){if(!Ae(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function I(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const L=e=>F(e)&&typeof e.kty==`string`,je=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Me=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Ne=e=>e.kty===`oct`&&typeof e.k==`string`;function Pe(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Fe(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Ie(e,t,n){let r=await Fe(t,e,`wrapKey`);Pe(r,e);let i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Le(e,t,n){let r=await Fe(t,e,`unwrapKey`);Pe(r,e);let i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Re(e){return i(s(e.length),e)}async function ze(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=new Uint8Array(4+e.length+n.length);r.set(s(t),0),r.set(e,4),r.set(n,4+e.length);let i=await ke(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Be(e,t,n,r,a=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let l=i(Re(c(n)),Re(a),Re(o),s(r),new Uint8Array);return ze(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,Ve(e))),r,l)}function Ve(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function He(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ue(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const We=(e,t)=>i(c(e),Uint8Array.of(0),t);async function Ge(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new D(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new D(`PBES2 Count Input must be a positive integer`);let i=We(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ue(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function Ke(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ge(i,e,r,t);return{encryptedKey:await Ie(e.slice(-6),a,n),p2c:r,p2s:p(i)}}async function qe(e,t,n,r,i){let a=await Ge(i,e,r,t);return Le(e.slice(-6),a,n)}function R(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Je(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ye(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ee(t,e,n),t}async function Xe(e,t,n){let r=await Ye(e,t,`sign`);R(e,r);let i=await crypto.subtle.sign(Je(e,r.algorithm),r,n);return new Uint8Array(i)}async function Ze(e,t,n,r){let i=await Ye(e,t,`verify`);R(e,i);let a=Je(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Qe=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function $e(e,t,n){return b(t,e,`encrypt`),R(e,t),new Uint8Array(await crypto.subtle.encrypt(Qe(e),t,n))}async function et(e,t,n){return b(t,e,`decrypt`),R(e,t),new Uint8Array(await crypto.subtle.decrypt(Qe(e),t,n))}const z=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function tt(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new T(z)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new T(z)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;default:throw new T(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function B(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=tt(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const V=`given KeyObject instance cannot be used for this algorithm`;let H;const nt=async(e,t,n,r=!1)=>{H||=new WeakMap;let i=H.get(e);if(i?.[n])return i[n];let a=await B({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:H.set(e,{[n]:a}),a},rt=(e,t)=>{H||=new WeakMap;let n=H.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(V)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(V)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(V);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(V);return n?n[t]=a:H.set(e,{[t]:a}),a};async function U(e,t){if(e instanceof Uint8Array||j(e))return e;if(de(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return rt(e,t)}catch(e){if(e instanceof TypeError)throw e}return nt(e,e.export({format:`jwk`}),t)}if(L(e))return e.k?f(e.k):nt(e,e,t,!0);throw Error(`unreachable`)}const it=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(`
|
|
2
|
+
`)}\n-----END ${t}-----`,at=async(e,t,n)=>{if(de(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!j(n))throw TypeError(S(n,`CryptoKey`,`KeyObject`));if(!n.extractable)throw TypeError(`CryptoKey is not extractable`);if(n.type!==e)throw TypeError(`key is not a ${e} key`);return it(l(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},ot=e=>at(`public`,`spki`,e),st=e=>at(`private`,`pkcs8`,e),ct=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},lt=e=>({data:e,pos:0}),W=e=>{let t=e.data[e.pos++];if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},ut=(e,t=1)=>{if(t<=0)return;e.pos++;let n=W(e);e.pos+=n,t>1&&ut(e,t-1)},G=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},dt=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ft=e=>(G(e,6,`Expected algorithm OID`),dt(e,W(e)));function pt(e){G(e,48,`Invalid PKCS#8 structure`),W(e),G(e,2,`Expected version field`);let t=W(e);e.pos+=t,G(e,48,`Expected algorithm identifier`);let n=W(e);return{algIdStart:e.pos,algIdLength:n}}function mt(e){G(e,48,`Invalid SPKI structure`),W(e),G(e,48,`Expected algorithm identifier`);let t=W(e);return{algIdStart:e.pos,algIdLength:t}}const ht=e=>{let t=ft(e);if(ct(t,[43,101,110]))return`X25519`;if(!ct(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);G(e,6,`Expected curve OID`);let n=dt(e,W(e));for(let{name:e,oid:t}of[{name:`P-256`,oid:[42,134,72,206,61,3,1,7]},{name:`P-384`,oid:[43,129,4,0,34]},{name:`P-521`,oid:[43,129,4,0,35]}])if(ct(n,t))return e;throw Error(`Unsupported named curve`)},gt=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`],c=()=>o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c();break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new T(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new T(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},_t=(e,t)=>u(e.replace(t,``)),vt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return pt(t),ht(t)}),gt(`pkcs8`,r,t,i)},yt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return mt(t),ht(t)}),gt(`spki`,r,t,i)};function bt(e){let t=lt(e);G(t,48,`Invalid certificate structure`),W(t),G(t,48,`Invalid tbsCertificate structure`),W(t),e[t.pos]===160?ut(t,6):ut(t,5);let n=t.pos;G(t,48,`Invalid SPKI structure`);let r=W(t);return e.subarray(n,n+r+(t.pos-n))}function xt(e){return bt(_t(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}const St=(e,t,n)=>{let r;try{r=xt(e)}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return yt(it(l(r),`PUBLIC KEY`),t,n)};async function Ct(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return yt(e,t,n)}async function wt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return St(e,t,n)}async function Tt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return vt(e,t,n)}async function Et(e,t,n){if(!F(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return f(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new T(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return B({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return B({...e,ext:r});case`EC`:case`OKP`:return B({...e,alg:t,ext:r});default:throw new T(`Unsupported "kty" (Key Type) Parameter value`)}}async function Dt(e){if(de(e))if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`});if(e instanceof Uint8Array)return{kty:`oct`,k:p(e)};if(!j(e))throw TypeError(S(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await crypto.subtle.exportKey(`jwk`,e);return a.kty===`AKP`&&(a.alg=r),a}async function Ot(e){return ot(e)}async function kt(e){return st(e)}async function At(e){return Dt(e)}async function jt(e,t,n,r){let i=await Ee(e.slice(0,7),n,t,r,new Uint8Array);return{encryptedKey:i.ciphertext,iv:p(i.iv),tag:p(i.tag)}}async function Mt(e,t,n,r,i){return De(e.slice(0,7),t,n,r,i,new Uint8Array)}const Nt=`Invalid or unsupported "alg" (JWE Algorithm) header value`;function K(e){if(e===void 0)throw new D(`JWE Encrypted Key missing`)}async function Pt(e,t,n,r,i){switch(e){case`dir`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);return t;case`ECDH-ES`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!F(r.epk))throw new D(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(A(t),!He(t))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let i=await Et(r.epk,e);A(i);let a,o;if(r.apu!==void 0){if(typeof r.apu!=`string`)throw new D(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);a=P(r.apu,`apu`,D)}if(r.apv!==void 0){if(typeof r.apv!=`string`)throw new D(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);o=P(r.apv,`apv`,D)}let s=await Be(i,t,e===`ECDH-ES`?r.enc:e,e===`ECDH-ES`?pe(r.enc):parseInt(e.slice(-5,-2),10),a,o);return e===`ECDH-ES`?s:(K(n),Le(e.slice(-6),s,n))}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return K(n),A(t),et(e,t,n);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(K(n),typeof r.p2c!=`number`)throw new D(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let a=i?.maxPBES2Count||1e4;if(r.p2c>a)throw new D(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof r.p2s!=`string`)throw new D(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o;return o=P(r.p2s,`p2s`,D),qe(e,t,n,r.p2c,o)}case`A128KW`:case`A192KW`:case`A256KW`:return K(n),Le(e,t,n);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(K(n),typeof r.iv!=`string`)throw new D(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof r.tag!=`string`)throw new D(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let i;i=P(r.iv,`iv`,D);let a;return a=P(r.tag,`tag`,D),Mt(e,t,n,i,a)}default:throw new T(Nt)}}async function Ft(e,t,n,r,i={}){let a,o,s;switch(e){case`dir`:s=n;break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(A(n),!He(n))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let{apu:c,apv:l}=i,u;u=i.epk?await U(i.epk,e):(await crypto.subtle.generateKey(n.algorithm,!0,[`deriveBits`])).privateKey;let{x:d,y:f,crv:m,kty:h}=await At(u),g=await Be(n,u,e===`ECDH-ES`?t:e,e===`ECDH-ES`?pe(t):parseInt(e.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:m,kty:h}},h===`EC`&&(o.epk.y=f),c&&(o.apu=p(c)),l&&(o.apv=p(l)),e===`ECDH-ES`){s=g;break}s=r||M(t),a=await Ie(e.slice(-6),g,s);break}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:s=r||M(t),A(n),a=await $e(e,n,s);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{s=r||M(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await Ke(e,n,s,c,l));break}case`A128KW`:case`A192KW`:case`A256KW`:s=r||M(t),a=await Ie(e,n,s);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{s=r||M(t);let{iv:c}=i;({encryptedKey:a,...o}=await jt(e,n,s,c));break}default:throw new T(Nt)}return{cek:s,encryptedKey:a,parameters:o}}function q(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new T(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function It(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const J=e=>e?.[Symbol.toStringTag],Lt=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Rt=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(L(t)){if(Ne(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},zt=(e,t,n)=>{if(L(t))switch(n){case`decrypt`:case`sign`:if(je(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Me(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Y(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Rt(e,t,n);break;default:zt(e,t,n)}}function Bt(e){if(globalThis[e]===void 0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Vt(e){Bt(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],a=t.readable.getReader();for(;;){let{value:e,done:t}=await a.read();if(t)break;r.push(e)}return i(...r)}async function Ht(e,t){Bt(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let a=[],o=0,s=n.readable.getReader();for(;;){let{value:e,done:n}=await s.read();if(n)break;if(a.push(e),o+=e.byteLength,t!==1/0&&o>t)throw new D(`Decompressed plaintext exceeded the configured limit`)}return i(...a)}async function Ut(e,t,r){if(!F(e))throw new D(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new D(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new D(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new D(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new D(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new D(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new D(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new D(`JWE AAD incorrect type`);if(e.header!==void 0&&!F(e.header))throw new D(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!F(e.unprotected))throw new D(`JWE Per-Recipient Unprotected Header incorrect type`);let a;if(e.protected)try{let t=f(e.protected);a=JSON.parse(n.decode(t))}catch{throw new D(`JWE Protected Header is invalid`)}if(!I(a,e.header,e.unprotected))throw new D(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let o={...a,...e.header,...e.unprotected};if(q(D,new Map,r?.crit,a,o),o.zip!==void 0&&o.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(o.zip!==void 0&&!a?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:s,enc:l}=o;if(typeof s!=`string`||!s)throw new D(`missing JWE Algorithm (alg) in JWE Header`);if(typeof l!=`string`||!l)throw new D(`missing JWE Encryption Algorithm (enc) in JWE Header`);let u=r&&It(`keyManagementAlgorithms`,r.keyManagementAlgorithms),d=r&&It(`contentEncryptionAlgorithms`,r.contentEncryptionAlgorithms);if(u&&!u.has(s)||!u&&s.startsWith(`PBES2`))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(d&&!d.has(l))throw new ie(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let p;e.encrypted_key!==void 0&&(p=P(e.encrypted_key,`encrypted_key`,D));let m=!1;typeof t==`function`&&(t=await t(a,e),m=!0),Y(s===`dir`?l:s,t,`decrypt`);let h=await U(t,s),g;try{g=await Pt(s,h,p,o,r)}catch(e){if(e instanceof TypeError||e instanceof D||e instanceof T)throw e;g=M(l)}let _,v;e.iv!==void 0&&(_=P(e.iv,`iv`,D)),e.tag!==void 0&&(v=P(e.tag,`tag`,D));let y=e.protected===void 0?new Uint8Array:c(e.protected),ee;ee=e.aad===void 0?y:i(y,c(`.`),c(e.aad));let b=P(e.ciphertext,`ciphertext`,D),x=await De(l,g,b,_,v,ee),S={plaintext:x};if(o.zip===`DEF`){let e=r?.maxDecompressedLength??25e4;if(e===0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);S.plaintext=await Ht(x,e).catch(e=>{throw e instanceof D?e:new D(`Failed to decompress plaintext`,{cause:e})})}return e.protected!==void 0&&(S.protectedHeader=a),e.aad!==void 0&&(S.additionalAuthenticatedData=P(e.aad,`aad`,D)),e.unprotected!==void 0&&(S.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(S.unprotectedHeader=e.header),m?{...S,key:h}:S}async function Wt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new D(`Compact JWE must be a string or Uint8Array`);let{0:i,1:a,2:o,3:s,4:c,length:l}=e.split(`.`);if(l!==5)throw new D(`Invalid Compact JWE`);let u=await Ut({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,r),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t==`function`?{...d,key:u.key}:d}async function Gt(e,t,n){if(!F(e))throw new D(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(F))throw new D(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new D(`JWE Recipients has no members`);for(let r of e.recipients)try{return await Ut({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,n)}catch{}throw new E}var Kt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this.#e=e}setKeyManagementParameters(e){return N(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return N(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return N(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return N(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return N(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return N(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new D(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!I(this.#t,this.#r,this.#n))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let n={...this.#t,...this.#r,...this.#n};if(q(D,new Map,t?.crit,this.#t,n),n.zip!==void 0&&n.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(n.zip!==void 0&&!this.#t?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:r,enc:a}=n;if(typeof r!=`string`||!r)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof a!=`string`||!a)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);let o;if(this.#a&&(r===`dir`||r===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${r}`);Y(r===`dir`?a:r,e,`encrypt`);let s;{let n,i=await U(e,r);({cek:s,encryptedKey:o,parameters:n}=await Ft(r,a,i,this.#a,this.#s)),n&&(t&&Oe in t?this.#r?this.#r={...this.#r,...n}:this.setUnprotectedHeader(n):this.#t?this.#t={...this.#t,...n}:this.setProtectedHeader(n))}let l,u,d,f;if(this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array),this.#i){f=p(this.#i);let e=c(f);l=i(d,c(`.`),e)}else l=d;let m=this.#e;n.zip===`DEF`&&(m=await Vt(m).catch(e=>{throw new D(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:h,tag:g,iv:_}=await Ee(a,m,s,this.#o,l),v={ciphertext:p(h)};return _&&(v.iv=p(_)),g&&(v.tag=p(g)),o&&(v.encrypted_key=p(o)),f&&(v.aad=f),this.#t&&(v.protected=u),this.#n&&(v.unprotected=this.#n),this.#r&&(v.header=this.#r),v}},qt=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setUnprotectedHeader(e){return N(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}setKeyManagementParameters(e){return N(this.keyManagementParameters,`setKeyManagementParameters`),this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Jt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new qt(this,e,{crit:t?.crit});return this.#t.push(n),n}setProtectedHeader(e){return N(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return N(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new D(`at least one recipient must be added`);if(this.#t.length===1){let[e]=this.#t,t=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),n={ciphertext:t.ciphertext,iv:t.iv,recipients:[{}],tag:t.tag};return t.aad&&(n.aad=t.aad),t.protected&&(n.protected=t.protected),t.unprotected&&(n.unprotected=t.unprotected),t.encrypted_key&&(n.recipients[0].encrypted_key=t.encrypted_key),t.header&&(n.recipients[0].header=t.header),n}let e;for(let t=0;t<this.#t.length;t++){let n=this.#t[t];if(!I(this.#n,this.#r,n.unprotectedHeader))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let r={...this.#n,...this.#r,...n.unprotectedHeader},{alg:i}=r;if(typeof i!=`string`||!i)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(i===`dir`||i===`ECDH-ES`)throw new D(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof r.enc!=`string`||!r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=r.enc;else if(e!==r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if(q(D,new Map,n.options.crit,this.#n,r),r.zip!==void 0&&r.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(r.zip!==void 0&&!this.#n?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}let t=M(e),n={ciphertext:``,recipients:[]};for(let r=0;r<this.#t.length;r++){let i=this.#t[r],a={};if(n.recipients.push(a),r===0){let e=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters(i.keyManagementParameters).encrypt(i.key,{...i.options,[Oe]:!0});n.ciphertext=e.ciphertext,n.iv=e.iv,n.tag=e.tag,e.aad&&(n.aad=e.aad),e.protected&&(n.protected=e.protected),e.unprotected&&(n.unprotected=e.unprotected),a.encrypted_key=e.encrypted_key,e.header&&(a.header=e.header);continue}let o=i.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;Y(o===`dir`?e:o,i.key,`encrypt`);let s=await U(i.key,o),{encryptedKey:c,parameters:l}=await Ft(o,e,s,t,i.keyManagementParameters);a.encrypted_key=p(c),(i.unprotectedHeader||l)&&(a.header={...i.unprotectedHeader,...l})}return n}};async function Yt(e,r,a){if(!F(e))throw new O(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new O(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new O(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new O(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new O(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!F(e.header))throw new O(`JWS Unprotected Header incorrect type`);let o={};if(e.protected)try{let t=f(e.protected);o=JSON.parse(n.decode(t))}catch{throw new O(`JWS Protected Header is invalid`)}if(!I(o,e.header))throw new O(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let s={...o,...e.header},l=q(O,new Map([[`b64`,!0]]),a?.crit,o,s),u=!0;if(l.has(`b64`)&&(u=o.b64,typeof u!=`boolean`))throw new O(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:d}=s;if(typeof d!=`string`||!d)throw new O(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let p=a&&It(`algorithms`,a.algorithms);if(p&&!p.has(d))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof e.payload!=`string`)throw new O(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new O(`JWS Payload must be a string or an Uint8Array instance`);let m=!1;typeof r==`function`&&(r=await r(o,e),m=!0),Y(d,r,`verify`);let h=i(e.protected===void 0?new Uint8Array:c(e.protected),c(`.`),typeof e.payload==`string`?u?c(e.payload):t.encode(e.payload):e.payload),g=P(e.signature,`signature`,O),_=await U(r,d);if(!await Ze(d,_,g,h))throw new ue;let v;v=u?P(e.payload,`payload`,O):typeof e.payload==`string`?t.encode(e.payload):e.payload;let y={payload:v};return e.protected!==void 0&&(y.protectedHeader=o),e.header!==void 0&&(y.unprotectedHeader=e.header),m?{...y,key:_}:y}async function Xt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new O(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new O(`Invalid Compact JWS`);let c=await Yt({payload:a,protected:i,signature:o},t,r),l={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t==`function`?{...l,key:c.key}:l}async function Zt(e,t,n){if(!F(e))throw new O(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(F))throw new O(`JWS Signatures missing or incorrect type`);for(let r of e.signatures)try{return await Yt({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,n)}catch{}throw new ue}const X=e=>Math.floor(e.getTime()/1e3),Qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Z(e){let t=Qt.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}function Q(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const $t=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,en=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function tn(e,t,r={}){let i;try{i=JSON.parse(n.decode(t))}catch{}if(!F(i))throw new k(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=r;if(a&&(typeof e.typ!=`string`||$t(e.typ)!==$t(a)))throw new w(`unexpected "typ" JWT header value`,i,`typ`,`check_failed`);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=r,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!(e in i))throw new w(`missing required "${e}" claim`,i,e,`missing`);if(s&&!(Array.isArray(s)?s:[s]).includes(i.iss))throw new w(`unexpected "iss" claim value`,i,`iss`,`check_failed`);if(c&&i.sub!==c)throw new w(`unexpected "sub" claim value`,i,`sub`,`check_failed`);if(l&&!en(i.aud,typeof l==`string`?[l]:l))throw new w(`unexpected "aud" claim value`,i,`aud`,`check_failed`);let f;switch(typeof r.clockTolerance){case`string`:f=Z(r.clockTolerance);break;case`number`:f=r.clockTolerance;break;case`undefined`:f=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:p}=r,m=X(p||new Date);if((i.iat!==void 0||u)&&typeof i.iat!=`number`)throw new w(`"iat" claim must be a number`,i,`iat`,`invalid`);if(i.nbf!==void 0){if(typeof i.nbf!=`number`)throw new w(`"nbf" claim must be a number`,i,`nbf`,`invalid`);if(i.nbf>m+f)throw new w(`"nbf" claim timestamp check failed`,i,`nbf`,`check_failed`)}if(i.exp!==void 0){if(typeof i.exp!=`number`)throw new w(`"exp" claim must be a number`,i,`exp`,`invalid`);if(i.exp<=m-f)throw new re(`"exp" claim timestamp check failed`,i,`exp`,`check_failed`)}if(u){let e=m-i.iat,t=typeof u==`number`?u:Z(u);if(e-f>t)throw new re(`"iat" claim timestamp check failed (too far in the past)`,i,`iat`,`check_failed`);if(e<0-f)throw new w(`"iat" claim timestamp check failed (it should be in the past)`,i,`iat`,`check_failed`)}return i}var nn=class{#e;constructor(e){if(!F(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return t.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e==`number`?this.#e.nbf=Q(`setNotBefore`,e):e instanceof Date?this.#e.nbf=Q(`setNotBefore`,X(e)):this.#e.nbf=X(new Date)+Z(e)}set exp(e){typeof e==`number`?this.#e.exp=Q(`setExpirationTime`,e):e instanceof Date?this.#e.exp=Q(`setExpirationTime`,X(e)):this.#e.exp=X(new Date)+Z(e)}set iat(e){e===void 0?this.#e.iat=X(new Date):e instanceof Date?this.#e.iat=Q(`setIssuedAt`,X(e)):typeof e==`string`?this.#e.iat=Q(`setIssuedAt`,X(new Date)+Z(e)):this.#e.iat=Q(`setIssuedAt`,e)}};async function rn(e,t,n){let r=await Xt(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new k(`JWTs MUST NOT use unencoded payload`);let i={payload:tn(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function an(e,t,n){let r=await Wt(e,t,n),i=tn(r.protectedHeader,r.plaintext,n),{protectedHeader:a}=r;if(a.iss!==void 0&&a.iss!==i.iss)throw new w(`replicated "iss" claim header parameter mismatch`,i,`iss`,`mismatch`);if(a.sub!==void 0&&a.sub!==i.sub)throw new w(`replicated "sub" claim header parameter mismatch`,i,`sub`,`mismatch`);if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new w(`replicated "aud" claim header parameter mismatch`,i,`aud`,`mismatch`);let o={payload:i,protectedHeader:a};return typeof t==`function`?{...o,key:r.key}:o}var on=class{#e;constructor(e){this.#e=new Kt(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this.#e.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}},sn=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return N(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return N(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new O(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!I(this.#t,this.#n))throw new O(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this.#t,...this.#n},r=q(O,new Map([[`b64`,!0]]),t?.crit,this.#t,n),a=!0;if(r.has(`b64`)&&(a=this.#t.b64,typeof a!=`boolean`))throw new O(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:o}=n;if(typeof o!=`string`||!o)throw new O(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);Y(o,e,`sign`);let s,l;a?(s=p(this.#e),l=c(s)):(l=this.#e,s=``);let u,d;this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array);let f=i(d,c(`.`),l),m={signature:p(await Xe(o,await U(e,o),f)),payload:s};return this.#n&&(m.header=this.#n),this.#t&&(m.protected=u),m}},cn=class{#e;constructor(e){this.#e=new sn(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){let n=await this.#e.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}},ln=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setProtectedHeader(e){return N(this.protectedHeader,`setProtectedHeader`),this.protectedHeader=e,this}setUnprotectedHeader(e){return N(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}addSignature(...e){return this.#e.addSignature(...e)}sign(...e){return this.#e.sign(...e)}done(){return this.#e}},un=class{#e;#t=[];constructor(e){this.#e=e}addSignature(e,t){let n=new ln(this,e,t);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new O(`at least one signature must be added`);let e={signatures:[],payload:``};for(let t=0;t<this.#t.length;t++){let n=this.#t[t],r=new sn(this.#e);r.setProtectedHeader(n.protectedHeader),r.setUnprotectedHeader(n.unprotectedHeader);let{payload:i,...a}=await r.sign(n.key,n.options);if(t===0)e.payload=i;else if(e.payload!==i)throw new O(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(a)}return e}},dn=class{#e;#t;constructor(e={}){this.#t=new nn(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new cn(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes(`b64`)&&this.#e.b64===!1)throw new k(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}},fn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#s=new nn(e)}setIssuer(e){return this.#s.iss=e,this}setSubject(e){return this.#s.sub=e,this}setAudience(e){return this.#s.aud=e,this}setJti(e){return this.#s.jti=e,this}setNotBefore(e){return this.#s.nbf=e,this}setExpirationTime(e){return this.#s.exp=e,this}setIssuedAt(e){return this.#s.iat=e,this}setProtectedHeader(e){return N(this.#r,`setProtectedHeader`),this.#r=e,this}setKeyManagementParameters(e){return N(this.#n,`setKeyManagementParameters`),this.#n=e,this}setContentEncryptionKey(e){return N(this.#e,`setContentEncryptionKey`),this.#e=e,this}setInitializationVector(e){return N(this.#t,`setInitializationVector`),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(e,t){let n=new on(this.#s.data());return this.#r&&(this.#i||this.#a||this.#o)&&(this.#r={...this.#r,iss:this.#i?this.#s.iss:void 0,sub:this.#a?this.#s.sub:void 0,aud:this.#o?this.#s.aud:void 0}),n.setProtectedHeader(this.#r),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#n&&n.setKeyManagementParameters(this.#n),n.encrypt(e,t)}};const $=(e,t)=>{if(typeof e!=`string`||!e)throw new ae(`${t} missing or invalid`)};async function pn(e,t){let n;if(L(e))n=e;else if(fe(e))n=await At(e);else throw TypeError(S(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$(n.alg,`"alg" (Algorithm) Parameter`),$(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$(n.crv,`"crv" (Curve) Parameter`),$(n.x,`"x" (X Coordinate) Parameter`),$(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$(n.e,`"e" (Exponent) Parameter`),$(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:$(n.k,`"k" (Key Value) Parameter`),r={k:n.k,kty:n.kty};break;default:throw new T(`"kty" (Key Type) Parameter missing or unsupported`)}let i=c(JSON.stringify(r));return p(await ke(t,i))}async function mn(e,t){t??=`sha256`;let n=await pn(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}async function hn(e,t){let n={...e,...t?.header};if(!F(n.jwk))throw new O(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let r=await Et({...n.jwk,ext:!0},n.alg);if(r instanceof Uint8Array||r.type!==`public`)throw new O(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return r}function gn(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new T(`Unsupported "alg" value for a JSON Web Key Set`)}}function _n(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(vn)}function vn(e){return F(e)}var yn=class{#e;#t=new WeakMap;constructor(e){if(!_n(e))throw new oe(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=gn(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new se;if(s!==1){let e=new ce,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await bn(t,e,n)}catch{}},e}return bn(this.#t,o,n)}};async function bn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await Et({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new oe(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function xn(e){let t=new yn(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Sn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Cn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Cn=`jose/v6.2.3`);const wn=Symbol();async function Tn(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new le:e});if(i.status!==200)throw new C(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new C(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const En=Symbol();function Dn(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!F(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,F))}var On=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Cn&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Cn),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[wn],t?.[En]!==void 0&&(this.#l=t?.[En],Dn(t?.[En],this.#r)&&(this.#i=this.#l.uat,this.#c=xn(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof se&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Sn()&&(this.#a=void 0),this.#a||=Tn(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=xn(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function kn(e,t){let n=new On(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}var An=class{#e;constructor(e={}){this.#e=new nn(e)}encode(){return`${p(JSON.stringify({alg:`none`}))}.${p(this.#e.data())}.`}setIssuer(e){return this.#e.iss=e,this}setSubject(e){return this.#e.sub=e,this}setAudience(e){return this.#e.aud=e,this}setJti(e){return this.#e.jti=e,this}setNotBefore(e){return this.#e.nbf=e,this}setExpirationTime(e){return this.#e.exp=e,this}setIssuedAt(e){return this.#e.iat=e,this}static decode(e,t){if(typeof e!=`string`)throw new k(`Unsecured JWT must be a string`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3||a!==``)throw new k(`Invalid Unsecured JWT`);let s;try{if(s=JSON.parse(n.decode(f(r))),s.alg!==`none`)throw Error()}catch{throw new k(`Invalid Unsecured JWT`)}return{payload:tn(s,f(i),t),header:s}}};function jn(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e)if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`);try{if(typeof t!=`string`||!t)throw Error();let e=JSON.parse(n.decode(f(t)));if(!F(e))throw Error();return e}catch{throw TypeError(`Invalid Token or Protected Header formatting`)}}function Mn(e){if(typeof e!=`string`)throw new k(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:r}=e.split(`.`);if(r===5)throw new k(`Only JWTs using Compact JWS serialization can be decoded`);if(r!==3)throw new k(`Invalid JWT`);if(!t)throw new k(`JWTs must contain a payload`);let i;try{i=f(t)}catch{throw new k(`Failed to base64url decode the payload`)}let a;try{a=JSON.parse(n.decode(i))}catch{throw new k(`Failed to parse the decoded payload as JSON`)}if(!F(a))throw new k(`Invalid JWT Claims Set`);return a}function Nn(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new T(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Pn(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:case`EdDSA`:r=[`sign`,`verify`],n={name:`Ed25519`};break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:r=[`sign`,`verify`],n={name:e};break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:n={name:`X25519`};break;default:throw new T(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`)}break}default:throw new T(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(n,t?.extractable??!1,r)}async function Fn(e,t){let n,r,i;switch(e){case`HS256`:case`HS384`:case`HS512`:n=parseInt(e.slice(-3),10),r={name:`HMAC`,hash:`SHA-${n}`,length:n},i=[`sign`,`verify`];break;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(n>>3));case`A128KW`:case`A192KW`:case`A256KW`:n=parseInt(e.slice(1,4),10),r={name:`AES-KW`,length:n},i=[`wrapKey`,`unwrapKey`];break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:n=parseInt(e.slice(1,4),10),r={name:`AES-GCM`,length:n},i=[`encrypt`,`decrypt`];break;default:throw new T(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(r,t?.extractable??!1,i)}const In=`WebCryptoAPI`;export{on as CompactEncrypt,cn as CompactSign,hn as EmbeddedJWK,fn as EncryptJWT,Kt as FlattenedEncrypt,sn as FlattenedSign,Jt as GeneralEncrypt,un as GeneralSign,dn as SignJWT,An as UnsecuredJWT,d as base64url,pn as calculateJwkThumbprint,mn as calculateJwkThumbprintUri,Wt as compactDecrypt,Xt as compactVerify,xn as createLocalJWKSet,kn as createRemoteJWKSet,In as cryptoRuntime,wn as customFetch,Mn as decodeJwt,jn as decodeProtectedHeader,ne as errors,At as exportJWK,kt as exportPKCS8,Ot as exportSPKI,Ut as flattenedDecrypt,Yt as flattenedVerify,Gt as generalDecrypt,Zt as generalVerify,Pn as generateKeyPair,Fn as generateSecret,Et as importJWK,Tt as importPKCS8,Ct as importSPKI,wt as importX509,En as jwksCache,an as jwtDecrypt,rn as jwtVerify};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) Microsoft
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ParseError {
|
|
2
|
+
readonly error: number;
|
|
3
|
+
readonly offset: number;
|
|
4
|
+
readonly length: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface ParseOptions {
|
|
8
|
+
readonly allowEmptyContent?: boolean | undefined;
|
|
9
|
+
readonly allowTrailingComma?: boolean | undefined;
|
|
10
|
+
readonly disallowComments?: boolean | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export declare function parse(text: string, errors?: ParseError[], options?: ParseOptions): unknown;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
function e(e,i=!1){let a=e.length,o=0,s=``,c=0,l=16,u=0,d=0,f=0,p=0,m=0;function h(t,n){let r=0,i=0;for(;r<t||!n;){let t=e.charCodeAt(o);if(t>=48&&t<=57)i=i*16+t-48;else if(t>=65&&t<=70)i=i*16+t-65+10;else if(t>=97&&t<=102)i=i*16+t-97+10;else break;o++,r++}return r<t&&(i=-1),i}function g(e){o=e,s=``,c=0,l=16,m=0}function _(){let t=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&r(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&r(e.charCodeAt(o)))for(o++;o<e.length&&r(e.charCodeAt(o));)o++;else return m=3,e.substring(t,o);let n=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&r(e.charCodeAt(o))){for(o++;o<e.length&&r(e.charCodeAt(o));)o++;n=o}else m=3;return e.substring(t,n)}function v(){let t=``,r=o;for(;;){if(o>=a){t+=e.substring(r,o),m=2;break}let i=e.charCodeAt(o);if(i===34){t+=e.substring(r,o),o++;break}if(i===92){if(t+=e.substring(r,o),o++,o>=a){m=2;break}switch(e.charCodeAt(o++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
|
|
2
|
+
`;break;case 114:t+=`\r`;break;case 116:t+=` `;break;case 117:let e=h(4,!0);e>=0?t+=String.fromCharCode(e):m=4;break;default:m=5}r=o;continue}if(i>=0&&i<=31)if(n(i)){t+=e.substring(r,o),m=2;break}else m=6;o++}return t}function y(){if(s=``,m=0,c=o,d=u,p=f,o>=a)return c=a,l=17;let i=e.charCodeAt(o);if(t(i)){do o++,s+=String.fromCharCode(i),i=e.charCodeAt(o);while(t(i));return l=15}if(n(i))return o++,s+=String.fromCharCode(i),i===13&&e.charCodeAt(o)===10&&(o++,s+=`
|
|
3
|
+
`),u++,f=o,l=14;switch(i){case 123:return o++,l=1;case 125:return o++,l=2;case 91:return o++,l=3;case 93:return o++,l=4;case 58:return o++,l=6;case 44:return o++,l=5;case 34:return o++,s=v(),l=10;case 47:let t=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<a&&!n(e.charCodeAt(o));)o++;return s=e.substring(t,o),l=12}if(e.charCodeAt(o+1)===42){o+=2;let r=a-1,i=!1;for(;o<r;){let t=e.charCodeAt(o);if(t===42&&e.charCodeAt(o+1)===47){o+=2,i=!0;break}o++,n(t)&&(t===13&&e.charCodeAt(o)===10&&o++,u++,f=o)}return i||(o++,m=1),s=e.substring(t,o),l=13}return s+=String.fromCharCode(i),o++,l=16;case 45:if(s+=String.fromCharCode(i),o++,o===a||!r(e.charCodeAt(o)))return l=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return s+=_(),l=11;default:for(;o<a&&b(i);)o++,i=e.charCodeAt(o);if(c!==o){switch(s=e.substring(c,o),s){case`true`:return l=8;case`false`:return l=9;case`null`:return l=7}return l=16}return s+=String.fromCharCode(i),o++,l=16}}function b(e){if(t(e)||n(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function x(){let e;do e=y();while(e>=12&&e<=15);return e}return{setPosition:g,getPosition:()=>o,scan:i?x:y,getToken:()=>l,getTokenValue:()=>s,getTokenOffset:()=>c,getTokenLength:()=>o-c,getTokenStartLine:()=>d,getTokenStartCharacter:()=>c-p,getTokenError:()=>m}}function t(e){return e===32||e===9}function n(e){return e===10||e===13}function r(e){return e>=48&&e<=57}var i;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(i||={});const a=Array(20).fill(0).map((e,t)=>` `.repeat(t)),o={" ":{"\n":Array(200).fill(0).map((e,t)=>`
|
|
4
|
+
`+` `.repeat(t)),"\r":Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
|
|
5
|
+
`+` `.repeat(t))}," ":{"\n":Array(200).fill(0).map((e,t)=>`
|
|
6
|
+
`+` `.repeat(t)),"\r":Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
|
|
7
|
+
`+` `.repeat(t))}},s=[`
|
|
8
|
+
`,`\r`,`\r
|
|
9
|
+
`];function c(t,n,r){let i,c,p,m,h;if(n){for(m=n.offset,h=m+n.length,p=m;p>0&&!f(t,p-1);)p--;let e=h;for(;e<t.length&&!f(t,e);)e++;c=t.substring(p,e),i=u(c,r)}else c=t,i=0,p=0,m=0,h=t.length;let g=d(r,t),_=s.includes(g),v=0,y=0,b;b=r.insertSpaces?a[r.tabSize||4]??l(a[1],r.tabSize||4):` `;let x=b===` `?` `:` `,S=e(c,!1),C=!1;function w(){if(v>1)return l(g,v)+l(b,i+y);let e=b.length*(i+y);return!_||e>o[x][g].length?g+l(b,i+y):e<=0?g:o[x][g][e]}function T(){let e=S.scan();for(v=0;e===15||e===14;)e===14&&r.keepLines?v+=1:e===14&&(v=1),e=S.scan();return C=e===16||S.getTokenError()!==0,e}let E=[];function D(e,r,i){!C&&(!n||r<h&&i>m)&&t.substring(r,i)!==e&&E.push({offset:r,length:i-r,content:e})}let O=T();if(r.keepLines&&v>0&&D(l(g,v),0,0),O!==17){let e=S.getTokenOffset()+p;D(b.length*i<20&&r.insertSpaces?a[b.length*i]:l(b,i),p,e)}for(;O!==17;){let e=S.getTokenOffset()+S.getTokenLength()+p,t=T(),n=``,i=!1;for(;v===0&&(t===12||t===13);){let r=S.getTokenOffset()+p;D(a[1],e,r),e=S.getTokenOffset()+S.getTokenLength()+p,i=t===12,n=i?w():``,t=T()}if(t===2)O!==1&&y--,r.keepLines&&v>0||!r.keepLines&&O!==1?n=w():r.keepLines&&(n=a[1]);else if(t===4)O!==3&&y--,r.keepLines&&v>0||!r.keepLines&&O!==3?n=w():r.keepLines&&(n=a[1]);else{switch(O){case 3:case 1:y++,n=r.keepLines&&v>0||!r.keepLines?w():a[1];break;case 5:n=r.keepLines&&v>0||!r.keepLines?w():a[1];break;case 12:n=w();break;case 13:v>0?n=w():i||(n=a[1]);break;case 6:r.keepLines&&v>0?n=w():i||(n=a[1]);break;case 10:r.keepLines&&v>0?n=w():t===6&&!i&&(n=``);break;case 7:case 8:case 9:case 11:case 2:case 4:r.keepLines&&v>0?n=w():(t===12||t===13)&&!i?n=a[1]:t!==5&&t!==17&&(C=!0);break;case 16:C=!0;break}v>0&&(t===12||t===13)&&(n=w())}t===17&&(n=r.keepLines&&v>0?w():r.insertFinalNewline?g:``);let o=S.getTokenOffset()+p;D(n,e,o),O=t}return E}function l(e,t){let n=``;for(let r=0;r<t;r++)n+=e;return n}function u(e,t){let n=0,r=0,i=t.tabSize||4;for(;n<e.length;){let t=e.charAt(n);if(t===a[1])r++;else if(t===` `)r+=i;else break;n++}return Math.floor(r/i)}function d(e,t){for(let e=0;e<t.length;e++){let n=t.charAt(e);if(n===`\r`)return e+1<t.length&&t.charAt(e+1)===`
|
|
10
|
+
`?`\r
|
|
11
|
+
`:`\r`;if(n===`
|
|
12
|
+
`)return`
|
|
13
|
+
`}return e&&e.eol||`
|
|
14
|
+
`}function f(e,t){return`\r
|
|
15
|
+
`.indexOf(e.charAt(t))!==-1}var p;(function(e){e.DEFAULT={allowTrailingComma:!1}})(p||={});function m(e,t){let n=[],r={},i,a={value:{},offset:0,length:0,type:`object`,parent:void 0},o=!1;function s(e,t,n,r){a.value=e,a.offset=t,a.length=n,a.type=r,a.colonOffset=void 0,i=a}try{S(e,{onObjectBegin:(e,a)=>{if(t<=e)throw r;i=void 0,o=t>e,n.push(``)},onObjectProperty:(e,i,a)=>{if(t<i||(s(e,i,a,`property`),n[n.length-1]=e,t<=i+a))throw r},onObjectEnd:(e,a)=>{if(t<=e)throw r;i=void 0,n.pop()},onArrayBegin:(e,a)=>{if(t<=e)throw r;i=void 0,n.push(0)},onArrayEnd:(e,a)=>{if(t<=e)throw r;i=void 0,n.pop()},onLiteralValue:(e,n,i)=>{if(t<n||(s(e,n,i,w(e)),t<=n+i))throw r},onSeparator:(e,a,s)=>{if(t<=a)throw r;if(e===`:`&&i&&i.type===`property`)i.colonOffset=a,o=!1,i=void 0;else if(e===`,`){let e=n[n.length-1];typeof e==`number`?n[n.length-1]=e+1:(o=!0,n[n.length-1]=``),i=void 0}}})}catch(e){if(e!==r)throw e}return{path:n,previousNode:i,isAtPropertyKey:o,matches:e=>{let t=0;for(let r=0;t<e.length&&r<n.length;r++)if(e[t]===n[r]||e[t]===`*`)t++;else if(e[t]!==`**`)return!1;return t===e.length}}}function h(e,t=[],n=p.DEFAULT){let r=null,i=[],a=[];function o(e){Array.isArray(i)?i.push(e):r!==null&&(i[r]=e)}return S(e,{onObjectBegin:()=>{let e={};o(e),a.push(i),i=e,r=null},onObjectProperty:e=>{r=e},onObjectEnd:()=>{i=a.pop()},onArrayBegin:()=>{let e=[];o(e),a.push(i),i=e,r=null},onArrayEnd:()=>{i=a.pop()},onLiteralValue:o,onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n),i[0]}function g(e,t=[],n=p.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function i(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function a(e){return r.children.push(e),e}S(e,{onObjectBegin:e=>{r=a({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=a({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{i(e+t),r.length=e+t-r.offset,r=r.parent,i(e+t)},onArrayBegin:(e,t)=>{r=a({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,i(e+t)},onLiteralValue:(e,t,n)=>{a({type:w(e),offset:t,length:n,parent:r,value:e}),i(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&i(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let o=r.children[0];return o&&delete o.parent,o}function _(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}function v(e){if(!e.parent||!e.parent.children)return[];let t=v(e.parent);if(e.parent.type===`property`){let n=e.parent.children[0].value;t.push(n)}else if(e.parent.type===`array`){let n=e.parent.children.indexOf(e);n!==-1&&t.push(n)}return t}function y(e){switch(e.type){case`array`:return e.children.map(y);case`object`:let t=Object.create(null);for(let n of e.children){let e=n.children[1];e&&(t[n.children[0].value]=y(e))}return t;case`null`:case`string`:case`number`:case`boolean`:return e.value;default:return}}function b(e,t,n=!1){return t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}function x(e,t,n=!1){if(b(e,t,n)){let r=e.children;if(Array.isArray(r))for(let e=0;e<r.length&&r[e].offset<=t;e++){let i=x(r[e],t,n);if(i)return i}return e}}function S(t,n,r=p.DEFAULT){let i=e(t,!1),a=[],o=0;function s(e){return e?()=>o===0&&e(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function c(e){return e?t=>o===0&&e(t,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function l(e){return e?t=>o===0&&e(t,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>a.slice()):()=>!0}function u(e){return e?()=>{o>0?o++:e(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>a.slice())===!1&&(o=1)}:()=>!0}function d(e){return e?()=>{o>0&&o--,o===0&&e(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter())}:()=>!0}let f=u(n.onObjectBegin),m=l(n.onObjectProperty),h=d(n.onObjectEnd),g=u(n.onArrayBegin),_=d(n.onArrayEnd),v=l(n.onLiteralValue),y=c(n.onSeparator),b=s(n.onComment),x=c(n.onError),S=r&&r.disallowComments,C=r&&r.allowTrailingComma;function w(){for(;;){let e=i.scan();switch(i.getTokenError()){case 4:T(14);break;case 5:T(15);break;case 3:T(13);break;case 1:S||T(11);break;case 2:T(12);break;case 6:T(16);break}switch(e){case 12:case 13:S?T(10):b();break;case 16:T(1);break;case 15:case 14:break;default:return e}}}function T(e,t=[],n=[]){if(x(e),t.length+n.length>0){let e=i.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){w();break}else if(n.indexOf(e)!==-1)break;e=w()}}}function E(e){let t=i.getTokenValue();return e?v(t):(m(t),a.push(t)),w(),!0}function D(){switch(i.getToken()){case 11:let e=i.getTokenValue(),t=Number(e);isNaN(t)&&(T(2),t=0),v(t);break;case 7:v(null);break;case 8:v(!0);break;case 9:v(!1);break;default:return!1}return w(),!0}function O(){return i.getToken()===10?(E(!1),i.getToken()===6?(y(`:`),w(),j()||T(4,[],[2,5])):T(5,[],[2,5]),a.pop(),!0):(T(3,[],[2,5]),!1)}function k(){f(),w();let e=!1;for(;i.getToken()!==2&&i.getToken()!==17;){if(i.getToken()===5){if(e||T(4,[],[]),y(`,`),w(),i.getToken()===2&&C)break}else e&&T(6,[],[]);O()||T(4,[],[2,5]),e=!0}return h(),i.getToken()===2?w():T(7,[2],[]),!0}function A(){g(),w();let e=!0,t=!1;for(;i.getToken()!==4&&i.getToken()!==17;){if(i.getToken()===5){if(t||T(4,[],[]),y(`,`),w(),i.getToken()===4&&C)break}else t&&T(6,[],[]);e?(a.push(0),e=!1):a[a.length-1]++,j()||T(4,[],[4,5]),t=!0}return _(),e||a.pop(),i.getToken()===4?w():T(8,[4],[]),!0}function j(){switch(i.getToken()){case 3:return A();case 1:return k();case 10:return E(!0);default:return D()}}return w(),i.getToken()===17?r.allowEmptyContent?!0:(T(4,[],[]),!1):j()?(i.getToken()!==17&&T(9,[],[]),!0):(T(4,[],[]),!1)}function C(t,n){let r=e(t),i=[],a,o=0,s;do switch(s=r.getPosition(),a=r.scan(),a){case 12:case 13:case 17:o!==s&&i.push(t.substring(o,s)),n!==void 0&&i.push(r.getTokenValue().replace(/[^\r\n]/g,n)),o=r.getPosition();break}while(a!==17);return i.join(``)}function w(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}function T(e,t,n,r){let i=t.slice(),a=g(e,[]),o,s;for(;i.length>0&&(s=i.pop(),o=_(a,i),o===void 0&&n!==void 0);)n=typeof s==`string`?{[s]:n}:[n];if(!o){if(n===void 0)throw Error(`Can not delete in empty document`);return E(e,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(n)},r)}else if(o.type===`object`&&typeof s==`string`&&Array.isArray(o.children)){let t=_(o,[s]);if(t!==void 0)if(n===void 0){if(!t.parent)throw Error(`Malformed AST`);let n=o.children.indexOf(t.parent),i,a=t.parent.offset+t.parent.length;if(n>0){let e=o.children[n-1];i=e.offset+e.length}else i=o.offset+1,o.children.length>1&&(a=o.children[1].offset);return E(e,{offset:i,length:a-i,content:``},r)}else return E(e,{offset:t.offset,length:t.length,content:JSON.stringify(n)},r);else{if(n===void 0)return[];let t=`${JSON.stringify(s)}: ${JSON.stringify(n)}`,i=r.getInsertionIndex?r.getInsertionIndex(o.children.map(e=>e.children[0].value)):o.children.length,a;if(i>0){let e=o.children[i-1];a={offset:e.offset+e.length,length:0,content:`,`+t}}else a=o.children.length===0?{offset:o.offset+1,length:0,content:t}:{offset:o.offset+1,length:0,content:t+`,`};return E(e,a,r)}}else if(o.type===`array`&&typeof s==`number`&&Array.isArray(o.children)){let t=s;if(t===-1){let t=`${JSON.stringify(n)}`,i;if(o.children.length===0)i={offset:o.offset+1,length:0,content:t};else{let e=o.children[o.children.length-1];i={offset:e.offset+e.length,length:0,content:`,`+t}}return E(e,i,r)}else if(n===void 0&&o.children.length>=0){let t=s,n=o.children[t],i;if(o.children.length===1)i={offset:o.offset+1,length:o.length-2,content:``};else if(o.children.length-1===t){let e=o.children[t-1],n=e.offset+e.length;i={offset:n,length:o.offset+o.length-2-n,content:``}}else i={offset:n.offset,length:o.children[t+1].offset-n.offset,content:``};return E(e,i,r)}else if(n!==void 0){let t,i=`${JSON.stringify(n)}`;if(!r.isArrayInsertion&&o.children.length>s){let e=o.children[s];t={offset:e.offset,length:e.length,content:i}}else if(o.children.length===0||s===0)t={offset:o.offset+1,length:0,content:o.children.length===0?i:i+`,`};else{let e=s>o.children.length?o.children.length:s,n=o.children[e-1];t={offset:n.offset+n.length,length:0,content:`,`+i}}return E(e,t,r)}else throw Error(`Can not ${n===void 0?`remove`:r.isArrayInsertion?`insert`:`modify`} Array index ${t} as length is not sufficient`)}else throw Error(`Can not add ${typeof s==`number`?`property`:`index`} to parent of type ${o.type}`)}function E(e,t,n){if(!n.formattingOptions)return[t];let r=D(e,t),i=t.offset,a=t.offset+t.content.length;if(t.length===0||t.content.length===0){for(;i>0&&!f(r,i-1);)i--;for(;a<r.length&&!f(r,a);)a++}let o=c(r,{offset:i,length:a-i},{...n.formattingOptions,keepLines:!1});for(let e=o.length-1;e>=0;e--){let t=o[e];r=D(r,t),i=Math.min(i,t.offset),a=Math.max(a,t.offset+t.length),a+=t.content.length-t.length}let s=e.length-(r.length-a)-i;return[{offset:i,length:s,content:r.substring(i,a)}]}function D(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}const O=e;var k;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(k||={});var A;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})(A||={});const j=m,M=h,N=g,P=_,F=x,I=v,L=y,R=S,z=C;var B;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(B||={});function V(e){switch(e){case 1:return`InvalidSymbol`;case 2:return`InvalidNumberFormat`;case 3:return`PropertyNameExpected`;case 4:return`ValueExpected`;case 5:return`ColonExpected`;case 6:return`CommaExpected`;case 7:return`CloseBraceExpected`;case 8:return`CloseBracketExpected`;case 9:return`EndOfFileExpected`;case 10:return`InvalidCommentToken`;case 11:return`UnexpectedEndOfComment`;case 12:return`UnexpectedEndOfString`;case 13:return`UnexpectedEndOfNumber`;case 14:return`InvalidUnicode`;case 15:return`InvalidEscapeCharacter`;case 16:return`InvalidCharacter`}return`<unknown ParseErrorCode>`}function H(e,t,n){return c(e,t,n)}function U(e,t,n,r){return T(e,t,n,r)}function W(e,t){let n=t.slice(0).sort((e,t)=>{let n=e.offset-t.offset;return n===0?e.length-t.length:n}),r=e.length;for(let t=n.length-1;t>=0;t--){let i=n[t];if(i.offset+i.length<=r)e=D(e,i);else throw Error(`Overlapping edit`);r=i.offset}return e}export{B as ParseErrorCode,k as ScanError,A as SyntaxKind,W as applyEdits,O as createScanner,P as findNodeAtLocation,F as findNodeAtOffset,H as format,j as getLocation,I as getNodePath,L as getNodeValue,U as modify,M as parse,N as parseTree,V as printParseErrorCode,z as stripComments,R as visit};
|