@shumai-one/shumai 0.5.2 → 0.5.3
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/bin/{chunk-zf5cyxnt.js → chunk-03zkxckm.js} +1 -1
- package/bin/{chunk-2w6gve12.js → chunk-04nqnkzs.js} +3 -3
- package/bin/{chunk-rw5h0n0s.js → chunk-157axqz1.js} +1 -1
- package/bin/{chunk-w9z27p0m.js → chunk-1tesbv8w.js} +1 -1
- package/bin/{chunk-vzdgsfkf.js → chunk-24da4wg9.js} +1 -1
- package/bin/chunk-24nx3krz.js +2 -0
- package/bin/{chunk-twpc640e.js → chunk-26am2rzm.js} +1 -1
- package/bin/{chunk-8ayz61rc.js → chunk-2pt9h882.js} +3 -3
- package/bin/{chunk-mn108p93.js → chunk-2rrcdhkj.js} +1 -1
- package/bin/{chunk-ryepy5er.js → chunk-2w2bknn2.js} +4 -4
- package/bin/{chunk-ypkkfwfb.js → chunk-3ahax79y.js} +2 -2
- package/bin/{chunk-zdzkjp4q.js → chunk-3fjgf7eb.js} +2 -2
- package/bin/{chunk-rmvhyqyb.js → chunk-3wcvema0.js} +3 -3
- package/bin/{chunk-kvwec0p3.js → chunk-40tmh04g.js} +2 -2
- package/bin/chunk-45p7d22e.js +2 -0
- package/bin/chunk-461gcgrs.js +2 -0
- package/bin/{chunk-p0j4wpa5.js → chunk-4bc3gqmn.js} +1 -1
- package/bin/{chunk-8tzfcqtb.js → chunk-4nkwe7dz.js} +1 -1
- package/bin/{chunk-eqr0znmc.js → chunk-59ayg5am.js} +1 -1
- package/bin/{chunk-8zgq5sav.js → chunk-5ebb2pdf.js} +2 -2
- package/bin/{chunk-n76w2wcr.js → chunk-5y3kx4kk.js} +1 -1
- package/bin/{chunk-d2dgazjj.js → chunk-68xsb3t8.js} +1 -1
- package/bin/{chunk-n9vp9nbg.js → chunk-6hs63sva.js} +30 -30
- package/bin/{chunk-bpxw19ez.js → chunk-6pwf7qa6.js} +1 -1
- package/bin/{chunk-f5z3096k.js → chunk-6sq6dfa1.js} +2 -2
- package/bin/chunk-87secbzy.js +1 -0
- package/bin/chunk-8pykp70z.js +1 -0
- package/bin/{chunk-3pm6q6kg.js → chunk-8ts3xkme.js} +1 -1
- package/bin/{chunk-rza95y4z.js → chunk-909h3qzp.js} +2 -2
- package/bin/{chunk-0v9srsdz.js → chunk-929abwgr.js} +1 -1
- package/bin/{chunk-j53sjkxt.js → chunk-9ca8a5f2.js} +1 -1
- package/bin/{chunk-2pw7xcrn.js → chunk-9fyb95r5.js} +1 -1
- package/bin/{chunk-mneeg71d.js → chunk-axeq2pq5.js} +2 -2
- package/bin/{chunk-r249n1xe.js → chunk-b3tkvdfk.js} +2 -2
- package/bin/{chunk-9ggwc289.js → chunk-b6dbqs39.js} +1 -1
- package/bin/{chunk-w73v578p.js → chunk-b88tdt79.js} +2 -2
- package/bin/{chunk-19q13a80.js → chunk-bcyvxp1c.js} +4 -4
- package/bin/{chunk-7qvvf0yd.js → chunk-bn0taqr3.js} +2 -2
- package/bin/chunk-cb37q6t0.js +1 -0
- package/bin/chunk-cfqny70c.js +3 -0
- package/bin/{chunk-ffj9cq9y.js → chunk-cqnected.js} +1 -1
- package/bin/{chunk-98mg3dpd.js → chunk-cvfznrnt.js} +4 -4
- package/bin/{chunk-951r2rx1.js → chunk-d1q1tn36.js} +1 -1
- package/bin/{chunk-0asthrjf.js → chunk-d1rjpbgv.js} +2 -2
- package/bin/{chunk-81dawvn4.js → chunk-eshwjf91.js} +2 -2
- package/bin/{chunk-04avc4fn.js → chunk-fa9yq17g.js} +26 -26
- package/bin/{chunk-m6v8vt2b.js → chunk-fnkkwna8.js} +2 -2
- package/bin/{chunk-3q5qkfkc.js → chunk-fpjvr3qw.js} +1 -1
- package/bin/{chunk-ggfx2b0f.js → chunk-fsr83nb1.js} +1 -1
- package/bin/{chunk-kzr6ecke.js → chunk-fznchvm7.js} +1 -1
- package/bin/chunk-g2z0c39g.js +1 -0
- package/bin/{chunk-5vqbzsjv.js → chunk-gvcjqcjf.js} +1 -1
- package/bin/{chunk-0ge2mm8j.js → chunk-hbnpx0a5.js} +1 -1
- package/bin/{chunk-tvkekn4z.js → chunk-hgy9rqt1.js} +1 -1
- package/bin/chunk-hk659cg2.css +1 -0
- package/bin/{chunk-8ny7wvzb.js → chunk-hn2g40r6.js} +1 -1
- package/bin/{chunk-0y4zq3y4.js → chunk-hsx4pns6.js} +1 -1
- package/bin/{chunk-bbcmhcvc.js → chunk-hy5ncvpf.js} +2 -2
- package/bin/{chunk-5nqvqvqp.js → chunk-j420aqk8.js} +3 -3
- package/bin/{chunk-t1yamxgk.js → chunk-k3ds96cb.js} +1 -1
- package/bin/{chunk-dppfek34.js → chunk-m41tbrvt.js} +2 -2
- package/bin/chunk-m9f21ye9.js +1 -0
- package/bin/chunk-md7pgk86.js +2 -0
- package/bin/chunk-me3zmpj5.js +14 -0
- package/bin/chunk-mg6sybt0.js +1 -0
- package/bin/{chunk-jgfye6nf.js → chunk-mzme3m82.js} +1 -1
- package/bin/{chunk-ce0bhc72.js → chunk-n08h1jgx.js} +1 -1
- package/bin/{chunk-ae6zgjhd.js → chunk-ncv8v6mj.js} +2 -2
- package/bin/{chunk-cx32wsa1.js → chunk-nmd1901j.js} +1 -1
- package/bin/{chunk-wnqxyqrg.js → chunk-np39aknv.js} +2 -2
- package/bin/{chunk-dche0gy0.js → chunk-p7zw53ep.js} +1 -1
- package/bin/{chunk-xr2v0d6y.js → chunk-ppb4aj0y.js} +4 -4
- package/bin/{chunk-15vsw36h.js → chunk-pwq6dbb5.js} +5 -5
- package/bin/chunk-q1gfypy3.js +2 -0
- package/bin/{chunk-0j22699g.js → chunk-q4qqmes7.js} +2 -2
- package/bin/{chunk-vm2pz2hm.js → chunk-q7t5zs7n.js} +2 -2
- package/bin/{chunk-e439kt05.js → chunk-qcpeefhr.js} +1 -1
- package/bin/{chunk-6rn094yj.js → chunk-qjdvs1s5.js} +1 -1
- package/bin/{chunk-9zgqjdx1.js → chunk-qqapw198.js} +2 -2
- package/bin/chunk-qx553512.js +211 -0
- package/bin/chunk-r3s1x5wp.js +1 -0
- package/bin/{chunk-rtaya5wc.js → chunk-rh8dy99a.js} +2 -2
- package/bin/{chunk-5rzxekn4.js → chunk-s0vfj06y.js} +1 -1
- package/bin/{chunk-4zksqvwj.js → chunk-s6g2mzpn.js} +2 -2
- package/bin/{chunk-zckxc8m6.js → chunk-s9sf37dv.js} +2 -2
- package/bin/{chunk-19jpn3r6.js → chunk-scvepfv8.js} +1 -1
- package/bin/chunk-sjbvt3wa.js +2 -0
- package/bin/{chunk-mn208vrv.js → chunk-srmx5z3v.js} +2 -2
- package/bin/{chunk-r776bhsg.js → chunk-srv5kvm4.js} +1 -1
- package/bin/{chunk-qmrg2jhs.js → chunk-t1h12r3q.js} +5 -5
- package/bin/{chunk-gvas3xkp.js → chunk-t6myw0jf.js} +1 -1
- package/bin/{chunk-z8e4wc59.js → chunk-t8jfp3vx.js} +1 -1
- package/bin/{chunk-15w79661.js → chunk-tqdde9bj.js} +1 -1
- package/bin/chunk-vk9ecq8n.js +2 -0
- package/bin/{chunk-d5hbzp7t.js → chunk-vsnq4381.js} +1 -1
- package/bin/{chunk-1nvj833s.js → chunk-w4adkd0a.js} +5 -5
- package/bin/{chunk-qxscgcn9.js → chunk-wbmqbpgm.js} +1 -1
- package/bin/{chunk-v034sfw8.js → chunk-wperd2h9.js} +2 -2
- package/bin/{chunk-y2dhf3p0.js → chunk-xbw7ffrz.js} +2 -2
- package/bin/{chunk-9bakwac0.js → chunk-xdrpahym.js} +4 -4
- package/bin/{chunk-6jkjx0n2.js → chunk-xfmnfcv2.js} +3 -3
- package/bin/chunk-xhngtwn9.js +1 -0
- package/bin/chunk-xjnehexk.js +2 -0
- package/bin/chunk-xzb0t8mx.js +1 -0
- package/bin/{chunk-k3prp6c6.js → chunk-y5h5d5gx.js} +4 -4
- package/bin/{chunk-wwkhskce.js → chunk-y6xyc4wp.js} +2 -2
- package/bin/{chunk-93p27bbm.js → chunk-zpk87b33.js} +5 -5
- package/bin/{chunk-asy868kq.js → chunk-zq5j9wsc.js} +1 -1
- package/bin/{chunk-grjek810.js → chunk-zsg61vr0.js} +2 -2
- package/bin/chunk-zts21ft7.js +1 -0
- package/bin/{chunk-cpj562n6.js → chunk-zzbn0b6c.js} +1 -1
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +350 -333
- package/package.json +7 -7
- package/prisma/migrations/20261014054332_add_embedding_768/migration.sql +8 -0
- package/prisma/schema.prisma +10 -8
- package/bin/chunk-2gf95tj0.js +0 -1
- package/bin/chunk-2tk5w3jc.js +0 -1
- package/bin/chunk-301e7g3z.js +0 -2
- package/bin/chunk-3kmjbc3m.js +0 -2
- package/bin/chunk-3td60k1m.js +0 -2
- package/bin/chunk-42hrvk6k.js +0 -211
- package/bin/chunk-5bk16qdp.js +0 -2
- package/bin/chunk-8abhmarc.js +0 -2
- package/bin/chunk-965102pf.js +0 -3
- package/bin/chunk-acn3r2m2.js +0 -1
- package/bin/chunk-ce75dw3k.css +0 -1
- package/bin/chunk-d9qpgkek.js +0 -2
- package/bin/chunk-dv6p6n5e.js +0 -1
- package/bin/chunk-qb178ntp.js +0 -2
- package/bin/chunk-s4r6e6ms.js +0 -1
- package/bin/chunk-syjjke3f.js +0 -1
- package/bin/chunk-tgfxe0sb.js +0 -1
- package/bin/chunk-tjretpx8.js +0 -1
- package/bin/chunk-w4yjgez6.js +0 -14
- package/bin/chunk-wjcebkpb.js +0 -1
- package/bin/chunk-ws71fg50.js +0 -2
- package/bin/chunk-yfp3q4da.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{dr}from"./chunk-b5r0be06.js";import"./chunk-8zgq5sav.js";import{Ui}from"./chunk-5bpvwv66.js";import{ti,ri,ni}from"./chunk-15vsw36h.js";import{as}from"./chunk-23780yj6.js";import{xn,Sn}from"./chunk-sbyyn9yw.js";import{Wn,Tr}from"./chunk-dppfek34.js";import{mn}from"./chunk-zdzkjp4q.js";import{nl}from"./chunk-rtaya5wc.js";import{Gr}from"./chunk-ae6zgjhd.js";import{Vi,Ec,ll,Jt}from"./chunk-vm2pz2hm.js";var z=new Set;function X(e){return z.add(e),()=>{z.delete(e)}}function j(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var me={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function F(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||dr(r)||dr(n)||""}function ye(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function be(e,t,r){let n=F("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function he(e,t){let r=ye(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||me[n]||0;if(!be(s,o,t))return"";let i=F(`${n}_proxy`,t)||F("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var we="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function V(e,t){let r=he(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${we} Got ${n.protocol}`);return n}function ge(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var D=ge(),Se="https://chatgpt.com/backend-api",Ee="https://api.openai.com/auth",_e=0,Y=1000,ke=60000,Te=15000,Re=3,ne=new Set(["openai","openai-codex","opencode"]),xe=1009,ve="websocket_connection_limit_reached",Ce="previous_response_not_found",Oe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ae(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Le(e,t){if(e===429&&Ae(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function We(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class K extends Error{}function Ne(e,t){let r=t?.maxRetryDelayMs??ke;if(r>0&&e>r)throw new K(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function Z(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function Q(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Pe(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Me(e){let t=Pe();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Re}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var De=(e,t,r)=>{let n=new Jt;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=ft(o),l=Wn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=as(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||nl(),f=dt(e.headers,r?.headers,i,o,c),S=pt(e.headers,r?.headers,i,o,g),m=JSON.stringify(d),p=Q(r?.timeoutMs),x=Q(r?.websocketConnectTimeoutMs),y=r?.transport||"auto",h=!1,b=y!=="sse"&&ce(a);if(b)ee(a);if(y!=="sse"&&!b){let w=!1,_=!1,C=!1;while(!0){w=!1;try{if(await ut(Be(e.baseUrl),d,S,s,n,e,()=>{if(w=!0,!h)h=!0,n.push({type:"start",partial:s})},p,x,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(T){let N=r?.signal?.aborted,P=!w&&Fe(T),A=Je(T);if(!N&&A&&!C){C=!0;continue}if(!N&&P&&!_){_=!0;continue}if(N||$e(T)&&!P)throw T;if(ll(s,Ec("provider_transport_failure",T,{configuredTransport:y,fallbackTransport:w?void 0:"sse",eventsEmitted:w,phase:w?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),Ye(a,T),w)throw T;ee(a);break}}}let v=Me(m);if(v)f.set("content-encoding","zstd");let O=v??m,E,W,U=r?.maxRetries??_e;for(let w=0;w<=U;w++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let _=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,C=j([r?.signal,_]);try{E=await fetch(ie(e.baseUrl),{method:"POST",headers:f,body:O,signal:C.signal})}catch(A){if(_?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw A}finally{C.cleanup()}if(await r?.onResponse?.({status:E.status,headers:mn(E.headers)},e),E.ok)break;let T=await E.text();if(w<U&&Le(E.status,T)){let A=We(E.headers),pe=A===void 0?Y*2**w:Ne(A,r);await Z(pe,r?.signal);continue}let N=new Response(T,{status:E.status,statusText:E.statusText}),P=await lt(N);throw Error(P.friendlyMessage||P.message)}catch(_){if(_ instanceof Error){if(_.name==="AbortError"||_.message==="Request was aborted")throw Error("Request was aborted")}if(W=_ instanceof Error?_:Error(String(_)),w<U&&!(W instanceof K)&&!W.message.includes("usage limit")){let C=Y*2**w;await Z(C,r?.signal);continue}throw W}}if(!E?.ok)throw W??Error("Failed after retries");if(!E.body)throw Error("No response body");if(!h)h=!0,n.push({type:"start",partial:s});if(await Ue(E,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=Sn(xn(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Wt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=Tr(e,t,r,n),o=r?.reasoning?Gr(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=Wn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ui(t,e.compat?.supportsToolSearch??!1),a=ti(e,t,ne,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=ri(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function qe(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function oe(e,t,r){let n=qe(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function se(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function ie(e){let r=(e&&e.trim().length>0?e:Se).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function Be(e){let t=new URL(ie(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function Ue(e,t,r,n,s,o){await ni(ae(Ge(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:se,applyServiceTierPricing:(i,l)=>oe(i,l,n)})}class L extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class B extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function $e(e){return e instanceof L||e instanceof B}function Fe(e){return e instanceof L&&e.code===ve}function Je(e){return e instanceof L&&e.code===Ce}function He(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*ae(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=He(t);throw new L(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new L(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:Ke(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function Ke(e){if(typeof e!=="string")return;return Oe.has(e)?e:void 0}async function*Ge(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
|
|
2
|
+
import{dr}from"./chunk-b5r0be06.js";import"./chunk-5ebb2pdf.js";import{Ui}from"./chunk-5bpvwv66.js";import{ri,ni,oi}from"./chunk-pwq6dbb5.js";import{as}from"./chunk-23780yj6.js";import{xn,Sn}from"./chunk-sbyyn9yw.js";import{Wn,Tr}from"./chunk-m41tbrvt.js";import{pn}from"./chunk-3fjgf7eb.js";import{il}from"./chunk-rh8dy99a.js";import{Gr}from"./chunk-ncv8v6mj.js";import{Vi,Tc,dl,Jt}from"./chunk-q7t5zs7n.js";var z=new Set;function X(e){return z.add(e),()=>{z.delete(e)}}function j(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var me={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function F(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||dr(r)||dr(n)||""}function ye(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function be(e,t,r){let n=F("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function he(e,t){let r=ye(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||me[n]||0;if(!be(s,o,t))return"";let i=F(`${n}_proxy`,t)||F("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var we="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function V(e,t){let r=he(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${we} Got ${n.protocol}`);return n}function ge(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var D=ge(),Se="https://chatgpt.com/backend-api",Ee="https://api.openai.com/auth",_e=0,Y=1000,ke=60000,Te=15000,Re=3,ne=new Set(["openai","openai-codex","opencode"]),xe=1009,ve="websocket_connection_limit_reached",Ce="previous_response_not_found",Oe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ae(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Le(e,t){if(e===429&&Ae(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function We(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class K extends Error{}function Ne(e,t){let r=t?.maxRetryDelayMs??ke;if(r>0&&e>r)throw new K(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function Z(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function Q(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Pe(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Me(e){let t=Pe();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Re}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var De=(e,t,r)=>{let n=new Jt;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=ft(o),l=Wn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=as(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||il(),f=dt(e.headers,r?.headers,i,o,c),S=pt(e.headers,r?.headers,i,o,g),m=JSON.stringify(d),p=Q(r?.timeoutMs),x=Q(r?.websocketConnectTimeoutMs),y=r?.transport||"auto",h=!1,b=y!=="sse"&&ce(a);if(b)ee(a);if(y!=="sse"&&!b){let w=!1,_=!1,C=!1;while(!0){w=!1;try{if(await ut(Be(e.baseUrl),d,S,s,n,e,()=>{if(w=!0,!h)h=!0,n.push({type:"start",partial:s})},p,x,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(T){let N=r?.signal?.aborted,P=!w&&Fe(T),A=Je(T);if(!N&&A&&!C){C=!0;continue}if(!N&&P&&!_){_=!0;continue}if(N||$e(T)&&!P)throw T;if(dl(s,Tc("provider_transport_failure",T,{configuredTransport:y,fallbackTransport:w?void 0:"sse",eventsEmitted:w,phase:w?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),Ye(a,T),w)throw T;ee(a);break}}}let v=Me(m);if(v)f.set("content-encoding","zstd");let O=v??m,E,W,U=r?.maxRetries??_e;for(let w=0;w<=U;w++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let _=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,C=j([r?.signal,_]);try{E=await fetch(ie(e.baseUrl),{method:"POST",headers:f,body:O,signal:C.signal})}catch(A){if(_?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw A}finally{C.cleanup()}if(await r?.onResponse?.({status:E.status,headers:pn(E.headers)},e),E.ok)break;let T=await E.text();if(w<U&&Le(E.status,T)){let A=We(E.headers),pe=A===void 0?Y*2**w:Ne(A,r);await Z(pe,r?.signal);continue}let N=new Response(T,{status:E.status,statusText:E.statusText}),P=await lt(N);throw Error(P.friendlyMessage||P.message)}catch(_){if(_ instanceof Error){if(_.name==="AbortError"||_.message==="Request was aborted")throw Error("Request was aborted")}if(W=_ instanceof Error?_:Error(String(_)),w<U&&!(W instanceof K)&&!W.message.includes("usage limit")){let C=Y*2**w;await Z(C,r?.signal);continue}throw W}}if(!E?.ok)throw W??Error("Failed after retries");if(!E.body)throw Error("No response body");if(!h)h=!0,n.push({type:"start",partial:s});if(await Ue(E,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=Sn(xn(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Wt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=Tr(e,t,r,n),o=r?.reasoning?Gr(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=Wn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ui(t,e.compat?.supportsToolSearch??!1),a=ri(e,t,ne,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=ni(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function qe(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function oe(e,t,r){let n=qe(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function se(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function ie(e){let r=(e&&e.trim().length>0?e:Se).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function Be(e){let t=new URL(ie(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function Ue(e,t,r,n,s,o){await oi(ae(Ge(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:se,applyServiceTierPricing:(i,l)=>oe(i,l,n)})}class L extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class B extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function $e(e){return e instanceof L||e instanceof B}function Fe(e){return e instanceof L&&e.code===ve}function Je(e){return e instanceof L&&e.code===Ce}function He(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*ae(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=He(t);throw new L(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new L(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:Ke(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function Ke(e){if(typeof e!=="string")return;return Oe.has(e)?e:void 0}async function*Ge(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
|
|
3
3
|
|
|
4
4
|
`);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let d=c.split(`
|
|
5
5
|
`).filter((u)=>u.startsWith("data:")).map((u)=>u.slice(5).trim());if(d.length>0){let u=d.join(`
|
|
6
6
|
`).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(g){throw new B(`Invalid Codex SSE JSON: ${Vi(g)}`,{cause:g,payload:u})}}a=s.indexOf(`
|
|
7
7
|
|
|
8
|
-
`)}}}finally{t?.removeEventListener("abort",o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var ze="responses_websockets=2026-02-06",Xe=300000,je=3300000,k=new Map,M=new Map,q=new Set;function G(e){let t=M.get(e);if(!t)t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},M.set(e,t);return t}function Nt(e){let t=M.get(e);return t?{...t}:void 0}function Pt(e){if(e){M.delete(e),q.delete(e);return}M.clear(),q.clear()}function Ve(e){let t=(r)=>{if(r.idleTimer)clearTimeout(r.idleTimer);R(r.socket,1000,"debug_close")};if(e){let r=k.get(e);if(r)t(r);k.delete(e);return}for(let r of k.values())t(r);k.clear()}X(Ve);function ce(e){return e?q.has(e):!1}function ee(e){if(!e)return;let t=G(e);t.sseFallbacks++,t.websocketFallbackActive=ce(e)}function Ye(e,t){if(!e)return;q.add(e);let r=G(e);r.websocketFailures++,r.lastWebSocketError=Vi(t),r.websocketFallbackActive=!0}var J=null;async function Ze(e){if(!e&&J)return J;if(typeof process<"u"&&process.versions?.bun){let r=class extends WebSocket{constructor(n,s){let o={};if(Array.isArray(s)||typeof s==="string")o={protocols:s};else o={...s};let i=V(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...o,...i?{proxy:i.toString()}:{}})}};if(!e)J=r;return r}let t=globalThis.WebSocket;if(typeof t!=="function")return null;return t}class ue extends Error{code;reason;wasClean;constructor(e,t){super(e);this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function Qe(e){let t=e.readyState;return typeof t==="number"?t:void 0}function I(e){let t=Qe(e);return t===void 0||t===1}function et(e){return Date.now()-e.createdAt>=je}function R(e,t=1000,r="done"){try{e.close(t,r)}catch{}}function te(e,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1000,"idle_timeout"),k.delete(e)},Xe)}async function H(e,t,r,n=Te,s){let o=await Ze(s);if(!o)throw Error("WebSocket transport is not available in this runtime");let i=
|
|
8
|
+
`)}}}finally{t?.removeEventListener("abort",o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var ze="responses_websockets=2026-02-06",Xe=300000,je=3300000,k=new Map,M=new Map,q=new Set;function G(e){let t=M.get(e);if(!t)t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},M.set(e,t);return t}function Nt(e){let t=M.get(e);return t?{...t}:void 0}function Pt(e){if(e){M.delete(e),q.delete(e);return}M.clear(),q.clear()}function Ve(e){let t=(r)=>{if(r.idleTimer)clearTimeout(r.idleTimer);R(r.socket,1000,"debug_close")};if(e){let r=k.get(e);if(r)t(r);k.delete(e);return}for(let r of k.values())t(r);k.clear()}X(Ve);function ce(e){return e?q.has(e):!1}function ee(e){if(!e)return;let t=G(e);t.sseFallbacks++,t.websocketFallbackActive=ce(e)}function Ye(e,t){if(!e)return;q.add(e);let r=G(e);r.websocketFailures++,r.lastWebSocketError=Vi(t),r.websocketFallbackActive=!0}var J=null;async function Ze(e){if(!e&&J)return J;if(typeof process<"u"&&process.versions?.bun){let r=class extends WebSocket{constructor(n,s){let o={};if(Array.isArray(s)||typeof s==="string")o={protocols:s};else o={...s};let i=V(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...o,...i?{proxy:i.toString()}:{}})}};if(!e)J=r;return r}let t=globalThis.WebSocket;if(typeof t!=="function")return null;return t}class ue extends Error{code;reason;wasClean;constructor(e,t){super(e);this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function Qe(e){let t=e.readyState;return typeof t==="number"?t:void 0}function I(e){let t=Qe(e);return t===void 0||t===1}function et(e){return Date.now()-e.createdAt>=je}function R(e,t=1000,r="done"){try{e.close(t,r)}catch{}}function te(e,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1000,"idle_timeout"),k.delete(e)},Xe)}async function H(e,t,r,n=Te,s){let o=await Ze(s);if(!o)throw Error("WebSocket transport is not available in this runtime");let i=pn(t);return delete i["OpenAI-Beta"],new Promise((l,a)=>{let c=!1,d,u;try{u=new o(e,{headers:i})}catch(y){a(y instanceof Error?y:Error(String(y)));return}let g=()=>{if(d)clearTimeout(d),d=void 0;u.removeEventListener("open",S),u.removeEventListener("error",m),u.removeEventListener("close",p),r?.removeEventListener("abort",x)},f=(y,h)=>{if(c)return;if(c=!0,g(),h)R(u,1000,h);a(y)},S=()=>{if(c)return;c=!0,g(),l(u)},m=(y)=>{f(le(y))},p=(y)=>{f(fe(y))},x=()=>{f(Error("Request was aborted"),"aborted")};if(u.addEventListener("open",S),u.addEventListener("error",m),u.addEventListener("close",p),r?.addEventListener("abort",x),n>0)d=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(r?.aborted)x()})}async function tt(e,t,r,n,s,o){if(!r){let c=await H(e,t,n,s,o);return{socket:c,reused:!1,release:()=>R(c)}}let i=k.get(r);if(i){if(i.idleTimer)clearTimeout(i.idleTimer),i.idleTimer=void 0;if(!i.busy&&et(i))R(i.socket,1000,"connection_age_limit"),k.delete(r);else if(!i.busy&&I(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:c}={})=>{if(!c||!I(i.socket)){R(i.socket),k.delete(r);return}i.busy=!1,te(r,i)}};if(i.busy){let c=await H(e,t,n,s,o);return{socket:c,reused:!1,release:()=>{R(c)}}}if(!I(i.socket))R(i.socket),k.delete(r)}let l=await H(e,t,n,s,o),a={socket:l,busy:!0,createdAt:Date.now()};return k.set(r,a),{socket:l,entry:a,reused:!1,release:({keep:c}={})=>{if(!c||!I(a.socket)){if(R(a.socket),a.idleTimer)clearTimeout(a.idleTimer);if(k.get(r)===a)k.delete(r);return}a.busy=!1,te(r,a)}}}function le(e){if(e&&typeof e==="object"){let t="message"in e?e.message:void 0;if(typeof t==="string"&&t.length>0)return Error(t);let r="error"in e?e.error:void 0;if(r instanceof Error&&r.message.length>0)return r;if(r&&typeof r==="object"&&"message"in r){let n=r.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function fe(e){if(e&&typeof e==="object"){let t="code"in e?e.code:void 0,r="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,s=typeof t==="number"?` ${t}`:"",o=typeof r==="string"&&r.length>0?` ${r}`:"";if(!o&&t===xe)o=" message too big";return new ue(`WebSocket closed${s}${o}`.trim(),{code:typeof t==="number"?t:void 0,reason:typeof r==="string"&&r.length>0?r:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function rt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==="object"&&"arrayBuffer"in e){let r=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(r))}return null}async function*nt(e,t,r){let n=[],s=null,o=!1,i=null,l=!1,a=()=>{if(!s)return;let f=s;s=null,f()},c=(f)=>{(async()=>{let S=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(S=await rt(f.data),!S)return;let m=JSON.parse(S),p=typeof m.type==="string"?m.type:"";if(p==="response.completed"||p==="response.done"||p==="response.incomplete")l=!0,o=!0;n.push(m),a()}catch(m){i=new B(`Invalid Codex WebSocket JSON: ${Vi(m)}`,{cause:m,payload:S}),o=!0,a()}})()},d=(f)=>{i=le(f),o=!0,a()},u=(f)=>{if(l){o=!0,a();return}if(!i)i=fe(f);o=!0,a()},g=()=>{i=Error("Request was aborted"),o=!0,a()};e.addEventListener("message",c),e.addEventListener("error",d),e.addEventListener("close",u),t?.addEventListener("abort",g);try{while(!0){if(t?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(o)break;let f;await new Promise((S,m)=>{if(s=S,r!==void 0&&r>0)f=setTimeout(()=>{let p=Error(`WebSocket idle timeout after ${r}ms`);i=p,o=!0,s=null,R(e,1000,"idle_timeout"),m(p)},r)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!l)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",c),e.removeEventListener("error",d),e.removeEventListener("close",u),t?.removeEventListener("abort",g)}}function re(e){let{input:t,previous_response_id:r,...n}=e;return n}function ot(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function st(e,t){return JSON.stringify(re(e))===JSON.stringify(re(t))}function it(e,t){if(!st(e,t.lastRequestBody))return;let r=e.input??[],n=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(r.length<n.length)return;let s=r.slice(0,n.length);if(!ot(s,n))return;return r.slice(n.length)}function at(e,t){let r=e.continuation;if(!r)return t;let n=it(t,r);if(!n||!r.lastResponseId)return e.continuation=void 0,t;return{...t,previous_response_id:r.lastResponseId,input:n}}async function*ct(e,t){let r=!1;for await(let n of e){if(!r)r=!0,t();yield n}}async function ut(e,t,r,n,s,o,i,l,a,c,d,u){let{socket:g,entry:f,reused:S,release:m}=await tt(e,r,c,u?.signal,a,u?.env),p=!0,x=u?.transport==="websocket-cached"||u?.transport==="auto",y=t,h=x&&f?at(f,y):y,b=c?G(c):void 0;if(b){if(b.requests++,S)b.connectionsReused++;else b.connectionsCreated++;if(x)b.cachedContextRequests++;if(h.store===!0)b.storeTrueRequests++;if(b.lastInputItems=h.input?.length??0,h.previous_response_id)b.deltaRequests++,b.lastDeltaInputItems=h.input?.length??0,b.lastPreviousResponseId=h.previous_response_id;else b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0}try{if(g.send(JSON.stringify({type:"response.create",...h})),await oi(ct(ae(nt(g,u?.signal,l)),i),n,s,o,{serviceTier:u?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:se,applyServiceTierPricing:(v,O)=>oe(v,O,o)}),u?.signal?.aborted)p=!1;else if(x&&f&&n.responseId){let v=ri(o,{messages:[n]},ne,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter((O)=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");f.continuation={lastRequestBody:y,lastResponseId:n.responseId,lastResponseItems:v}}}catch(v){if(f)f.continuation=void 0;throw p=!1,v}finally{m({keep:p})}}async function lt(e){let t=await e.text(),r=t||e.statusText||"Request failed",n;try{let o=JSON.parse(t)?.error;if(o){let i=o.code||o.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let l=o.plan_type?` (${o.plan_type.toLowerCase()} plan)`:"",a=o.resets_at?Math.max(0,Math.round((o.resets_at*1000-Date.now())/60000)):void 0,c=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${l}.${c}`.trim()}r=o.message||n||r}}catch{}return{message:r,friendlyMessage:n}}function ft(e){try{let t=e.split(".");if(t.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(t[1]))?.[Ee]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function de(e,t,r,n){let s=new Headers(e);for(let[i,l]of Object.entries(t||{}))if(l===null)s.delete(i);else s.set(i,l);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",r),s.set("originator","pi");let o=D?`pi (${D.platform()} ${D.release()}; ${D.arch()})`:"pi (browser)";return s.set("User-Agent",o),s}function dt(e,t,r,n,s){let o=de(e,t,r,n);if(o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s)o.set("session-id",s),o.set("x-client-request-id",s);return o}function pt(e,t,r,n,s){let o=de(e,t,r,n);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",ze),o.set("x-client-request-id",s),o.set("session-id",s),o}export{Ve as closeOpenAICodexWebSocketSessions,Nt as getOpenAICodexWebSocketDebugStats,Pt as resetOpenAICodexWebSocketDebugStats,De as stream,Wt as streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xu}from"./chunk-cdk8vqeg.js";import{dr}from"./chunk-b5r0be06.js";import"./chunk-
|
|
2
|
+
import{xu}from"./chunk-cdk8vqeg.js";import{dr}from"./chunk-b5r0be06.js";import"./chunk-5ebb2pdf.js";import{ri,ni,oi}from"./chunk-pwq6dbb5.js";import{as}from"./chunk-23780yj6.js";import{xn,Sn}from"./chunk-sbyyn9yw.js";import{ls}from"./chunk-6hzktewz.js";import{Wn,Tr}from"./chunk-m41tbrvt.js";import{pn}from"./chunk-3fjgf7eb.js";import{Gr}from"./chunk-ncv8v6mj.js";import{Jt}from"./chunk-q7t5zs7n.js";var d="v1",A=new Set(["openai","openai-codex","opencode","azure-openai-responses"]),E=16;function R(r){let a=new Map;if(!r)return a;for(let e of r.split(",")){let n=e.trim();if(!n)continue;let[s,t]=n.split("=",2);if(!s||!t)continue;a.set(s.trim(),t.trim())}return a}function h(r,a){if(a?.azureDeploymentName)return a.azureDeploymentName;return R(dr("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",a?.env)).get(r.id)||r.id}function g(r){return Sn(xn(r),"Azure OpenAI API error")}var y=(r,a,e)=>{let n=new Jt;return(async()=>{let s=h(r,e),t={role:"assistant",content:[],api:"azure-openai-responses",provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=e?.apiKey;if(!o)throw Error(`No API key for provider: ${r.provider}`);let i=O(r,o,e),m=Wn(a.tools,r.compat?.supportsOpenAIGrammarTools??!1),p=U(r,a,e,s,m),u=await e?.onPayload?.(p,r);if(u!==void 0)p=u;let f={...e?.signal?{signal:e.signal}:{},...e?.timeoutMs!==void 0?{timeout:e.timeoutMs}:{},maxRetries:0},{data:l,response:c}=await ls(()=>i.responses.create(p,f).withResponse(),{maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,signal:e?.signal});if(await e?.onResponse?.({status:c.status,headers:pn(c.headers)},r),n.push({type:"start",partial:t}),await oi(l,t,n,r,{grammarToolInputProperties:m}),e?.signal?.aborted)throw Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw Error("An unknown error occurred");n.push({type:"done",reason:t.stopReason,message:t}),n.end()}catch(o){for(let i of t.content)delete i.index,delete i.partialJson,delete i.customInput;t.stopReason=e?.signal?.aborted?"aborted":"error",t.errorMessage=g(o),n.push({type:"error",reason:t.stopReason,error:t}),n.end()}})(),n},B=(r,a,e)=>{let n=e?.apiKey;if(!n)throw Error(`No API key for provider: ${r.provider}`);let s=Tr(r,a,e,n),t=e?.reasoning?Gr(r,e.reasoning):void 0;return y(r,a,{...s,reasoningEffort:t==="off"?void 0:t})};function _(r){let a=r.trim().replace(/\/+$/,""),e;try{e=new URL(a)}catch{throw Error(`Invalid Azure OpenAI base URL: ${r}`)}let n=e.hostname.endsWith(".openai.azure.com")||e.hostname.endsWith(".cognitiveservices.azure.com")||e.hostname.endsWith(".ai.azure.com"),s=e.pathname.replace(/\/+$/,"");if(n&&(s===""||s==="/"||s==="/openai"||s==="/openai/v1/responses"))e.pathname="/openai/v1",e.search="";return e.toString().replace(/\/+$/,"")}function I(r){return`https://${r}.openai.azure.com/openai/v1`}function v(r,a){let e=a?.azureApiVersion||dr("AZURE_OPENAI_API_VERSION",a?.env)||d,n=a?.azureBaseUrl?.trim()||dr("AZURE_OPENAI_BASE_URL",a?.env)?.trim()||void 0,s=a?.azureResourceName||dr("AZURE_OPENAI_RESOURCE_NAME",a?.env),t=n;if(!t&&s)t=I(s);if(!t&&r.baseUrl)t=r.baseUrl;if(!t)throw Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:_(t),apiVersion:e}}function O(r,a,e){let n={...r.headers};if(e?.headers)Object.assign(n,e.headers);let{baseUrl:s,apiVersion:t}=v(r,e);return new xu({apiKey:a,apiVersion:t,dangerouslyAllowBrowser:!0,defaultHeaders:n,baseURL:s})}function U(r,a,e,n,s=Wn(a.tools,r.compat?.supportsOpenAIGrammarTools??!1)){let t=ri(r,a,A,{grammarToolInputProperties:s}),o={model:n,input:t,stream:!0,prompt_cache_key:as(e?.sessionId),store:!1};if(e?.maxTokens)o.max_output_tokens=Math.max(e.maxTokens,E);if(e?.temperature!==void 0)o.temperature=e?.temperature;if(a.tools&&a.tools.length>0)o.tools=ni(a.tools,{supportsStrictMode:r.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:r.compat?.supportsOpenAIGrammarTools??!1});if(r.reasoning){if(e?.reasoningEffort||e?.reasoningSummary){let i=e?.reasoningEffort?r.thinkingLevelMap?.[e.reasoningEffort]??e.reasoningEffort:"medium";o.reasoning={effort:i,summary:e?.reasoningSummary||"auto"},o.include=["reasoning.encrypted_content"]}else if(r.thinkingLevelMap?.off!==null)o.reasoning={effort:r.thinkingLevelMap?.off??"none"}}return o}export{y as stream,B as streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Dt}from"./chunk-
|
|
2
|
+
import{Dt}from"./chunk-3ahax79y.js";import{Ge}from"./chunk-y5h5d5gx.js";import{H}from"./chunk-a8bymrv1.js";var f=H(Ge());var N=H(Ge());var m=H(Dt()),l=H(Ge());var E=H(Dt()),d=H(Ge()),P=(e,t,r)=>{let o={EcsContainer:async(s)=>{let{fromHttp:i}=await import("./chunk-26am2rzm.js"),{fromContainerMetadata:n}=await import("./chunk-24da4wg9.js");return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>d.chain(i(s??{}),n(s))().then(_)},Ec2InstanceMetadata:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:i}=await import("./chunk-24da4wg9.js");return async()=>i(s)().then(_)},Environment:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:i}=await import("./chunk-sjbvt3wa.js");return async()=>i(s)().then(_)}};if(e in o)return o[e];else throw new d.CredentialsProviderError(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},_=(e)=>E.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var v=(e,{profile:t="default",logger:r}={})=>Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(K(e,{profile:t,logger:r})||G(e,{profile:t,logger:r})),K=(e,{profile:t,logger:r})=>{let o=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(o)r?.debug?.(` ${t} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return o},G=(e,{profile:t,logger:r})=>{let o=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(o)r?.debug?.(` ${t} isCredentialSourceProfile credential_source=${e.credential_source}`);return o},I=async(e,t,r,o,s={},i)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let n=t[e],{source_profile:a,region:j}=n;if(!r.roleAssumer){let{getDefaultRoleAssumer:c}=await import("./chunk-59ayg5am.js");r.roleAssumer=c({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...o,...r?.parentClientConfig,region:j??r?.parentClientConfig?.region??o?.region}},r.clientPlugins)}if(a&&a in s)throw new l.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${l.getProfileName(r)}. Profiles visited: `+Object.keys(s).join(", "),{logger:r.logger});r.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${a?`source_profile=[${a}]`:`profile=[${e}]`}`);let w=a?i(a,t,r,o,{...s,[a]:!0},S(t[a]??{})):(await P(n.credential_source,e,r.logger)(r))();if(S(n))return w.then((c)=>m.setCredentialFeature(c,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let c={RoleArn:n.role_arn,RoleSessionName:n.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:n.external_id,DurationSeconds:parseInt(n.duration_seconds||"3600",10)},{mfa_serial:u}=n;if(u){if(!r.mfaCodeProvider)throw new l.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});c.SerialNumber=u,c.TokenCode=await r.mfaCodeProvider(u)}let M=await w;return r.roleAssumer(M,c).then((B)=>m.setCredentialFeature(B,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},S=(e)=>!e.role_arn&&!!e.credential_source;var R=H(Dt()),A=(e)=>Boolean(e&&e.login_session),L=async(e,t,r)=>{let{fromLoginCredentials:o}=await import("./chunk-nmd1901j.js"),s=await o({...t,profile:e})({callerClientConfig:r});return R.setCredentialFeature(s,"CREDENTIALS_PROFILE_LOGIN","AC")};var O=H(Dt()),b=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",x=async(e,t)=>{let{fromProcess:r}=await import("./chunk-srv5kvm4.js"),o=await r({...e,profile:t})();return O.setCredentialFeature(o,"CREDENTIALS_PROFILE_PROCESS","v")};var p=H(Dt()),k=async(e,t,r={},o)=>{let{fromSSO:s}=await import("./chunk-hsx4pns6.js");return s({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then((i)=>{if(t.sso_session)return p.setCredentialFeature(i,"CREDENTIALS_PROFILE_SSO","r");else return p.setCredentialFeature(i,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},F=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var h=H(Dt()),C=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,y=async(e,t)=>{t?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let r={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return h.setCredentialFeature(r,"CREDENTIALS_PROFILE","n")};var D=H(Dt()),T=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,W=async(e,t,r)=>{let{fromTokenFile:o}=await import("./chunk-scvepfv8.js"),s=await o({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:t.roleAssumerWithWebIdentity,logger:t.logger,parentClientConfig:t.parentClientConfig})({callerClientConfig:r});return D.setCredentialFeature(s,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")};var g=async(e,t,r,o,s={},i=!1)=>{let n=t[e];if(Object.keys(s).length>0&&C(n))return y(n,r);if(i||v(n,{profile:e,logger:r.logger}))return I(e,t,r,o,s,g);if(C(n))return y(n,r);if(T(n))return W(n,r,o);if(b(n))return x(r,e);if(F(n))return await k(e,n,r,o);if(A(n))return L(e,r,o);throw new N.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:r.logger})};var U=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let r=await f.parseKnownFiles(e);return g(f.getProfileName({profile:e.profile??t?.profile}),r,e,t)};export{U as fromIni};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m,D,u,S,L,t,o,V,B,mt,Re,ze,A,O,jn,
|
|
1
|
+
import{m,D,u,S,L,t,o,V,B,mt,Re,ze,A,O,jn,qs,Pa,E,Ce,Ie,Te,GA,e_,Q_,Lf,qc,$s,Uw,Il,TS,WE,zI,An,ut,Nt,M,vr,Me,$t,Ct,im}from"./chunk-qx553512.js";import{Ir}from"./chunk-6pwf7qa6.js";import{ql}from"./chunk-wperd2h9.js";import{tr}from"./chunk-md7pgk86.js";import{Pn,Nn,Dn,xr,It,xt}from"./chunk-k3ds96cb.js";import{fo}from"./chunk-fxg81vtx.js";import{Nr}from"./chunk-68xsb3t8.js";S();var _=(a)=>{if(!a)return"??";return a.split(" ").map((i)=>i[0]).slice(0,2).join("").toUpperCase()};function F(){let{projectId:a}=P.useParams(),{teamId:i,ensureTeamIdForProject:d}=ut(),N=V(),y=Re();m(()=>{d(a)},[a,d]);let{data:n}=tr(im(a)),c=n?.rootFolder,[w,k]=u(240),{shareConfigLeftSidebarCollapsed:p,setShareConfigLeftSidebarCollapsed:C}=$t(),{data:f,isLoading:I,fetchNextPage:b,hasNextPage:g,isFetchingNextPage:l}=mt({queryKey:["shares",a],queryFn:async({pageParam:e})=>{let r=await A.api.projects[":projectId"].shares.$get({param:{projectId:a},query:{first:"20",after:e}});if(!r.ok)throw Error("Failed to fetch share links");return await r.json()},initialPageParam:"",getNextPageParam:(e)=>e.pageInfo?.cursor||void 0,enabled:!!a}),{ref:T,inView:x}=Nt();m(()=>{if(x&&g&&!l)b()},[x,g,l,b]);let h=D(()=>f?.pages.flatMap((e)=>e.data)||[],[f]),{mutate:j}=B({mutationFn:async({id:e,isDisabled:r})=>{let s=await A.api.shares[":shareId"].$put({param:{shareId:e},json:{isDisabled:r}});if(!s.ok)throw Error("Failed to update share link");return await s.json()},onSuccess:()=>{N.invalidateQueries({queryKey:["shares",a]}),M.success(zI())},onError:(e)=>{M.error($s({message:e.message}))}});if(!i||!c||!n)return t(Ct,{});let v=async(e)=>{let r=`${window.location.origin}/share/${e}`;if(await fo(r))M.success(Uw())};return t("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:o("div",{className:"flex flex-1 overflow-hidden relative",children:[!p&&t("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:()=>C(!0)}),!p&&o(L,{children:[t("div",{className:"bg-background",style:{width:w},children:t(vr,{teamId:i,projectId:a,projectName:n.name??"",rootFolderId:c})}),t(Ir,{onResize:(e)=>{k((r)=>Math.max(180,Math.min(400,r+e)))},className:"hidden md:block"})]}),o("div",{className:"flex-1 flex flex-col min-h-0 bg-card overflow-hidden",children:[t("header",{className:"h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10",children:o("div",{className:"flex items-center gap-2",children:[t(Pa,{className:"h-5 w-5 text-primary"}),t("h1",{className:"font-bold text-lg text-foreground",children:e_()})]})}),t("div",{className:"flex-1 overflow-y-auto p-6",children:I?t("div",{className:"flex justify-center items-center h-64",children:t("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):h.length===0?o("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground gap-3",children:[t(qs,{className:"h-10 w-10 text-muted-foreground/50"}),t("p",{children:TS()})]}):o("div",{className:"border border-border rounded-xl bg-background overflow-hidden shadow-xs",children:[o(Pn,{children:[t(Nn,{children:o(xr,{className:"hover:bg-transparent bg-muted/20",children:[t(It,{className:"font-semibold px-4 py-3",children:Il()}),t(It,{className:"font-semibold px-4 py-3",children:WE()}),t(It,{className:"font-semibold px-4 py-3",children:qc()}),t(It,{className:"font-semibold px-4 py-3 w-[150px]",children:Lf()}),t(It,{className:"font-semibold px-4 py-3 text-right w-[120px]",children:GA()})]})}),t(Dn,{children:h.map((e)=>{let r=`${window.location.origin}/share/${e.id}`;return o(xr,{className:"hover:bg-muted/10 transition-colors",children:[t(xt,{className:"font-medium px-4 py-3.5",children:t("span",{className:"cursor-pointer hover:underline text-foreground",onClick:()=>y({to:"/projects/$projectId/shares/$shareId",params:{projectId:a,shareId:e.id}}),children:e.name})}),t(xt,{className:"px-4 py-3.5 max-w-[300px]",children:o("div",{className:"flex items-center gap-2 group",children:[t("span",{className:"truncate text-xs font-mono bg-muted/50 text-muted-foreground px-2 py-1 rounded-md border border-border cursor-pointer hover:bg-muted transition-colors flex-1",onClick:()=>v(e.id),title:Q_(),children:r}),t(E,{variant:"ghost",size:"icon-sm",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(e.id),children:t(Nr,{className:"h-3.5 w-3.5"})}),t("a",{href:r,target:"_blank",rel:"noreferrer",className:"text-muted-foreground hover:text-foreground inline-flex items-center",children:t(ql,{className:"h-3.5 w-3.5"})})]})}),t(xt,{className:"px-4 py-3.5",children:o("div",{className:"flex items-center gap-2",children:[o(Ce,{className:"h-6 w-6",children:[e.creator?.image&&t(Ie,{src:e.creator.image,alt:e.creator.name,className:"object-cover"}),t(Te,{className:"text-[10px]",children:_(e.creator?.name)})]}),t("span",{className:"text-sm font-medium text-foreground truncate max-w-[150px]",children:e.creator?.name||An()})]})}),t(xt,{className:"px-4 py-3.5 text-muted-foreground text-sm",children:o("div",{className:"flex items-center gap-2",children:[t(jn,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),t("span",{children:new Date(e.createdAt).toLocaleDateString()})]})}),t(xt,{className:"px-4 py-3.5 text-right",children:t("div",{className:"flex justify-end",children:t(Me,{checked:!e.isDisabled,onCheckedChange:(s)=>j({id:e.id,isDisabled:!s})})})})]},e.id)})})]}),t("div",{ref:T,className:"h-10 w-full flex items-center justify-center",children:l&&t(O,{className:"h-6 w-6 animate-spin text-primary"})})]})})]})]})})}var P=ze("/projects/$projectId/shares/")({component:F});export{P as Route};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m,S,t,Z,B,ze,A,Vh,ut,um,UA}from"./chunk-qx553512.js";import"./chunk-fa9yq17g.js";import"./chunk-me3zmpj5.js";import"./chunk-1tesbv8w.js";import"./chunk-cqnected.js";import"./chunk-np39aknv.js";import"./chunk-2w2bknn2.js";import"./chunk-s9sf37dv.js";import"./chunk-909h3qzp.js";import"./chunk-461gcgrs.js";import"./chunk-d1rjpbgv.js";import"./chunk-2pt9h882.js";import"./chunk-xfmnfcv2.js";import"./chunk-6pwf7qa6.js";import{Qn}from"./chunk-n08h1jgx.js";import{tr}from"./chunk-md7pgk86.js";import"./chunk-y6xyc4wp.js";import"./chunk-tqdde9bj.js";import"./chunk-03zkxckm.js";import"./chunk-4nkwe7dz.js";import"./chunk-qqapw198.js";import"./chunk-wbmqbpgm.js";import"./chunk-zsg61vr0.js";import"./chunk-68xsb3t8.js";S();function h(){let{projectId:o,collectionId:r}=y.useParams(),{teamId:s,ensureTeamIdForProject:i}=ut();m(()=>{i(o)},[o,i]);let{data:l}=tr(um(o)),{data:a,refetch:d}=Z({...UA(r)}),{mutate:p}=B({mutationFn:async(n)=>{let c=await A.api.collections[":collectionId"].$patch({param:{collectionId:r},json:n});if(!c.ok)throw Error("Failed to update collection");return await c.json()},onSuccess:()=>{d()}}),e=l?.rootFolder,{data:f}=Z({queryKey:["folders",e],queryFn:async()=>{let n=await A.api.folders[":folderId"].$get({param:{folderId:e}});if(!n.ok)throw Error("Failed to fetch folder");return await n.json()},enabled:!!e});if(!s||!e||!f||!a)return t("div",{children:Vh()});let u=a.filter.sourceFolderId||e;return t(Qn,{teamId:s,projectId:o,projectName:l.name??"",assetId:u,rootFolderId:e,collection:a,onUpdateCollection:p})}var y=ze("/projects/$projectId/collections/$collectionId")({component:h});export{y as Route};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ke}from"./chunk-a8bymrv1.js";var ye=new TextEncoder,q=new TextDecoder,re=new TextDecoder("utf-8",{fatal:!0});function A(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function tt(e,t,r){if(t<0||t>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function rt(e){let t=Math.floor(e/4294967296),r=e%4294967296,n=new Uint8Array(8);return tt(n,t,0),tt(n,r,4),n}function Te(e){let t=new Uint8Array(4);return tt(t,e),t}function b(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Pe=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function nt(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ie(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!=="number"||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function k(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw Pe(t.name);if(t.hash&&n.hash?.name!==t.hash)throw Pe(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw Pe(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw Pe(t.length,"algorithm.length");nt(e,r)}function Ot(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else if(r.length===2)e+=`one of type ${r[0]} or ${r[1]}.`;else e+=`of type ${r[0]}.`;if(t==null)e+=` Received ${t}`;else if(typeof t==="function"&&t.name)e+=` Received function ${t.name}`;else if(typeof t==="object"&&t!=null){if(t.constructor?.name)e+=` Received an instance of ${t.constructor.name}`}return e}var B=(e,...t)=>Ot("Key must be ",e,...t),he=(e,t,...r)=>Ot(`Key for the ${e} algorithm must be `,t,...r);class x 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)}}class _ extends x{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}});this.claim=r,this.reason=n,this.payload=t}}class el extends x{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}});this.claim=r,this.reason=n,this.payload=t}}class ne extends x{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class m extends x{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Oe extends x{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class f extends x{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class w extends x{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class E extends x{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class _e extends x{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class De extends x{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class we extends x{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)}}class ot extends x{[Symbol.asyncIterator]=async function*(){};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)}}class it extends x{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class at extends x{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Ue(e){if(!M(e))throw Error("CryptoKey instance expected")}var M=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},st=(e)=>e?.[Symbol.toStringTag]==="KeyObject",Re=(e)=>M(e)||st(e);var L=(e)=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function _t(e,t){let r=e.byteLength<<3;if(r!==t)throw new f(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var Wr=(e)=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function Dt(e,t){if(t.length<<3!==e.ivBits)throw new f("Invalid Initialization Vector length")}async function Ut(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(B(t,"Uint8Array"));let n=e.cekBits>>1,o=await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),a=await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return[o,a,n]}async function Rt(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function Cr(e,t,r,n,o){let[a,i,s]=await Ut(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),p=A(o,n,c,rt(o.length*8)),d=await Rt(i,p,s);return{ciphertext:c,tag:d,iv:n}}async function vr(e,t){let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign","verify"]),o=await crypto.subtle.sign(r,n,e);return crypto.subtle.verify(r,n,o,t)}async function Tr(e,t,r,n,o,a){let[i,s,c]=await Ut(e,t,"decrypt"),p=A(a,n,r,rt(a.length*8)),d=await Rt(s,p,c);try{if(await vr(o,d))return new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},i,r))}catch{}throw new Oe}async function Pr(e,t,r,n,o){let a=r instanceof Uint8Array?await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(k(r,e.subtle,"encrypt"),r),i=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s,iv:n}}async function Ir(e,t,r,n,o,a){let i=t instanceof Uint8Array?await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(k(t,e.subtle,"decrypt"),t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,A(r,o)))}catch{throw new Oe}}async function Ne(e,t,r,n,o){if(!M(r)&&!(r instanceof Uint8Array))throw TypeError(B(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n)Dt(e,n);else n=Wr(e);if(r instanceof Uint8Array)_t(r,e.cekBits);return e.cbc?Cr(e,t,r,n,o):Pr(e,t,r,n,o)}async function He(e,t,r,n,o,a){if(!M(t)&&!(t instanceof Uint8Array))throw TypeError(B(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new f("JWE Initialization Vector missing");if(!o)throw new f("JWE Authentication Tag missing");if(!e.cbc&&o.length!==16)throw new f("Invalid Authentication Tag length");if(Dt(e,n),t instanceof Uint8Array)_t(t,e.cekBits);return e.cbc?Tr(e,t,r,n,o,a):Ir(e,t,r,n,o,a)}var pf={};ke(pf,{decode:()=>D,encode:()=>fr});function ct(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function Be(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var pt="The input to be decoded is not correctly encoded.";function D(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==="string"?e:q.decode(e),{alphabet:"base64url"})}catch(r){throw TypeError(pt,{cause:r})}let t=e;if(t instanceof Uint8Array)t=q.decode(t);if(t.includes("+")||t.includes("/"))throw TypeError(pt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Be(t)}catch{throw TypeError(pt)}}function fr(e){let t=e;if(typeof t==="string")t=ye.encode(t);if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:"base64url",omitPadding:!0});return ct(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Z(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function S(e){if(typeof e!=="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Me(e){return S(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(S)}function Nt(...e){let t=new Set;for(let r of e){if(!r)continue;for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}}return!0}var Ht=Symbol();function Q(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function W(e,t,r){try{return D(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function dt(e,t,r){try{return b(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}async function $e(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}function F(e,t,r){let n;try{n=JSON.parse(re.decode(D(e)))}catch{throw new t(r)}if(!S(n))throw new t(r);return n}async function j(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t};if(o.kty!=="AKP")delete o.alg;return delete o.use,crypto.subtle.importKey("jwk",o,r,t.ext??!n,t.key_ops??e.usages[n?1:0])}function oe(e){return{__proto__:null,...e}}function Le(e){let t=oe(e);if(t.ext!==void 0&&typeof t.ext!=="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some((o)=>typeof o!=="string")||new Set(n).size!==n.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}var ft=(e)=>e[Symbol.toStringTag],Or=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};function _r(e,t,r){let{alg:n,secret:o}=e,a=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return[Bt,t];if(S(t)){let i=Le(t);if(typeof i.kty!=="string")throw TypeError(o?he(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):he(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(o?i.kty==="oct"&&typeof i.k==="string":i.kty!=="oct"&&(a?i.kty==="AKP"&&typeof i.priv==="string"||typeof i.d==="string":i.d===void 0&&i.priv===void 0)))throw TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${a?"private":"public"} JWK`);return Or(e,i,r),[Lt,t,i]}if(!Re(t))throw TypeError(o?he(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):he(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(o){if(t.type!=="secret")throw TypeError(`${ft(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw TypeError(`${ft(t)} instances for asymmetric algorithms must not be of type "secret"`);let i=a?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==i){let s=r==="sign"?"signing":r==="verify"?"verifying":`${r.slice(0,-1)}tion`;throw TypeError(`${ft(t)} instances for asymmetric algorithm ${s} must be of type "${i}"`)}}return M(t)?[Mt,t]:[$t,t]}var Bt=0,Mt=1,$t=2,Lt=3,ut,Dr={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function je(e,t,r){ut||=new WeakMap;let n=ut.get(e);if(r)if(n)n[t]=r;else ut.set(e,{[t]:r});return r??n?.[t]}var kt=async(e,t,r)=>je(e,r.alg)??je(e,r.alg,await j(r,{...t,alg:r.alg})),Ur=(e,t)=>{let r=je(e,t.alg);if(r)return r;let n=e.type==="public",o=t.usages[n?0:1],{asymmetricKeyType:a}=e,i=Dr[e.asymmetricKeyDetails?.namedCurve],s=t.resolve?.({crv:i,asymmetricKeyType:a})??t.subtle;return je(e,t.alg,e.toCryptoKey(s,n,o))};async function U(e,t,r){let n=_r(e,t,r);switch(n[0]){case Bt:case Mt:return n[1];case Lt:{let o=n[1],a=n[2];if(a.kty==="oct")return D(a.k);if(!Object.isFrozen(o)){let{key_ops:i}=o;if(Array.isArray(i))Object.freeze(i);Object.freeze(o)}return kt(o,a,e)}case $t:{let o=n[1];if(o.type==="secret")return o.export();if("toCryptoKey"in o&&typeof o.toCryptoKey==="function")return Ur(o,e);return kt(o,o.export({format:"jwk"}),e)}}}function ge(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Rr=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Nr=[[],["deriveBits"]],Ge=[[],[]];function ze(e){return{kty:["RSA"],subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Rr,ops:["wrapKey","unwrapKey"]}}function Ve(){return{kty:["EC","OKP"],subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if(t==="X25519"||r==="x25519")return{name:"X25519"};if(e==="OKP")throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Nr,ops:[void 0,"deriveBits"]}}function ie(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:Ge,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function lt(){return{kty:["oct"],secret:!0,subtle:{name:"PBKDF2"},usages:Ge,ops:["deriveBits","deriveBits"]}}var mt=ge({dir:{kty:["oct"],secret:!0,subtle:{name:"AES-GCM"},usages:Ge,ops:["encrypt","decrypt"]},"RSA-OAEP":ze(1),"RSA-OAEP-256":ze(256),"RSA-OAEP-384":ze(384),"RSA-OAEP-512":ze(512),"ECDH-ES":Ve(),"ECDH-ES+A128KW":Ve(),"ECDH-ES+A192KW":Ve(),"ECDH-ES+A256KW":Ve(),A128KW:ie(128),A192KW:ie(192),A256KW:ie(256),A128GCMKW:ie(128,!0),A192GCMKW:ie(192,!0),A256GCMKW:ie(256,!0),"PBES2-HS256+A128KW":lt(),"PBES2-HS384+A192KW":lt(),"PBES2-HS512+A256KW":lt()}),Hr=["encrypt","decrypt"];function ae(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:Ge,ops:Hr,cekBits:e,ivBits:t?128:96,cbc:t}}var kr=ge({A128GCM:ae(128),A192GCM:ae(192),A256GCM:ae(256),"A128CBC-HS256":ae(256,!0),"A192CBC-HS384":ae(384,!0),"A256CBC-HS512":ae(512,!0)});function jt(e,t){throw new m(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function R(e){return(typeof e==="string"?mt[e]:void 0)??jt("alg","Algorithm")}function ee(e){return(typeof e==="string"?kr[e]:void 0)??jt("enc","Encryption Algorithm")}function zt(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");nt(e,t)}async function Gt(e,t,r){let n=R(t).subtle,o=e instanceof Uint8Array?await crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):e;return k(o,n,r),o}async function yt(e,t,r){let n=await Gt(t,e,"wrapKey"),o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function ht(e,t,r){let n=await Gt(t,e,"unwrapKey"),o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}function Ft(e,t,r){k(t,R(e).subtle,r),Ie(e,t)}function Br(e,t){if(e instanceof Uint8Array)return crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);return k(e,R(t).subtle,"deriveBits"),e}async function Xt(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new f("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new f("PBES2 Count Input must be a positive integer");let o=A(b(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await Br(n,t);return new Uint8Array(await crypto.subtle.deriveBits(i,s,a))}function wt(e){return A(Te(e.length),e)}async function Mr(e,t,r){let n=t>>3,o=32,a=Math.ceil(n/32),i=new Uint8Array(a*32);for(let s=1;s<=a;s++){let c=await $e("sha256",A(Te(s),e,r));i.set(c,(s-1)*32)}return i.slice(0,n)}async function Yt(e,t,r,n,o=new Uint8Array,a=new Uint8Array){zt(e),zt(t,"deriveBits");let i=A(wt(b(r)),wt(o),wt(a),Te(n)),s=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Mr(s,n,i)}function qt(e){Ue(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function Ee(e){if(e===void 0)throw new f("JWE Encrypted Key missing")}function Vt(e){if(e!==void 0)throw new f("Encountered unexpected JWE Encrypted Key")}async function Zt(e,t,r,n,o,a){let i=R(e);if(e==="dir")return Vt(n),r;switch(i.subtle.name){case"ECDH":{if(e==="ECDH-ES")Vt(n);if(!S(o.epk))throw new f('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');qt(r);let s=await j(i,o.epk),c,p;if(o.apu!==void 0){if(typeof o.apu!=="string")throw new f('JOSE Header "apu" (Agreement PartyUInfo) invalid');c=W(o.apu,"apu",f)}if(o.apv!==void 0){if(typeof o.apv!=="string")throw new f('JOSE Header "apv" (Agreement PartyVInfo) invalid');p=W(o.apv,"apv",f)}let d=await Yt(s,r,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),c,p);if(e==="ECDH-ES")return d;return Ee(n),ht(e.slice(-6),d,n)}case"RSA-OAEP":return Ee(n),Ue(r),Ft(e,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,n));case"PBKDF2":{if(Ee(n),typeof o.p2c!=="number")throw new f('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=a||1e4;if(o.p2c>s)throw new f('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof o.p2s!=="string")throw new f('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let c=W(o.p2s,"p2s",f),p=await Xt(c,e,o.p2c,r);return ht(e.slice(-6),p,n)}case"AES-KW":return Ee(n),ht(e,r,n);case"AES-GCM":{if(Ee(n),typeof o.iv!=="string")throw new f('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof o.tag!=="string")throw new f('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=W(o.iv,"iv",f);let c;return c=W(o.tag,"tag",f),He(ee(e.slice(0,-2)),r,n,s,c,new Uint8Array)}}}async function Qt(e,t,r,n,o={}){let a,i,s,c=R(e);if(e==="dir")return[r,void 0,void 0];switch(c.subtle.name){case"ECDH":{qt(r);let{apu:p,apv:d}=o;if(p!==void 0)Z(p,'"apu"');if(d!==void 0)Z(d,'"apv"');let u;if(o.epk!==void 0)u=await U(c,o.epk,"decrypt");else u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let l=crypto.subtle,K=u;if(!K.extractable){if(typeof l.getPublicKey!=="function")throw TypeError('CryptoKey for "epk" must be extractable');K=await l.getPublicKey(u,[])}let{x:T,y:g,crv:h,kty:v}=await l.exportKey("jwk",K),y=await Yt(r,u,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),p,d);if(i={epk:{x:T,crv:h,kty:v}},v==="EC")i.epk.y=g;if(p)i.apu=fr(p);if(d)i.apv=fr(d);if(e==="ECDH-ES"){s=y;break}s=n||L(t);let J=e.slice(-6);a=await yt(J,y,s);break}case"RSA-OAEP":{s=n||L(t),Ue(r),Ft(e,r,"encrypt"),a=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",r,s));break}case"PBKDF2":{s=n||L(t);let{p2c:p=2048,p2s:d=crypto.getRandomValues(new Uint8Array(16))}=o,u=await Xt(d,e,p,r);a=await yt(e.slice(-6),u,s),i={p2c:p,p2s:fr(d)};break}case"AES-KW":{s=n||L(t),a=await yt(e,r,s);break}case"AES-GCM":{s=n||L(t);let{iv:p}=o,d=await Ne(ee(e.slice(0,-2)),s,r,p,new Uint8Array);a=d.ciphertext,i={iv:fr(d.iv),tag:fr(d.tag)};break}}return[s,a,i]}var se={__proto__:null,b64:!0},Fe={__proto__:null};function be(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some((r)=>typeof r!=="string")))throw TypeError(`"${e}" option must be an array of strings`);if(!t)return;return new Set(t)}function Xe(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function N(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some((i)=>typeof i!=="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a=r===void 0?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in a))throw new m(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}function ce(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!=="boolean")throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function pe(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!S(n))throw new e("JOSE Header is not a JSON object");return[n,r]}function Ye(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new f('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function er(e){if(typeof globalThis[e]>"u")throw new m(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function tr(e){er("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],o=t.readable.getReader();for(;;){let{value:a,done:i}=await o.read();if(i)break;n.push(a)}return A(...n)}async function rr(e,t){er("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let o=[],a=0,i=r.readable.getReader();for(;;){let{value:s,done:c}=await i.read();if(c)break;if(o.push(s),a+=s.byteLength,t!==1/0&&a>t)throw new f("Decompressed plaintext exceeded the configured limit")}return A(...o)}function nr(e){return[e&&be("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&be("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function $r(e,t,r,n,o){let[a,i,s,c,p]=r,[d,u,l,K,T]=t,{encrypted_key:g}=e;N(f,Fe,s,d,o),Ye(o,d);let{alg:h,enc:v}=o;if(typeof h!=="string"||!h)throw new f("missing JWE Algorithm (alg) in JWE Header");if(typeof v!=="string"||!v)throw new f("missing JWE Encryption Algorithm (enc) in JWE Header");if(a&&!a.has(h)||!a&&h.startsWith("PBES2"))throw new ne('"alg" (Algorithm) Header Parameter value not allowed');if(i&&!i.has(v))throw new ne('"enc" (Encryption Algorithm) Header Parameter value not allowed');let y=ee(v),J;if(g!==void 0)J=W(g,"encrypted_key",f);let P=!1;if(typeof n==="function")n=await n(d,e),P=!0;let H=R(h),O=await U(h==="dir"?y:H,n,"decrypt"),I;try{if(I=await Zt(h,y,O,J,o,c),g!==void 0&&I instanceof Uint8Array&&I.byteLength<<3!==y.cekBits)I=L(y)}catch(C){if(C instanceof TypeError||C instanceof f||C instanceof m)throw C;I=L(y)}let X=await He(y,I,u,l,K,T);if(o.zip==="DEF"){let C=p??250000;if(C===0)throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(C!==1/0&&(!Number.isSafeInteger(C)||C<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");X=await rr(X,C).catch((Y)=>{if(Y instanceof f)throw Y;throw new f("Failed to decompress plaintext",{cause:Y})})}return[X,d,O,P]}async function or(e,t,r){if(e instanceof Uint8Array)e=q.decode(e);if(typeof e!=="string")throw new f("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:c}=e.split(".");if(c!==5)throw new f("Invalid Compact JWE");let p={ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},d=F(n,f,"JWE Protected Header is invalid"),u=b(n),l=[d,W(i,"ciphertext",f),a?W(a,"iv",f):void 0,s?W(s,"tag",f):void 0,u];return $r(p,l,t,r,d)}function ir(e,t,r){if(!Nt(e,t,r))throw new f("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function Lr(e){let[,t,r,n,o,a,i,s,c]=e;if(o!==void 0)Z(o,"JWE Additional Authenticated Data");if(a!==void 0)Z(a,"JWE Content Encryption Key");if(i!==void 0)Z(i,"JWE Initialization Vector");if(t!==void 0)t=pe(f,t)[0],e[1]=t;if(r!==void 0)r=pe(f,r)[0],e[2]=r;if(n!==void 0)n=pe(f,n)[0],e[3]=n;if(s!==void 0&&!S(s))throw TypeError("JWE Key Management Parameters must be an object");ir(t,r,n);let p={...t,...r,...n};Xe(f,t),N(f,Fe,c,t,p),Ye(p,t);let{alg:d,enc:u}=p;if(typeof d!=="string"||!d)throw new f('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof u!=="string"||!u)throw new f('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[p,d,u,ee(u)]}async function jr(e,t,r){let[n,o,,a]=t,[i,s,c,p,d,u,l,K,,T]=e,g=s,h=c;if(u&&(o==="dir"||o==="ECDH-ES"))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let v=R(o),y=await U(o==="dir"?a:v,r,"encrypt"),[J,P,H]=await Qt(o,a,y,u,K);if(H){if(T)h=h?{...h,...H}:H;else g=g?{...g,...H}:H;ir(g,h,p)}let O,I;if(g)O=fr(JSON.stringify(g)),I=b(O);else O="",I=new Uint8Array;let X,C;if(d?.byteLength)C=fr(d),X=A(I,b("."),b(C));else X=I;let Y=i;if(n.zip==="DEF")Y=await tr(Y).catch((Jr)=>{throw new f("Failed to compress plaintext",{cause:Jr})});let{ciphertext:Kr,tag:Pt,iv:It}=await Ne(a,Y,J,l,X),G={ciphertext:fr(Kr)};if(It)G.iv=fr(It);if(Pt)G.tag=fr(Pt);if(P)G.encrypted_key=fr(P);if(C)G.aad=C;if(g)G.protected=O;if(p)G.unprotected=p;if(h)G.header=h;return G}async function ar(e,t,r){if(!e[1]&&!e[2]&&!e[3])throw new f("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(r!==void 0)e[8]=r?.crit,e[9]=r?Ht in r:!1;return jr(e,Lr(e),t)}async function sr(e,t,r){if(t instanceof Uint8Array)return crypto.subtle.importKey("raw",t,e.subtle,!1,[r]);if(k(t,e.subtle,r),e.minRsaBits)Ie(e.alg,t);return t}async function cr(e,t,r){let n=await sr(e,t,"sign"),o=await crypto.subtle.sign(e.signing,n,r);return new Uint8Array(o)}async function pr(e,t,r,n){let o=await sr(e,t,"verify");try{return await crypto.subtle.verify(e.signing,o,r,n)}catch{return!1}}var Se=[["verify"],["sign"]];function gt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Se}}function de(e,t){let n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Se,minRsaBits:2048}}function Et(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Se}}function dr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Se}}function bt(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:Se}}var Ae=ge({HS256:gt(256),HS384:gt(384),HS512:gt(512),RS256:de(256),RS384:de(384),RS512:de(512),PS256:de(256,32),PS384:de(384,48),PS512:de(512,64),ES256:Et("P-256",256),ES384:Et("P-384",384),ES512:Et("P-521",512),EdDSA:dr(),Ed25519:dr(),"ML-DSA-44":bt(44),"ML-DSA-65":bt(65),"ML-DSA-87":bt(87)});function qe(e){let t=typeof e==="string"?Ae[e]:void 0;if(!t)throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function ur(e){return[e&&be("algorithms",e.algorithms),e?.crit]}function zr(e,t=e===void 0?{}:F(e,w,"JWS Protected Header is invalid")){return t}function Vr(e,t,r){let n=ce(e,N(w,se,r[1],e,t)),o=t.alg;if(typeof o!=="string"||!o)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(r[0]&&!r[0].has(o))throw new ne('"alg" (Algorithm) Header Parameter value not allowed');return[n,o]}function Gr(e){try{return b(e)}catch{throw new w("JWS Compact Serialization payload must use only ASCII characters")}}async function Fr(e,t,r,n,o,a,i){let s=!1;if(typeof r==="function")r=await r(o,e),s=!0;let c=typeof i==="string",p=qe(a),d=A(n!==void 0?b(n):new Uint8Array,b("."),c?t[2]??=dt(i,"payload",w):i),u=W(e.signature,"signature",w),l=await U(p,r,"verify");if(!await pr(p,l,u,d))throw new at;return[c?W(i,"payload",w):i,o,c,l,s]}async function lr(e,t,r){if(e instanceof Uint8Array)e=q.decode(e);if(typeof e!=="string")throw new w("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new w("Invalid Compact JWS");let s={payload:o,protected:n,signature:a},c=zr(n),[p,d]=Vr(c,c,t),u=p?o:Gr(o);return Fr(s,t,r,n,c,d,u)}var xe=(e)=>Math.floor(e.getTime()/1000),Xr={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,fe="check_failed";function St(){throw TypeError("Invalid time period format")}function Ze(e){if(typeof e!=="string")St();let t=Yr.exec(e);if(!t||t[4]&&t[1])St();let r=parseFloat(t[2]),n=Math.round(r*Xr[t[3][0].toLowerCase()]);if(!Number.isFinite(n))St();if(t[1]==="-"||t[4]==="ago")return-n;return n}function ue(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function At(e,t){if(typeof t!=="string")throw TypeError(`"${e}" claim must be a string`)}function Zr(e){if(typeof e!=="string"&&(!Array.isArray(e)||Array.from(e).some((t)=>typeof t!=="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function xt(e,t){if(typeof e==="number")return ue(t,e);if(e instanceof Date)return ue(t,xe(e));return xe(new Date)+Ze(e)}var mr=(e)=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},Qr=(e,t)=>{if(typeof e==="string")return t.includes(e);if(Array.isArray(e))return t.some((r)=>e.includes(r));return!1};function Kt(e,t,r=!1){let n=e[t];if(n===void 0&&!r)return;if(typeof n!=="number")throw new _(`"${t}" claim must be a number`,e,t,"invalid");return n}function Jt(e,t){throw new _(`unexpected "${t}" claim value`,e,t,fe)}function le(e,t,r={}){let n;try{n=JSON.parse(re.decode(t))}catch{}if(!S(n))throw new E("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!=="string"||mr(e.typ)!==mr(o)))throw new _('unexpected "typ" JWT header value',n,"typ",fe);let{requiredClaims:a=[],issuer:i,subject:s,audience:c,maxTokenAge:p}=r,d=[...a];if(p!==void 0)d.push("iat");if(c!==void 0)d.push("aud");if(s!==void 0)d.push("sub");if(i!==void 0)d.push("iss");for(let y of new Set(d.reverse()))if(!Object.hasOwn(n,y))throw new _(`missing required "${y}" claim`,n,y,"missing");if(i!==void 0&&!(Array.isArray(i)?i:[i]).includes(n.iss))Jt(n,"iss");if(s!==void 0&&n.sub!==s)Jt(n,"sub");if(c!==void 0&&!Qr(n.aud,typeof c==="string"?[c]:c))Jt(n,"aud");let{clockTolerance:u}=r,l=0;if(typeof u==="string")l=Ze(u);else if(u!==void 0){if(typeof u!=="number")throw TypeError("Invalid clockTolerance option type");l=u}ue("clockTolerance option",l);let{currentDate:K}=r,T=ue("currentDate option",xe(K===void 0?new Date:K)),g=Kt(n,"iat",p!==void 0),h=Kt(n,"nbf");if(h!==void 0){if(h>T+l)throw new _('"nbf" claim timestamp check failed',n,"nbf",fe)}let v=Kt(n,"exp");if(v!==void 0){if(v<=T-l)throw new el('"exp" claim timestamp check failed',n,"exp",fe)}if(p!==void 0){let y=T-g,J=ue("maxTokenAge option",typeof p==="number"?p:Ze(p));if(y-l>J)throw new el('"iat" claim timestamp check failed (too far in the past)',n,"iat",fe);if(y<-l)throw new _('"iat" claim timestamp check failed (it should be in the past)',n,"iat",fe)}return n}var yr;function z(e){return yr.get(e)}function me(e){let t=z(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n==="number"&&!Number.isFinite(n))throw TypeError(`"${r}" claim must be a finite number`)}return ye.encode(JSON.stringify(t))}function Qe(e,t){return z(e)[t]}class te{constructor(e={}){if(!S(e))throw TypeError("JWT Claims Set MUST be an object");(yr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return At("iss",e),z(this).iss=e,this}setSubject(e){return At("sub",e),z(this).sub=e,this}setAudience(e){return Zr(e),z(this).aud=e,this}setJti(e){return At("jti",e),z(this).jti=e,this}setNotBefore(e){return z(this).nbf=xt(e,"setNotBefore"),this}setExpirationTime(e){return z(this).exp=xt(e,"setExpirationTime"),this}setIssuedAt(e){let t=z(this);if(e===void 0)t.iat=xe(new Date);else if(typeof e==="string")t.iat=ue("setIssuedAt",xe(new Date)+Ze(e));else t.iat=xt(e,"setIssuedAt");return this}}async function On(e,t,r){let n=await lr(e,ur(r),t);if(!n[2])throw new E("JWTs MUST NOT use unencoded payload");let a={payload:le(n[1],n[0],r),protectedHeader:n[1]};if(typeof t==="function")return{...a,key:n[3]};return a}async function pc(e,t,r){let n=await or(e,nr(r),t),o=n[1],a=le(o,n[0],r);for(let s of["iss","sub","aud"])if(o[s]!==void 0&&(s==="aud"?JSON.stringify(o.aud)!==JSON.stringify(a.aud):o[s]!==a[s]))throw new _(`replicated "${s}" claim header parameter mismatch`,a,s,"mismatch");let i={payload:a,protectedHeader:o};if(typeof t==="function")return{...i,key:n[2]};return i}function en(e){if(e===void 0)return[void 0,""];let t=pe(w,e);return[t[0],fr(t[1])]}function tn(e,t,r){return Xe(w,e),ce(e,N(w,se,r,e,t))}function rn(e){let t=e.alg;if(typeof t!=="string"||!t)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');return qe(t)}async function nn(e,t,r,n){let o=A(b(e),b("."),t),a=await U(r,n,"sign");return fr(await cr(r,a,o))}async function hr(e,t,r,n,o){let[a,i]=en(t);if(!a)throw new w("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tn(a,a,r))o();let c=rn(a),p=fr(e),d=await nn(i,b(p),c,n);return`${i}.${p}.${d}`}var on=te;class mc extends on{#e;setProtectedHeader(e){return Q(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return hr(me(this),this.#e,t?.crit,e,()=>{throw new E("JWTs MUST NOT use unencoded payload")})}}var an=te;class hc extends an{#e;#r;#n;#t;#o;#i;#a;setProtectedHeader(e){return Q(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return Q(this.#n,"setKeyManagementParameters"),this.#n=e,this}setContentEncryptionKey(e){return Q(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return Q(this.#r,"setInitializationVector"),this.#r=e,this}replicateIssuerAsHeader(){return this.#o=!0,this}replicateSubjectAsHeader(){return this.#i=!0,this}replicateAudienceAsHeader(){return this.#a=!0,this}async encrypt(e,t){let r=me(this);if(this.#t&&(this.#o||this.#i||this.#a))this.#t={...this.#t,iss:this.#o?Qe(this,"iss"):void 0,sub:this.#i?Qe(this,"sub"):void 0,aud:this.#a?Qe(this,"aud"):void 0};let n=await ar([r,this.#t,void 0,void 0,void 0,this.#e,this.#r,this.#n,void 0,!1],e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}var Wt='"alg" (Algorithm)';function Ct(e='JWK "alg" (Algorithm) Parameter'){throw new m(`Invalid or unsupported ${e} value`)}function Ke(e,t){return(typeof e==="string"?Ae[e]??mt[e]:void 0)??Ct(t)}function et(e){if(e!==void 0&&typeof e!=="boolean")throw TypeError('"extractable" option must be a boolean');return e}var Je=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},sn=(e)=>({data:e,pos:0}),vt=(e)=>{let t=e.data[e.pos++];if(t===void 0)throw Error("Unexpected end of ASN.1 input");return t},We=(e)=>{let t=vt(e);if(t&128){let r=t&127,n=0;for(let o=0;o<r;o++)n=n<<8|vt(e);return n}return t};var Ce=(e,t,r)=>{if(vt(e)!==t)throw Error(r)},wr=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},cn=(e)=>{Ce(e,6,"Expected algorithm OID");let t=We(e);return wr(e,t)};function pn(e,t){if(Ce(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),We(e),t==="pkcs8"){Ce(e,2,"Expected version field");let r=We(e);e.pos+=r}Ce(e,48,"Expected algorithm identifier"),We(e)}var dn=(e)=>{let t=cn(e);if(Je(t,[43,101,110]))return"X25519";if(!Je(t,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");Ce(e,6,"Expected curve OID");let r=We(e),n=wr(e,r);if(Je(n,[42,134,72,206,61,3,1,7]))return"P-256";if(Je(n,[43,129,4,0,34]))return"P-384";if(Je(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")},fn=async(e,t,r,n)=>{let o=et(n?.extractable),a=Ke(r,Wt);if(a.secret)Ct(Wt);let i=e==="spki",s;if(a.resolve)try{let c=sn(t);pn(c,e),s=a.resolve({crv:dn(c)})}catch{throw new m("Invalid or unsupported key format")}else s=a.subtle;return crypto.subtle.importKey(e,t,s,o??i,a.usages[i?0:1])},un=(e,t)=>Be(e.replace(t,"")),gr=(e,t,r)=>{let n=un(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return fn("pkcs8",n,t,r)};function ln(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function mn(e){if(st(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:fr(e)};if(!M(e))throw TypeError(B(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=ln(await crypto.subtle.exportKey("jwk",e));if(a.kty==="AKP")a.alg=n;return a}function Er(e){return mn(e)}var V=(e,t)=>{if(typeof e!=="string"||!e)throw new _e(`${t} missing or invalid`)};async function gc(e,t){let r;if(S(e)){if(r=oe(e),typeof r.kty!=="string")throw TypeError(B(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(Re(e))r=oe(await Er(e));else throw TypeError(B(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 n;switch(r.kty){case"AKP":V(r.alg,'"alg" (Algorithm) Parameter'),V(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":V(r.crv,'"crv" (Curve) Parameter'),V(r.x,'"x" (X Coordinate) Parameter'),V(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":V(r.crv,'"crv" (Subtype of Key Pair) Parameter'),V(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":V(r.e,'"e" (Exponent) Parameter'),V(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!=="string")throw new _e('"k" (Key Value) Parameter missing or invalid');n={k:r.k,kty:r.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}let o=b(JSON.stringify(n));return fr(await $e(t,o))}function yn(e,t,r,n){let{kty:o,key_ops:a,ext:i,kid:s,alg:c,use:p,crv:d}=oe(e),u=Array.isArray(a)?[...a]:a;return(i===void 0||typeof i==="boolean")&&(u===void 0||Array.isArray(u)&&u.every((l,K)=>typeof l==="string"&&u.indexOf(l)===K)&&u.includes("verify"))&&t.kty.includes(o)&&(n===void 0||typeof n==="string"&&n===s)&&(c===void 0?o!=="AKP":r===c)&&(p===void 0||p==="sig")&&(!t.crv||d===t.crv)}async function br(e,t,r){let n=e.get(t)||e.set(t,{}).get(t),{alg:o}=r;if(n[o]===void 0){let a=await j(r,{...t,alg:o,ext:!0});if(a.type!=="public")throw new De("JSON Web Key Set members must be public keys");n[o]=a}return n[o]}function Su(e){let t;try{t=structuredClone(e)}catch{}if(!Me(t))throw new De("JSON Web Key Set malformed");let r=new WeakMap;return Object.defineProperty(async(o,a)=>{let{alg:i,kid:s}={...o,...a?.header},c=typeof i==="string"?Ae[i]:void 0;if(!c||c.secret)throw new m('Unsupported "alg" value for a JSON Web Key Set');let p=t.keys.filter((l)=>yn(l,c,i,s)),{0:d,length:u}=p;if(!u)throw new we;if(u!==1){let l=new ot;throw l[Symbol.asyncIterator]=async function*(){for(let K of p)try{yield await br(r,K,c)}catch{}},l}return br(r,d,c)},"jwks",{value:()=>structuredClone(t)})}function hn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var Tt;if(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))Tt="jose/v6.2.10";var Ar=Symbol();async function wn(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch((a)=>{if(a.name==="TimeoutError")throw new it;throw a});if(o.status!==200)throw new x("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new x("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var xr=Symbol();function ve(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Sr(e,t,r){if(Number.isNaN(e))throw TypeError(`"${r}" option must not be NaN`);return typeof e==="number"?e:t}function Eu(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let r=new URL(e.href).href,n=t??{},o=n.timeoutDuration;if(typeof o==="number"&&(!Number.isInteger(o)||o<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let a=typeof o==="number"?o:5000,i=Sr(n.cooldownDuration,30000,"cooldownDuration"),s=Sr(n.cacheMaxAge,600000,"cacheMaxAge"),c=new Headers(n.headers);if(Tt&&!c.has("User-Agent"))c.set("User-Agent",Tt);if(!c.has("accept"))c.set("accept","application/json, application/jwk-set+json");let p=n[Ar],d=n[xr],u,l,K=0,T=0,g;if(d&&typeof d==="object"){let{uat:y,jwks:J}=d;if(ve(y,s)&&Me(J))u=y,g=Su(J)}let h=async()=>{if(l&&hn())l=void 0;if(!l){let y=++K,J=l=wn(r,c,AbortSignal.timeout(a),p).then((P)=>{let H=Su(P);if(y<=T)return;g=H;let O=Date.now();if(d)d.uat=O,d.jwks=P;u=O,T=y}).finally(()=>{if(l===J)l=void 0})}await l};return Object.defineProperties(async(y,J)=>{if(!g||!ve(u,s))await h();try{return await g(y,J)}catch(P){if(P instanceof we&&!ve(u,i))return await h(),g(y,J);throw P}},{coolingDown:{get:()=>ve(u,i),enumerable:!0},fresh:{get:()=>ve(u,s),enumerable:!0},reload:{value:h,enumerable:!0},reloading:{get:()=>!!l,enumerable:!0},jwks:{value:()=>g?.jwks(),enumerable:!0}})}var gn=te;class Am extends gn{encode(){let e=fr(JSON.stringify({alg:"none"})),t=fr(me(this));return`${e}.${t}.`}static decode(e,t){if(typeof e!=="string")throw new E("Unsecured JWT must be a string");let{0:r,1:n,2:o,length:a}=e.split(".");if(a!==3||o!=="")throw new E("Invalid Unsecured JWT");let i,s;try{i=F(r,w,"JWS Protected Header is invalid");let p=N(w,se,void 0,i,i);s=ce(i,p)}catch(p){if(!(p instanceof w))throw p;throw new E("Invalid Unsecured JWT",{cause:p})}if(i.alg!=="none")throw new E("Invalid Unsecured JWT");if(!s)throw new E("JWTs MUST NOT use unencoded payload");return{payload:le(i,W(n,"payload",E),t),header:i}}}async function jA(e,t,r){if(typeof e!=="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw TypeError('"pkcs8" must be PKCS#8 formatted string');return gr(e,t,r)}async function Ms(e,t,r){if(!S(e))throw TypeError("JWK must be an object");let n=Le(e),o=et(r?.extractable),{alg:a}=n;t??=a;let i=o??n.ext;if(n.kty!=="oct"&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(n.kty){case"oct":if(typeof n.k!=="string")throw TypeError('missing "k" (Key Value) Parameter value');return D(n.k);case"AKP":{if(typeof a!=="string"||!a)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==a)throw TypeError("JWK alg and alg option value mismatch");return j(Ke(t),{...n,ext:i})}case"RSA":case"EC":case"OKP":return j(Ke(t),{...n,alg:t,ext:i});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}function Ho(e){let t;if(typeof e==="string"){let n=e.split(".");if(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");let r="Invalid Token or Protected Header formatting";if(typeof t!=="string"||!t)throw TypeError(r);return F(t,TypeError,r)}function qr(e){if(typeof e!=="string")throw new E("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new E("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new E("Invalid JWT");if(!t)throw new E("JWTs must contain a payload");let n;try{n=D(t)}catch{throw new E("Failed to base64url decode the payload")}let o;try{o=JSON.parse(re.decode(n))}catch{throw new E("Failed to parse the decoded payload as JSON")}if(!S(o))throw new E("Invalid JWT Claims Set");return o}export{el,fr,pf,On,pc,mc,hc,gc,Su,Eu,Am,jA,Ms,Ho,qr};
|
|
2
|
+
import{ke}from"./chunk-a8bymrv1.js";var ye=new TextEncoder,q=new TextDecoder,re=new TextDecoder("utf-8",{fatal:!0});function A(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function tt(e,t,r){if(t<0||t>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function rt(e){let t=Math.floor(e/4294967296),r=e%4294967296,n=new Uint8Array(8);return tt(n,t,0),tt(n,r,4),n}function Te(e){let t=new Uint8Array(4);return tt(t,e),t}function b(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Pe=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function nt(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ie(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!=="number"||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function k(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw Pe(t.name);if(t.hash&&n.hash?.name!==t.hash)throw Pe(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw Pe(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw Pe(t.length,"algorithm.length");nt(e,r)}function Ot(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else if(r.length===2)e+=`one of type ${r[0]} or ${r[1]}.`;else e+=`of type ${r[0]}.`;if(t==null)e+=` Received ${t}`;else if(typeof t==="function"&&t.name)e+=` Received function ${t.name}`;else if(typeof t==="object"&&t!=null){if(t.constructor?.name)e+=` Received an instance of ${t.constructor.name}`}return e}var B=(e,...t)=>Ot("Key must be ",e,...t),he=(e,t,...r)=>Ot(`Key for the ${e} algorithm must be `,t,...r);class x 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)}}class _ extends x{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}});this.claim=r,this.reason=n,this.payload=t}}class nl extends x{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}});this.claim=r,this.reason=n,this.payload=t}}class ne extends x{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class m extends x{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Oe extends x{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class f extends x{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class w extends x{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class E extends x{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class _e extends x{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class De extends x{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class we extends x{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)}}class ot extends x{[Symbol.asyncIterator]=async function*(){};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)}}class it extends x{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class at extends x{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Ue(e){if(!M(e))throw Error("CryptoKey instance expected")}var M=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},st=(e)=>e?.[Symbol.toStringTag]==="KeyObject",Re=(e)=>M(e)||st(e);var L=(e)=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function _t(e,t){let r=e.byteLength<<3;if(r!==t)throw new f(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var Wr=(e)=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function Dt(e,t){if(t.length<<3!==e.ivBits)throw new f("Invalid Initialization Vector length")}async function Ut(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(B(t,"Uint8Array"));let n=e.cekBits>>1,o=await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),a=await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return[o,a,n]}async function Rt(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function Cr(e,t,r,n,o){let[a,i,s]=await Ut(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),p=A(o,n,c,rt(o.length*8)),d=await Rt(i,p,s);return{ciphertext:c,tag:d,iv:n}}async function vr(e,t){let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign","verify"]),o=await crypto.subtle.sign(r,n,e);return crypto.subtle.verify(r,n,o,t)}async function Tr(e,t,r,n,o,a){let[i,s,c]=await Ut(e,t,"decrypt"),p=A(a,n,r,rt(a.length*8)),d=await Rt(s,p,c);try{if(await vr(o,d))return new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},i,r))}catch{}throw new Oe}async function Pr(e,t,r,n,o){let a=r instanceof Uint8Array?await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(k(r,e.subtle,"encrypt"),r),i=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s,iv:n}}async function Ir(e,t,r,n,o,a){let i=t instanceof Uint8Array?await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(k(t,e.subtle,"decrypt"),t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,A(r,o)))}catch{throw new Oe}}async function Ne(e,t,r,n,o){if(!M(r)&&!(r instanceof Uint8Array))throw TypeError(B(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n)Dt(e,n);else n=Wr(e);if(r instanceof Uint8Array)_t(r,e.cekBits);return e.cbc?Cr(e,t,r,n,o):Pr(e,t,r,n,o)}async function He(e,t,r,n,o,a){if(!M(t)&&!(t instanceof Uint8Array))throw TypeError(B(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new f("JWE Initialization Vector missing");if(!o)throw new f("JWE Authentication Tag missing");if(!e.cbc&&o.length!==16)throw new f("Invalid Authentication Tag length");if(Dt(e,n),t instanceof Uint8Array)_t(t,e.cekBits);return e.cbc?Tr(e,t,r,n,o,a):Ir(e,t,r,n,o,a)}var pf={};ke(pf,{decode:()=>D,encode:()=>fr});function ct(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function Be(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var pt="The input to be decoded is not correctly encoded.";function D(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==="string"?e:q.decode(e),{alphabet:"base64url"})}catch(r){throw TypeError(pt,{cause:r})}let t=e;if(t instanceof Uint8Array)t=q.decode(t);if(t.includes("+")||t.includes("/"))throw TypeError(pt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Be(t)}catch{throw TypeError(pt)}}function fr(e){let t=e;if(typeof t==="string")t=ye.encode(t);if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:"base64url",omitPadding:!0});return ct(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Z(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function S(e){if(typeof e!=="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Me(e){return S(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(S)}function Nt(...e){let t=new Set;for(let r of e){if(!r)continue;for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}}return!0}var Ht=Symbol();function Q(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function W(e,t,r){try{return D(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function dt(e,t,r){try{return b(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}async function $e(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}function F(e,t,r){let n;try{n=JSON.parse(re.decode(D(e)))}catch{throw new t(r)}if(!S(n))throw new t(r);return n}async function j(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t};if(o.kty!=="AKP")delete o.alg;return delete o.use,crypto.subtle.importKey("jwk",o,r,t.ext??!n,t.key_ops??e.usages[n?1:0])}function oe(e){return{__proto__:null,...e}}function Le(e){let t=oe(e);if(t.ext!==void 0&&typeof t.ext!=="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some((o)=>typeof o!=="string")||new Set(n).size!==n.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}var ft=(e)=>e[Symbol.toStringTag],Or=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};function _r(e,t,r){let{alg:n,secret:o}=e,a=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return[Bt,t];if(S(t)){let i=Le(t);if(typeof i.kty!=="string")throw TypeError(o?he(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):he(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(o?i.kty==="oct"&&typeof i.k==="string":i.kty!=="oct"&&(a?i.kty==="AKP"&&typeof i.priv==="string"||typeof i.d==="string":i.d===void 0&&i.priv===void 0)))throw TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${a?"private":"public"} JWK`);return Or(e,i,r),[Lt,t,i]}if(!Re(t))throw TypeError(o?he(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):he(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(o){if(t.type!=="secret")throw TypeError(`${ft(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw TypeError(`${ft(t)} instances for asymmetric algorithms must not be of type "secret"`);let i=a?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==i){let s=r==="sign"?"signing":r==="verify"?"verifying":`${r.slice(0,-1)}tion`;throw TypeError(`${ft(t)} instances for asymmetric algorithm ${s} must be of type "${i}"`)}}return M(t)?[Mt,t]:[$t,t]}var Bt=0,Mt=1,$t=2,Lt=3,ut,Dr={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function je(e,t,r){ut||=new WeakMap;let n=ut.get(e);if(r)if(n)n[t]=r;else ut.set(e,{[t]:r});return r??n?.[t]}var kt=async(e,t,r)=>je(e,r.alg)??je(e,r.alg,await j(r,{...t,alg:r.alg})),Ur=(e,t)=>{let r=je(e,t.alg);if(r)return r;let n=e.type==="public",o=t.usages[n?0:1],{asymmetricKeyType:a}=e,i=Dr[e.asymmetricKeyDetails?.namedCurve],s=t.resolve?.({crv:i,asymmetricKeyType:a})??t.subtle;return je(e,t.alg,e.toCryptoKey(s,n,o))};async function U(e,t,r){let n=_r(e,t,r);switch(n[0]){case Bt:case Mt:return n[1];case Lt:{let o=n[1],a=n[2];if(a.kty==="oct")return D(a.k);if(!Object.isFrozen(o)){let{key_ops:i}=o;if(Array.isArray(i))Object.freeze(i);Object.freeze(o)}return kt(o,a,e)}case $t:{let o=n[1];if(o.type==="secret")return o.export();if("toCryptoKey"in o&&typeof o.toCryptoKey==="function")return Ur(o,e);return kt(o,o.export({format:"jwk"}),e)}}}function ge(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Rr=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Nr=[[],["deriveBits"]],Ge=[[],[]];function ze(e){return{kty:["RSA"],subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Rr,ops:["wrapKey","unwrapKey"]}}function Ve(){return{kty:["EC","OKP"],subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if(t==="X25519"||r==="x25519")return{name:"X25519"};if(e==="OKP")throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Nr,ops:[void 0,"deriveBits"]}}function ie(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:Ge,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function lt(){return{kty:["oct"],secret:!0,subtle:{name:"PBKDF2"},usages:Ge,ops:["deriveBits","deriveBits"]}}var mt=ge({dir:{kty:["oct"],secret:!0,subtle:{name:"AES-GCM"},usages:Ge,ops:["encrypt","decrypt"]},"RSA-OAEP":ze(1),"RSA-OAEP-256":ze(256),"RSA-OAEP-384":ze(384),"RSA-OAEP-512":ze(512),"ECDH-ES":Ve(),"ECDH-ES+A128KW":Ve(),"ECDH-ES+A192KW":Ve(),"ECDH-ES+A256KW":Ve(),A128KW:ie(128),A192KW:ie(192),A256KW:ie(256),A128GCMKW:ie(128,!0),A192GCMKW:ie(192,!0),A256GCMKW:ie(256,!0),"PBES2-HS256+A128KW":lt(),"PBES2-HS384+A192KW":lt(),"PBES2-HS512+A256KW":lt()}),Hr=["encrypt","decrypt"];function ae(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:Ge,ops:Hr,cekBits:e,ivBits:t?128:96,cbc:t}}var kr=ge({A128GCM:ae(128),A192GCM:ae(192),A256GCM:ae(256),"A128CBC-HS256":ae(256,!0),"A192CBC-HS384":ae(384,!0),"A256CBC-HS512":ae(512,!0)});function jt(e,t){throw new m(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function R(e){return(typeof e==="string"?mt[e]:void 0)??jt("alg","Algorithm")}function ee(e){return(typeof e==="string"?kr[e]:void 0)??jt("enc","Encryption Algorithm")}function zt(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");nt(e,t)}async function Gt(e,t,r){let n=R(t).subtle,o=e instanceof Uint8Array?await crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):e;return k(o,n,r),o}async function yt(e,t,r){let n=await Gt(t,e,"wrapKey"),o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function ht(e,t,r){let n=await Gt(t,e,"unwrapKey"),o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}function Ft(e,t,r){k(t,R(e).subtle,r),Ie(e,t)}function Br(e,t){if(e instanceof Uint8Array)return crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);return k(e,R(t).subtle,"deriveBits"),e}async function Xt(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new f("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new f("PBES2 Count Input must be a positive integer");let o=A(b(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await Br(n,t);return new Uint8Array(await crypto.subtle.deriveBits(i,s,a))}function wt(e){return A(Te(e.length),e)}async function Mr(e,t,r){let n=t>>3,o=32,a=Math.ceil(n/32),i=new Uint8Array(a*32);for(let s=1;s<=a;s++){let c=await $e("sha256",A(Te(s),e,r));i.set(c,(s-1)*32)}return i.slice(0,n)}async function Yt(e,t,r,n,o=new Uint8Array,a=new Uint8Array){zt(e),zt(t,"deriveBits");let i=A(wt(b(r)),wt(o),wt(a),Te(n)),s=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Mr(s,n,i)}function qt(e){Ue(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function Ee(e){if(e===void 0)throw new f("JWE Encrypted Key missing")}function Vt(e){if(e!==void 0)throw new f("Encountered unexpected JWE Encrypted Key")}async function Zt(e,t,r,n,o,a){let i=R(e);if(e==="dir")return Vt(n),r;switch(i.subtle.name){case"ECDH":{if(e==="ECDH-ES")Vt(n);if(!S(o.epk))throw new f('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');qt(r);let s=await j(i,o.epk),c,p;if(o.apu!==void 0){if(typeof o.apu!=="string")throw new f('JOSE Header "apu" (Agreement PartyUInfo) invalid');c=W(o.apu,"apu",f)}if(o.apv!==void 0){if(typeof o.apv!=="string")throw new f('JOSE Header "apv" (Agreement PartyVInfo) invalid');p=W(o.apv,"apv",f)}let d=await Yt(s,r,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),c,p);if(e==="ECDH-ES")return d;return Ee(n),ht(e.slice(-6),d,n)}case"RSA-OAEP":return Ee(n),Ue(r),Ft(e,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,n));case"PBKDF2":{if(Ee(n),typeof o.p2c!=="number")throw new f('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=a||1e4;if(o.p2c>s)throw new f('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof o.p2s!=="string")throw new f('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let c=W(o.p2s,"p2s",f),p=await Xt(c,e,o.p2c,r);return ht(e.slice(-6),p,n)}case"AES-KW":return Ee(n),ht(e,r,n);case"AES-GCM":{if(Ee(n),typeof o.iv!=="string")throw new f('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof o.tag!=="string")throw new f('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=W(o.iv,"iv",f);let c;return c=W(o.tag,"tag",f),He(ee(e.slice(0,-2)),r,n,s,c,new Uint8Array)}}}async function Qt(e,t,r,n,o={}){let a,i,s,c=R(e);if(e==="dir")return[r,void 0,void 0];switch(c.subtle.name){case"ECDH":{qt(r);let{apu:p,apv:d}=o;if(p!==void 0)Z(p,'"apu"');if(d!==void 0)Z(d,'"apv"');let u;if(o.epk!==void 0)u=await U(c,o.epk,"decrypt");else u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let l=crypto.subtle,K=u;if(!K.extractable){if(typeof l.getPublicKey!=="function")throw TypeError('CryptoKey for "epk" must be extractable');K=await l.getPublicKey(u,[])}let{x:T,y:g,crv:h,kty:v}=await l.exportKey("jwk",K),y=await Yt(r,u,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),p,d);if(i={epk:{x:T,crv:h,kty:v}},v==="EC")i.epk.y=g;if(p)i.apu=fr(p);if(d)i.apv=fr(d);if(e==="ECDH-ES"){s=y;break}s=n||L(t);let J=e.slice(-6);a=await yt(J,y,s);break}case"RSA-OAEP":{s=n||L(t),Ue(r),Ft(e,r,"encrypt"),a=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",r,s));break}case"PBKDF2":{s=n||L(t);let{p2c:p=2048,p2s:d=crypto.getRandomValues(new Uint8Array(16))}=o,u=await Xt(d,e,p,r);a=await yt(e.slice(-6),u,s),i={p2c:p,p2s:fr(d)};break}case"AES-KW":{s=n||L(t),a=await yt(e,r,s);break}case"AES-GCM":{s=n||L(t);let{iv:p}=o,d=await Ne(ee(e.slice(0,-2)),s,r,p,new Uint8Array);a=d.ciphertext,i={iv:fr(d.iv),tag:fr(d.tag)};break}}return[s,a,i]}var se={__proto__:null,b64:!0},Fe={__proto__:null};function be(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some((r)=>typeof r!=="string")))throw TypeError(`"${e}" option must be an array of strings`);if(!t)return;return new Set(t)}function Xe(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function N(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some((i)=>typeof i!=="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a=r===void 0?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in a))throw new m(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}function ce(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!=="boolean")throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function pe(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!S(n))throw new e("JOSE Header is not a JSON object");return[n,r]}function Ye(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new f('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function er(e){if(typeof globalThis[e]>"u")throw new m(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function tr(e){er("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],o=t.readable.getReader();for(;;){let{value:a,done:i}=await o.read();if(i)break;n.push(a)}return A(...n)}async function rr(e,t){er("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let o=[],a=0,i=r.readable.getReader();for(;;){let{value:s,done:c}=await i.read();if(c)break;if(o.push(s),a+=s.byteLength,t!==1/0&&a>t)throw new f("Decompressed plaintext exceeded the configured limit")}return A(...o)}function nr(e){return[e&&be("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&be("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function $r(e,t,r,n,o){let[a,i,s,c,p]=r,[d,u,l,K,T]=t,{encrypted_key:g}=e;N(f,Fe,s,d,o),Ye(o,d);let{alg:h,enc:v}=o;if(typeof h!=="string"||!h)throw new f("missing JWE Algorithm (alg) in JWE Header");if(typeof v!=="string"||!v)throw new f("missing JWE Encryption Algorithm (enc) in JWE Header");if(a&&!a.has(h)||!a&&h.startsWith("PBES2"))throw new ne('"alg" (Algorithm) Header Parameter value not allowed');if(i&&!i.has(v))throw new ne('"enc" (Encryption Algorithm) Header Parameter value not allowed');let y=ee(v),J;if(g!==void 0)J=W(g,"encrypted_key",f);let P=!1;if(typeof n==="function")n=await n(d,e),P=!0;let H=R(h),O=await U(h==="dir"?y:H,n,"decrypt"),I;try{if(I=await Zt(h,y,O,J,o,c),g!==void 0&&I instanceof Uint8Array&&I.byteLength<<3!==y.cekBits)I=L(y)}catch(C){if(C instanceof TypeError||C instanceof f||C instanceof m)throw C;I=L(y)}let X=await He(y,I,u,l,K,T);if(o.zip==="DEF"){let C=p??250000;if(C===0)throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(C!==1/0&&(!Number.isSafeInteger(C)||C<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");X=await rr(X,C).catch((Y)=>{if(Y instanceof f)throw Y;throw new f("Failed to decompress plaintext",{cause:Y})})}return[X,d,O,P]}async function or(e,t,r){if(e instanceof Uint8Array)e=q.decode(e);if(typeof e!=="string")throw new f("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:c}=e.split(".");if(c!==5)throw new f("Invalid Compact JWE");let p={ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},d=F(n,f,"JWE Protected Header is invalid"),u=b(n),l=[d,W(i,"ciphertext",f),a?W(a,"iv",f):void 0,s?W(s,"tag",f):void 0,u];return $r(p,l,t,r,d)}function ir(e,t,r){if(!Nt(e,t,r))throw new f("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function Lr(e){let[,t,r,n,o,a,i,s,c]=e;if(o!==void 0)Z(o,"JWE Additional Authenticated Data");if(a!==void 0)Z(a,"JWE Content Encryption Key");if(i!==void 0)Z(i,"JWE Initialization Vector");if(t!==void 0)t=pe(f,t)[0],e[1]=t;if(r!==void 0)r=pe(f,r)[0],e[2]=r;if(n!==void 0)n=pe(f,n)[0],e[3]=n;if(s!==void 0&&!S(s))throw TypeError("JWE Key Management Parameters must be an object");ir(t,r,n);let p={...t,...r,...n};Xe(f,t),N(f,Fe,c,t,p),Ye(p,t);let{alg:d,enc:u}=p;if(typeof d!=="string"||!d)throw new f('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof u!=="string"||!u)throw new f('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[p,d,u,ee(u)]}async function jr(e,t,r){let[n,o,,a]=t,[i,s,c,p,d,u,l,K,,T]=e,g=s,h=c;if(u&&(o==="dir"||o==="ECDH-ES"))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let v=R(o),y=await U(o==="dir"?a:v,r,"encrypt"),[J,P,H]=await Qt(o,a,y,u,K);if(H){if(T)h=h?{...h,...H}:H;else g=g?{...g,...H}:H;ir(g,h,p)}let O,I;if(g)O=fr(JSON.stringify(g)),I=b(O);else O="",I=new Uint8Array;let X,C;if(d?.byteLength)C=fr(d),X=A(I,b("."),b(C));else X=I;let Y=i;if(n.zip==="DEF")Y=await tr(Y).catch((Jr)=>{throw new f("Failed to compress plaintext",{cause:Jr})});let{ciphertext:Kr,tag:Pt,iv:It}=await Ne(a,Y,J,l,X),G={ciphertext:fr(Kr)};if(It)G.iv=fr(It);if(Pt)G.tag=fr(Pt);if(P)G.encrypted_key=fr(P);if(C)G.aad=C;if(g)G.protected=O;if(p)G.unprotected=p;if(h)G.header=h;return G}async function ar(e,t,r){if(!e[1]&&!e[2]&&!e[3])throw new f("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(r!==void 0)e[8]=r?.crit,e[9]=r?Ht in r:!1;return jr(e,Lr(e),t)}async function sr(e,t,r){if(t instanceof Uint8Array)return crypto.subtle.importKey("raw",t,e.subtle,!1,[r]);if(k(t,e.subtle,r),e.minRsaBits)Ie(e.alg,t);return t}async function cr(e,t,r){let n=await sr(e,t,"sign"),o=await crypto.subtle.sign(e.signing,n,r);return new Uint8Array(o)}async function pr(e,t,r,n){let o=await sr(e,t,"verify");try{return await crypto.subtle.verify(e.signing,o,r,n)}catch{return!1}}var Se=[["verify"],["sign"]];function gt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Se}}function de(e,t){let n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Se,minRsaBits:2048}}function Et(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Se}}function dr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Se}}function bt(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:Se}}var Ae=ge({HS256:gt(256),HS384:gt(384),HS512:gt(512),RS256:de(256),RS384:de(384),RS512:de(512),PS256:de(256,32),PS384:de(384,48),PS512:de(512,64),ES256:Et("P-256",256),ES384:Et("P-384",384),ES512:Et("P-521",512),EdDSA:dr(),Ed25519:dr(),"ML-DSA-44":bt(44),"ML-DSA-65":bt(65),"ML-DSA-87":bt(87)});function qe(e){let t=typeof e==="string"?Ae[e]:void 0;if(!t)throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function ur(e){return[e&&be("algorithms",e.algorithms),e?.crit]}function zr(e,t=e===void 0?{}:F(e,w,"JWS Protected Header is invalid")){return t}function Vr(e,t,r){let n=ce(e,N(w,se,r[1],e,t)),o=t.alg;if(typeof o!=="string"||!o)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(r[0]&&!r[0].has(o))throw new ne('"alg" (Algorithm) Header Parameter value not allowed');return[n,o]}function Gr(e){try{return b(e)}catch{throw new w("JWS Compact Serialization payload must use only ASCII characters")}}async function Fr(e,t,r,n,o,a,i){let s=!1;if(typeof r==="function")r=await r(o,e),s=!0;let c=typeof i==="string",p=qe(a),d=A(n!==void 0?b(n):new Uint8Array,b("."),c?t[2]??=dt(i,"payload",w):i),u=W(e.signature,"signature",w),l=await U(p,r,"verify");if(!await pr(p,l,u,d))throw new at;return[c?W(i,"payload",w):i,o,c,l,s]}async function lr(e,t,r){if(e instanceof Uint8Array)e=q.decode(e);if(typeof e!=="string")throw new w("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new w("Invalid Compact JWS");let s={payload:o,protected:n,signature:a},c=zr(n),[p,d]=Vr(c,c,t),u=p?o:Gr(o);return Fr(s,t,r,n,c,d,u)}var xe=(e)=>Math.floor(e.getTime()/1000),Xr={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,fe="check_failed";function St(){throw TypeError("Invalid time period format")}function Ze(e){if(typeof e!=="string")St();let t=Yr.exec(e);if(!t||t[4]&&t[1])St();let r=parseFloat(t[2]),n=Math.round(r*Xr[t[3][0].toLowerCase()]);if(!Number.isFinite(n))St();if(t[1]==="-"||t[4]==="ago")return-n;return n}function ue(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function At(e,t){if(typeof t!=="string")throw TypeError(`"${e}" claim must be a string`)}function Zr(e){if(typeof e!=="string"&&(!Array.isArray(e)||Array.from(e).some((t)=>typeof t!=="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function xt(e,t){if(typeof e==="number")return ue(t,e);if(e instanceof Date)return ue(t,xe(e));return xe(new Date)+Ze(e)}var mr=(e)=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},Qr=(e,t)=>{if(typeof e==="string")return t.includes(e);if(Array.isArray(e))return t.some((r)=>e.includes(r));return!1};function Kt(e,t,r=!1){let n=e[t];if(n===void 0&&!r)return;if(typeof n!=="number")throw new _(`"${t}" claim must be a number`,e,t,"invalid");return n}function Jt(e,t){throw new _(`unexpected "${t}" claim value`,e,t,fe)}function le(e,t,r={}){let n;try{n=JSON.parse(re.decode(t))}catch{}if(!S(n))throw new E("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!=="string"||mr(e.typ)!==mr(o)))throw new _('unexpected "typ" JWT header value',n,"typ",fe);let{requiredClaims:a=[],issuer:i,subject:s,audience:c,maxTokenAge:p}=r,d=[...a];if(p!==void 0)d.push("iat");if(c!==void 0)d.push("aud");if(s!==void 0)d.push("sub");if(i!==void 0)d.push("iss");for(let y of new Set(d.reverse()))if(!Object.hasOwn(n,y))throw new _(`missing required "${y}" claim`,n,y,"missing");if(i!==void 0&&!(Array.isArray(i)?i:[i]).includes(n.iss))Jt(n,"iss");if(s!==void 0&&n.sub!==s)Jt(n,"sub");if(c!==void 0&&!Qr(n.aud,typeof c==="string"?[c]:c))Jt(n,"aud");let{clockTolerance:u}=r,l=0;if(typeof u==="string")l=Ze(u);else if(u!==void 0){if(typeof u!=="number")throw TypeError("Invalid clockTolerance option type");l=u}ue("clockTolerance option",l);let{currentDate:K}=r,T=ue("currentDate option",xe(K===void 0?new Date:K)),g=Kt(n,"iat",p!==void 0),h=Kt(n,"nbf");if(h!==void 0){if(h>T+l)throw new _('"nbf" claim timestamp check failed',n,"nbf",fe)}let v=Kt(n,"exp");if(v!==void 0){if(v<=T-l)throw new nl('"exp" claim timestamp check failed',n,"exp",fe)}if(p!==void 0){let y=T-g,J=ue("maxTokenAge option",typeof p==="number"?p:Ze(p));if(y-l>J)throw new nl('"iat" claim timestamp check failed (too far in the past)',n,"iat",fe);if(y<-l)throw new _('"iat" claim timestamp check failed (it should be in the past)',n,"iat",fe)}return n}var yr;function z(e){return yr.get(e)}function me(e){let t=z(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n==="number"&&!Number.isFinite(n))throw TypeError(`"${r}" claim must be a finite number`)}return ye.encode(JSON.stringify(t))}function Qe(e,t){return z(e)[t]}class te{constructor(e={}){if(!S(e))throw TypeError("JWT Claims Set MUST be an object");(yr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return At("iss",e),z(this).iss=e,this}setSubject(e){return At("sub",e),z(this).sub=e,this}setAudience(e){return Zr(e),z(this).aud=e,this}setJti(e){return At("jti",e),z(this).jti=e,this}setNotBefore(e){return z(this).nbf=xt(e,"setNotBefore"),this}setExpirationTime(e){return z(this).exp=xt(e,"setExpirationTime"),this}setIssuedAt(e){let t=z(this);if(e===void 0)t.iat=xe(new Date);else if(typeof e==="string")t.iat=ue("setIssuedAt",xe(new Date)+Ze(e));else t.iat=xt(e,"setIssuedAt");return this}}async function On(e,t,r){let n=await lr(e,ur(r),t);if(!n[2])throw new E("JWTs MUST NOT use unencoded payload");let a={payload:le(n[1],n[0],r),protectedHeader:n[1]};if(typeof t==="function")return{...a,key:n[3]};return a}async function gc(e,t,r){let n=await or(e,nr(r),t),o=n[1],a=le(o,n[0],r);for(let s of["iss","sub","aud"])if(o[s]!==void 0&&(s==="aud"?JSON.stringify(o.aud)!==JSON.stringify(a.aud):o[s]!==a[s]))throw new _(`replicated "${s}" claim header parameter mismatch`,a,s,"mismatch");let i={payload:a,protectedHeader:o};if(typeof t==="function")return{...i,key:n[2]};return i}function en(e){if(e===void 0)return[void 0,""];let t=pe(w,e);return[t[0],fr(t[1])]}function tn(e,t,r){return Xe(w,e),ce(e,N(w,se,r,e,t))}function rn(e){let t=e.alg;if(typeof t!=="string"||!t)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');return qe(t)}async function nn(e,t,r,n){let o=A(b(e),b("."),t),a=await U(r,n,"sign");return fr(await cr(r,a,o))}async function hr(e,t,r,n,o){let[a,i]=en(t);if(!a)throw new w("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tn(a,a,r))o();let c=rn(a),p=fr(e),d=await nn(i,b(p),c,n);return`${i}.${p}.${d}`}var on=te;class Ac extends on{#e;setProtectedHeader(e){return Q(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return hr(me(this),this.#e,t?.crit,e,()=>{throw new E("JWTs MUST NOT use unencoded payload")})}}var an=te;class _c extends an{#e;#r;#n;#t;#o;#i;#a;setProtectedHeader(e){return Q(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return Q(this.#n,"setKeyManagementParameters"),this.#n=e,this}setContentEncryptionKey(e){return Q(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return Q(this.#r,"setInitializationVector"),this.#r=e,this}replicateIssuerAsHeader(){return this.#o=!0,this}replicateSubjectAsHeader(){return this.#i=!0,this}replicateAudienceAsHeader(){return this.#a=!0,this}async encrypt(e,t){let r=me(this);if(this.#t&&(this.#o||this.#i||this.#a))this.#t={...this.#t,iss:this.#o?Qe(this,"iss"):void 0,sub:this.#i?Qe(this,"sub"):void 0,aud:this.#a?Qe(this,"aud"):void 0};let n=await ar([r,this.#t,void 0,void 0,void 0,this.#e,this.#r,this.#n,void 0,!1],e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}var Wt='"alg" (Algorithm)';function Ct(e='JWK "alg" (Algorithm) Parameter'){throw new m(`Invalid or unsupported ${e} value`)}function Ke(e,t){return(typeof e==="string"?Ae[e]??mt[e]:void 0)??Ct(t)}function et(e){if(e!==void 0&&typeof e!=="boolean")throw TypeError('"extractable" option must be a boolean');return e}var Je=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},sn=(e)=>({data:e,pos:0}),vt=(e)=>{let t=e.data[e.pos++];if(t===void 0)throw Error("Unexpected end of ASN.1 input");return t},We=(e)=>{let t=vt(e);if(t&128){let r=t&127,n=0;for(let o=0;o<r;o++)n=n<<8|vt(e);return n}return t};var Ce=(e,t,r)=>{if(vt(e)!==t)throw Error(r)},wr=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},cn=(e)=>{Ce(e,6,"Expected algorithm OID");let t=We(e);return wr(e,t)};function pn(e,t){if(Ce(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),We(e),t==="pkcs8"){Ce(e,2,"Expected version field");let r=We(e);e.pos+=r}Ce(e,48,"Expected algorithm identifier"),We(e)}var dn=(e)=>{let t=cn(e);if(Je(t,[43,101,110]))return"X25519";if(!Je(t,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");Ce(e,6,"Expected curve OID");let r=We(e),n=wr(e,r);if(Je(n,[42,134,72,206,61,3,1,7]))return"P-256";if(Je(n,[43,129,4,0,34]))return"P-384";if(Je(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")},fn=async(e,t,r,n)=>{let o=et(n?.extractable),a=Ke(r,Wt);if(a.secret)Ct(Wt);let i=e==="spki",s;if(a.resolve)try{let c=sn(t);pn(c,e),s=a.resolve({crv:dn(c)})}catch{throw new m("Invalid or unsupported key format")}else s=a.subtle;return crypto.subtle.importKey(e,t,s,o??i,a.usages[i?0:1])},un=(e,t)=>Be(e.replace(t,"")),gr=(e,t,r)=>{let n=un(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return fn("pkcs8",n,t,r)};function ln(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function mn(e){if(st(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:fr(e)};if(!M(e))throw TypeError(B(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=ln(await crypto.subtle.exportKey("jwk",e));if(a.kty==="AKP")a.alg=n;return a}function Er(e){return mn(e)}var V=(e,t)=>{if(typeof e!=="string"||!e)throw new _e(`${t} missing or invalid`)};async function yc(e,t){let r;if(S(e)){if(r=oe(e),typeof r.kty!=="string")throw TypeError(B(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(Re(e))r=oe(await Er(e));else throw TypeError(B(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 n;switch(r.kty){case"AKP":V(r.alg,'"alg" (Algorithm) Parameter'),V(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":V(r.crv,'"crv" (Curve) Parameter'),V(r.x,'"x" (X Coordinate) Parameter'),V(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":V(r.crv,'"crv" (Subtype of Key Pair) Parameter'),V(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":V(r.e,'"e" (Exponent) Parameter'),V(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!=="string")throw new _e('"k" (Key Value) Parameter missing or invalid');n={k:r.k,kty:r.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}let o=b(JSON.stringify(n));return fr(await $e(t,o))}function yn(e,t,r,n){let{kty:o,key_ops:a,ext:i,kid:s,alg:c,use:p,crv:d}=oe(e),u=Array.isArray(a)?[...a]:a;return(i===void 0||typeof i==="boolean")&&(u===void 0||Array.isArray(u)&&u.every((l,K)=>typeof l==="string"&&u.indexOf(l)===K)&&u.includes("verify"))&&t.kty.includes(o)&&(n===void 0||typeof n==="string"&&n===s)&&(c===void 0?o!=="AKP":r===c)&&(p===void 0||p==="sig")&&(!t.crv||d===t.crv)}async function br(e,t,r){let n=e.get(t)||e.set(t,{}).get(t),{alg:o}=r;if(n[o]===void 0){let a=await j(r,{...t,alg:o,ext:!0});if(a.type!=="public")throw new De("JSON Web Key Set members must be public keys");n[o]=a}return n[o]}function Su(e){let t;try{t=structuredClone(e)}catch{}if(!Me(t))throw new De("JSON Web Key Set malformed");let r=new WeakMap;return Object.defineProperty(async(o,a)=>{let{alg:i,kid:s}={...o,...a?.header},c=typeof i==="string"?Ae[i]:void 0;if(!c||c.secret)throw new m('Unsupported "alg" value for a JSON Web Key Set');let p=t.keys.filter((l)=>yn(l,c,i,s)),{0:d,length:u}=p;if(!u)throw new we;if(u!==1){let l=new ot;throw l[Symbol.asyncIterator]=async function*(){for(let K of p)try{yield await br(r,K,c)}catch{}},l}return br(r,d,c)},"jwks",{value:()=>structuredClone(t)})}function hn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var Tt;if(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))Tt="jose/v6.2.10";var Ar=Symbol();async function wn(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch((a)=>{if(a.name==="TimeoutError")throw new it;throw a});if(o.status!==200)throw new x("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new x("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var xr=Symbol();function ve(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Sr(e,t,r){if(Number.isNaN(e))throw TypeError(`"${r}" option must not be NaN`);return typeof e==="number"?e:t}function Eu(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let r=new URL(e.href).href,n=t??{},o=n.timeoutDuration;if(typeof o==="number"&&(!Number.isInteger(o)||o<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let a=typeof o==="number"?o:5000,i=Sr(n.cooldownDuration,30000,"cooldownDuration"),s=Sr(n.cacheMaxAge,600000,"cacheMaxAge"),c=new Headers(n.headers);if(Tt&&!c.has("User-Agent"))c.set("User-Agent",Tt);if(!c.has("accept"))c.set("accept","application/json, application/jwk-set+json");let p=n[Ar],d=n[xr],u,l,K=0,T=0,g;if(d&&typeof d==="object"){let{uat:y,jwks:J}=d;if(ve(y,s)&&Me(J))u=y,g=Su(J)}let h=async()=>{if(l&&hn())l=void 0;if(!l){let y=++K,J=l=wn(r,c,AbortSignal.timeout(a),p).then((P)=>{let H=Su(P);if(y<=T)return;g=H;let O=Date.now();if(d)d.uat=O,d.jwks=P;u=O,T=y}).finally(()=>{if(l===J)l=void 0})}await l};return Object.defineProperties(async(y,J)=>{if(!g||!ve(u,s))await h();try{return await g(y,J)}catch(P){if(P instanceof we&&!ve(u,i))return await h(),g(y,J);throw P}},{coolingDown:{get:()=>ve(u,i),enumerable:!0},fresh:{get:()=>ve(u,s),enumerable:!0},reload:{value:h,enumerable:!0},reloading:{get:()=>!!l,enumerable:!0},jwks:{value:()=>g?.jwks(),enumerable:!0}})}var gn=te;class Am extends gn{encode(){let e=fr(JSON.stringify({alg:"none"})),t=fr(me(this));return`${e}.${t}.`}static decode(e,t){if(typeof e!=="string")throw new E("Unsecured JWT must be a string");let{0:r,1:n,2:o,length:a}=e.split(".");if(a!==3||o!=="")throw new E("Invalid Unsecured JWT");let i,s;try{i=F(r,w,"JWS Protected Header is invalid");let p=N(w,se,void 0,i,i);s=ce(i,p)}catch(p){if(!(p instanceof w))throw p;throw new E("Invalid Unsecured JWT",{cause:p})}if(i.alg!=="none")throw new E("Invalid Unsecured JWT");if(!s)throw new E("JWTs MUST NOT use unencoded payload");return{payload:le(i,W(n,"payload",E),t),header:i}}}async function zA(e,t,r){if(typeof e!=="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw TypeError('"pkcs8" must be PKCS#8 formatted string');return gr(e,t,r)}async function ks(e,t,r){if(!S(e))throw TypeError("JWK must be an object");let n=Le(e),o=et(r?.extractable),{alg:a}=n;t??=a;let i=o??n.ext;if(n.kty!=="oct"&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(n.kty){case"oct":if(typeof n.k!=="string")throw TypeError('missing "k" (Key Value) Parameter value');return D(n.k);case"AKP":{if(typeof a!=="string"||!a)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==a)throw TypeError("JWK alg and alg option value mismatch");return j(Ke(t),{...n,ext:i})}case"RSA":case"EC":case"OKP":return j(Ke(t),{...n,alg:t,ext:i});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}function Ho(e){let t;if(typeof e==="string"){let n=e.split(".");if(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");let r="Invalid Token or Protected Header formatting";if(typeof t!=="string"||!t)throw TypeError(r);return F(t,TypeError,r)}function qr(e){if(typeof e!=="string")throw new E("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new E("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new E("Invalid JWT");if(!t)throw new E("JWTs must contain a payload");let n;try{n=D(t)}catch{throw new E("Failed to base64url decode the payload")}let o;try{o=JSON.parse(re.decode(n))}catch{throw new E("Failed to parse the decoded payload as JSON")}if(!S(o))throw new E("Invalid JWT Claims Set");return o}export{nl,fr,pf,On,gc,Ac,_c,yc,Su,Eu,Am,zA,ks,Ho,qr};
|