@npayload/sdk 0.0.0-stage → 5.0.5
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/LICENSE +21 -0
- package/README.md +160 -2
- package/dist/chunk-26BFOUGE.mjs +1 -0
- package/dist/chunk-2XQXDEXA.mjs +1 -0
- package/dist/chunk-455C67EN.mjs +1 -0
- package/dist/chunk-4NWQCPI4.mjs +1 -0
- package/dist/chunk-5KFQTEH3.mjs +1 -0
- package/dist/chunk-5SMWYS7Z.mjs +1 -0
- package/dist/chunk-5WGVEULS.mjs +3 -0
- package/dist/chunk-6BBB7BRP.mjs +1 -0
- package/dist/chunk-6HF3N3NR.mjs +1 -0
- package/dist/chunk-6ITUDSL7.mjs +17 -0
- package/dist/chunk-A7HA64P6.mjs +1 -0
- package/dist/chunk-APBVAT7F.mjs +1 -0
- package/dist/chunk-BBHWYMQA.mjs +1 -0
- package/dist/chunk-CJDCY2NH.mjs +1 -0
- package/dist/chunk-CNAIHF3M.mjs +1 -0
- package/dist/chunk-CWBN2DOO.mjs +1 -0
- package/dist/chunk-EXNCOEHS.mjs +1 -0
- package/dist/chunk-FAO3QJC5.mjs +1 -0
- package/dist/chunk-GEJT7NMK.mjs +1 -0
- package/dist/chunk-GGXNXM73.mjs +1 -0
- package/dist/chunk-HTQLUO4J.mjs +1 -0
- package/dist/chunk-I3UZ2FRE.mjs +1 -0
- package/dist/chunk-I7YPDC7V.mjs +2 -0
- package/dist/chunk-IK32U5FV.mjs +1 -0
- package/dist/chunk-JNYV4RW3.mjs +1 -0
- package/dist/chunk-JUXYOKI2.mjs +64 -0
- package/dist/chunk-K3SNPW2B.mjs +9 -0
- package/dist/chunk-KUJJYP3K.mjs +22 -0
- package/dist/chunk-LJNU5QHZ.mjs +1 -0
- package/dist/chunk-LVVHOJLW.mjs +5 -0
- package/dist/chunk-MDW42OG6.mjs +8 -0
- package/dist/chunk-MPYL6HQR.mjs +1 -0
- package/dist/chunk-MW4TLR2T.mjs +1 -0
- package/dist/chunk-O7HHWVMT.mjs +1 -0
- package/dist/chunk-OA73YMB6.mjs +6 -0
- package/dist/chunk-P5GCOROB.mjs +1 -0
- package/dist/chunk-PKG2R6XN.mjs +1 -0
- package/dist/chunk-PYLSDRRO.mjs +20 -0
- package/dist/chunk-QGH4LHSH.mjs +4 -0
- package/dist/chunk-QHGF2GC6.mjs +1 -0
- package/dist/chunk-SRQQNHSX.mjs +5 -0
- package/dist/chunk-TQFAYJEP.mjs +4 -0
- package/dist/chunk-UJP3Q23X.mjs +1 -0
- package/dist/chunk-UNDT7J2V.mjs +1 -0
- package/dist/chunk-X3VVI7V3.mjs +1 -0
- package/dist/chunk-XLK55DEY.mjs +1 -0
- package/dist/cli/index.d.mts +54 -0
- package/dist/cli/index.d.ts +54 -0
- package/dist/cli/index.js +854 -0
- package/dist/cli/index.mjs +698 -0
- package/dist/events/index.d.mts +10 -0
- package/dist/events/index.d.ts +10 -0
- package/dist/events/index.js +1 -0
- package/dist/events/index.mjs +1 -0
- package/dist/index.d.mts +49687 -0
- package/dist/index.d.ts +49687 -0
- package/dist/index.js +2 -0
- package/dist/index.mjs +2 -0
- package/package.json +120 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as i,G as c}from"./chunk-JUXYOKI2.mjs";import{a as e,b as n,c as t}from"./chunk-FAO3QJC5.mjs";import{a as o}from"./chunk-LJNU5QHZ.mjs";var a={events:e,pipes:n,primus:t};async function u(){let s=new Set;for(let[f,p]of Object.entries(a)){let r=i(f);if(!r)continue;let g=await c(r);for(let m of p(g))s.add(m)}return[...s].sort()}o(u,"projectAllPermissions");export{u as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-IK32U5FV.mjs";import"./chunk-SRQQNHSX.mjs";import"./chunk-MW4TLR2T.mjs";import"./chunk-JUXYOKI2.mjs";import"./chunk-TQFAYJEP.mjs";import"./chunk-4NWQCPI4.mjs";import"./chunk-FAO3QJC5.mjs";import"./chunk-455C67EN.mjs";import"./chunk-CJDCY2NH.mjs";import"./chunk-2XQXDEXA.mjs";import"./chunk-XLK55DEY.mjs";import"./chunk-LVVHOJLW.mjs";import"./chunk-I7YPDC7V.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-P5GCOROB.mjs";import"./chunk-UJP3Q23X.mjs";import"./chunk-QGH4LHSH.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as computeFloor,c as coversFloor,b as floorGap};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{a as r}from"./chunk-LJNU5QHZ.mjs";import{homedir as p}from"os";import{join as u}from"path";var i="npayload",w="default",f=process.env.NPAYLOAD_AUTH_HOME??u(p(),".npayload"),S=u(f,"credentials.json"),s=class extends Error{static{r(this,"KeychainUnavailableError")}cause;constructor(t){super(`The npayload CLI stores credentials in the OS keychain (macOS Keychain / Windows Credential Manager / Linux Secret Service), and it is not reachable here.
|
|
2
|
+
\u2022 On a desktop session: install/start a Secret Service (e.g. \`gnome-keyring\` or KWallet on Linux).
|
|
3
|
+
\u2022 Headless / CI / container: authenticate without a keychain by exporting machine credentials \u2014
|
|
4
|
+
export NPAYLOAD_CLIENT_ID=... NPAYLOAD_CLIENT_SECRET=... (or NPAYLOAD_TOKEN=<short-lived token>)
|
|
5
|
+
\u2022 Run \`npayload doctor\` to see exactly what is available on this host.
|
|
6
|
+
Plaintext credential files are intentionally NOT supported.`),this.name="KeychainUnavailableError",this.cause=t}};function l(e){return(e instanceof Error?e.message:String(e)).toLowerCase().includes("no matching entry")}r(l,"isNoEntryError");var c=null,y=null;async function m(){let e=await import("@napi-rs/keyring"),t=e.default??e;if(typeof t.AsyncEntry!="function")throw new Error("@napi-rs/keyring did not load an Entry class");return t}r(m,"loadRealKeyring");function P(e){return{async getPassword(t,n){try{return await new e.AsyncEntry(t,n).getPassword()??null}catch(a){if(l(a))return null;throw new s(a)}},async setPassword(t,n,a){try{await new e.AsyncEntry(t,n).setPassword(a)}catch(g){throw new s(g)}},async deletePassword(t,n){try{return await new e.AsyncEntry(t,n).deleteCredential()}catch(a){if(l(a))return!1;throw new s(a)}},async findCredentials(t){try{return await e.findCredentialsAsync(t)}catch(n){if(l(n))return[];throw new s(n)}}}}r(P,"adaptKeyring");async function o(){if(c)return c;let e;try{e=y?await y():await m()}catch(t){throw t instanceof s?t:new s(t)}return c=P(e),c}r(o,"loadKeytar");async function A(){try{return await(await o()).getPassword(i,"__probe__"),!0}catch{return!1}}r(A,"keychainAvailable");async function E(e=w){let n=await(await o()).getPassword(i,e);if(!n)return null;try{return JSON.parse(n)}catch{return null}}r(E,"getStoredCredentials");var d="__management__";async function N(e){await(await o()).setPassword(i,d,JSON.stringify({...e,storedAt:e.storedAt||Date.now()}))}r(N,"saveManagementSession");async function v(){let t=await(await o()).getPassword(i,d);if(!t)return null;try{return JSON.parse(t)}catch{return null}}r(v,"getManagementSession");async function K(){await(await o()).deletePassword(i,d)}r(K,"clearManagementSession");export{s as a,A as b,E as c,N as d,v as e,K as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{T as t,U as f}from"./chunk-QGH4LHSH.mjs";import{a as s}from"./chunk-LJNU5QHZ.mjs";function l(e){let r=f(e.edge),a=r!==void 0,n=r??(e.npp&&e.guard.production?t:void 0);if(n===void 0&&!e.npp)return{named:!1};for(let d of e.provisioning??[]){let i=e.guard.refusal(d);if(i!==void 0)return{named:a,refusal:i}}if(n===void 0){let d=e.guard.noEdge();return d===void 0?{named:!1}:{named:!1,refusal:d}}let o=e.guard.refusal(n);return o===void 0?{edgeUrl:n,named:a}:{named:a,refusal:o}}s(l,"resolveEdge");export{l as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-LJNU5QHZ.mjs";var n=class a{static{i(this,"UndiciStreamWrapper")}readableStream;reader;events;paused;resumeCallback;encoding;constructor(e){this.readableStream=e,this.reader=this.readableStream.getReader(),this.events={data:[],end:[],error:[],readable:[],close:[],pause:[],resume:[]},this.paused=!1,this.resumeCallback=null,this.encoding=null}on(e,r){this.events[e]?.push(r)}off(e,r){this.events[e]=this.events[e]?.filter(t=>t!==r)}pipe(e){return this.on("data",r=>{if(e instanceof a)e._write(r);else{let t=e.getWriter();t.write(r).then(()=>t.releaseLock())}}),this.on("end",()=>{e instanceof a?e._end():e.getWriter().close()}),this.on("error",r=>{e instanceof a?e._error(r):e.getWriter().abort(r)}),this._startReading(),e}pipeTo(e){return this.pipe(e)}unpipe(e){this.off("data",r=>{if(e instanceof a)e._write(r);else{let t=e.getWriter();t.write(r).then(()=>t.releaseLock())}}),this.off("end",()=>{e instanceof a?e._end():e.getWriter().close()}),this.off("error",r=>{e instanceof a?e._error(r):e.getWriter().abort(r)})}destroy(e){this.reader.cancel(e).then(()=>{this._emit("close")}).catch(r=>{this._emit("error",r)})}pause(){this.paused=!0,this._emit("pause")}resume(){this.paused&&(this.paused=!1,this._emit("resume"),this.resumeCallback&&(this.resumeCallback(),this.resumeCallback=null))}get isPaused(){return this.paused}async read(){this.paused&&await new Promise(t=>{this.resumeCallback=t});let{done:e,value:r}=await this.reader.read();if(!e)return r}setEncoding(e){this.encoding=e}async text(){let e=[];for(;;){let{done:t,value:s}=await this.reader.read();if(t)break;s&&e.push(s)}return new TextDecoder(this.encoding||"utf-8").decode(await new Blob(e).arrayBuffer())}async json(){let e=await this.text();return JSON.parse(e)}_write(e){this._emit("data",e)}_end(){this._emit("end")}_error(e){this._emit("error",e)}_emit(e,r){if(this.events[e])for(let t of this.events[e]||[])t(r)}async _startReading(){try{for(this._emit("readable");;){this.paused&&await new Promise(t=>{this.resumeCallback=t});let{done:e,value:r}=await this.reader.read();if(e){this._emit("end"),this._emit("close");break}r&&this._emit("data",r)}}catch(e){this._emit("error",e)}}[Symbol.asyncIterator](){return{next:i(async()=>{this.paused&&await new Promise(t=>{this.resumeCallback=t});let{done:e,value:r}=await this.reader.read();return e?{done:!0,value:void 0}:{done:!1,value:r}},"next"),[Symbol.asyncIterator](){return this}}}};export{n as UndiciStreamWrapper};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{b as P,c as R}from"./chunk-MDW42OG6.mjs";import{a as b}from"./chunk-UNDT7J2V.mjs";import{a as y,b as G}from"./chunk-IK32U5FV.mjs";import{g as x,k as g,l as h,o as m,p as w}from"./chunk-JUXYOKI2.mjs";import{f as S}from"./chunk-LVVHOJLW.mjs";import{a as c}from"./chunk-LJNU5QHZ.mjs";import{readFileSync as _,writeFileSync as D}from"fs";import a from"chalk";import{existsSync as u,readFileSync as $,watch as j}from"fs";import{resolve as C,join as d}from"path";function L(o){if(o){let e=C(process.cwd(),o);return u(e)?[e]:[]}let t=[];for(let e of["events","primus","pipes"])for(let n of[d("npayload",`${e}.config.ts`),`${e}.config.ts`]){let r=d(process.cwd(),n);u(r)&&t.push(r)}return t}c(L,"findAllConfigs");function I(o,t){if(u(o))try{for(let e of $(o,"utf8").split(`
|
|
2
|
+
`)){let n=e.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(!(r===-1||n.slice(0,r).trim()!==t))return n.slice(r+1).trim().replace(/^["']|["']$/g,"")}}catch{}}c(I,"readEnvVar");function v(o){if(o)return o;let t=process.env.NPAYLOAD_APP_ID?.trim();if(t)return t;for(let e of[d(process.cwd(),".env"),d(process.cwd(),"npayload",".env")]){let n=I(e,"NPAYLOAD_APP_ID");if(n)return n}for(let e=process.cwd(),n=0;n<5;n++){let r=d(e,".npayload.json");if(u(r))try{let i=JSON.parse($(r,"utf8"));if(typeof i.appId=="string"&&i.appId.trim())return i.appId.trim()}catch{}let s=d(e,"..");if(s===e)break;e=s}}c(v,"resolveAppGid");function M(o,t,e=300,n){let r=null,s=c(()=>{r&&clearTimeout(r),r=setTimeout(()=>void t("change"),e)},"bump"),i=o.map(p=>j(p,s)),f=new Promise(p=>{process.on("SIGINT",()=>p())});return n===void 0?f:Promise.race([f,n.ended]).catch(p=>{r&&clearTimeout(r);for(let l of i)l.close();throw p})}c(M,"watchConfigs");function k(o,t){return{...o!==void 0?{cwd:o}:{},components:t}}c(k,"floorOptions");function A(o,t){let e=x(o);e.length!==0&&t?.(a.dim(` (declared component(s) not embeddable \u2014 they contribute no scope: ${e.join(", ")})
|
|
3
|
+
`))}c(A,"reportInertComponents");async function F(o={}){let t=m(o.cwd),e=t?.path??w(o.cwd);if(!t||!e)throw new Error("no npayload.toml found \u2014 `np scopes fix` needs a manifest with an [access_scopes] block.");h(t.accessScopes);let n=o.floor??await y(k(o.cwd,t.embedComponents));A(t.embedComponents,o.log);let r=G(t.accessScopes,n),s=r.filter(l=>g(l)),i=r.filter(l=>!g(l));if(i.length>0&&o.log?.(a.dim(` (skipped ${i.length} non-catalog projection scope(s) \u2014 not declarable in [access_scopes]: ${i.join(", ")})
|
|
4
|
+
`)),s.length===0)return o.log?.(a.dim(` [access_scopes] already covers the projected floor \u2014 nothing to add.
|
|
5
|
+
`)),{appended:[],path:e,covered:!0};let f=_(e,"utf8"),p=R(f,t.accessScopes,s);return D(e,p,"utf8"),o.log?.(a.green(`\u2713 appended ${s.length} floor scope(s) to [access_scopes]:
|
|
6
|
+
${s.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`)),{appended:s,path:e,covered:!0}}c(F,"runScopesFix");async function T(o={}){let t=m(o.cwd);if(!t)throw new Error("no npayload.toml found \u2014 `np scopes diff` needs a manifest with an [access_scopes] block.");h(t.accessScopes);let e=o.floor??await y(k(o.cwd,t.embedComponents)),n=o.appGid??v(),r=null;o.readRemoteGrant&&n&&(r=await o.readRemoteGrant(n));let s=b({declared:t.accessScopes,floor:e,remote:r??{scopes:[],configDrift:!1}}),i=o.log??(f=>process.stdout.write(f));switch(A(t.embedComponents,i),s.kind){case"floor-gap":i(a.yellow(`\u2717 [access_scopes] is missing ${s.gap.length} floor scope(s):
|
|
9
|
+
${s.gap.join(`
|
|
10
|
+
`)}
|
|
11
|
+
`)),i(a.dim(" run `npayload scopes fix` to add them.\n"));break;case"conflict":i(a.yellow(`\u2717 remote grant has drifted from the manifest:
|
|
12
|
+
`)),i(a.dim(` manifest : ${s.diff.manifest.join(", ")||"(none)"}
|
|
13
|
+
`)),i(a.dim(` remote : ${s.diff.remote.join(", ")||"(none)"}
|
|
14
|
+
`)),i(a.dim(` resolve on push with --accept-remote or --overwrite-remote.
|
|
15
|
+
`));break;case"sync":i(a.green(`\u2713 [access_scopes] covers the floor and matches the remote grant (${s.grant.length} scope(s)).
|
|
16
|
+
`));break;case"accept-remote":i(a.green(`\u2713 resolvable via --accept-remote.
|
|
17
|
+
`));break}return s}c(T,"runScopesDiff");async function Z(o){let t=m(o.cwd),e=t?.path??w(o.cwd);if(!t||!e)return null;let n=o.appGid??v();if(!n)return null;let r=await o.readRemoteGrant(n);if(!r)return null;let s=[...new Set(r.scopes)].sort(),i=P(_(e,"utf8"),s);return D(e,i,"utf8"),o.log?.(a.green(`\u2713 pulled ${s.length} scope(s) from the remote grant into [access_scopes].
|
|
18
|
+
`)),{written:s,path:e}}c(Z,"pullScopesIntoManifest");async function E(o){let{restoreSession:t}=await import("./chunk-I3UZ2FRE.mjs"),e=await t();return e?e.getOacGrant(o):null}c(E,"sessionGrantReader");function ee(o){let t=o.command("scopes").description("Scopes-as-code: inspect and reconcile the manifest's [access_scopes] against the floor + the remote grant");t.command("diff").description("Show the floor gap + manifest\u21C4remote drift for [access_scopes]. Exit 0 in sync, 2 with a gap/conflict, 1 on error.").action(async()=>{try{let e=await T({readRemoteGrant:E});process.exit(e.kind==="sync"||e.kind==="accept-remote"?0:2)}catch(e){process.stderr.write(a.red(`${S(`scopes diff failed: ${e instanceof Error?e.message:String(e)}`,e)}
|
|
19
|
+
`)),process.exit(1)}}),t.command("fix").description("Append exactly the projected-floor gap to the manifest's [access_scopes] (idempotent)").action(async()=>{try{await F({log:c(e=>process.stdout.write(e),"log")}),process.exit(0)}catch(e){process.stderr.write(a.red(`scopes fix failed: ${e instanceof Error?e.message:String(e)}
|
|
20
|
+
`)),process.exit(1)}})}c(ee,"registerScopes");export{L as a,v as b,M as c,F as d,T as e,Z as f,ee as g};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{f as Gn,g as jn,h as Jn}from"./chunk-GGXNXM73.mjs";import{a as i}from"./chunk-LJNU5QHZ.mjs";import{webcrypto as G}from"crypto";import{inspect as os}from"util";var Wt="[REDACTED_DPOP_PRIVATE_JWK]",Ue=class{static{i(this,"DpopPrivateJwk")}#e;constructor(e){if(!e||typeof e!="object")throw new TypeError("DpopPrivateJwk requires a JsonWebKey");if(e.kty!=="EC"||e.crv!=="P-256")throw new TypeError(`DpopPrivateJwk requires kty=EC, crv=P-256 (got kty=${e.kty}, crv=${e.crv})`);if(typeof e.d!="string"||e.d.length===0)throw new TypeError("DpopPrivateJwk requires the private `d` field");this.#e=e}get publicJwk(){let{d:e,...n}=this.#e;return n}get crv(){return this.#e.crv}unsafeUse(e){return e(this.#e)}toJSON(){return Wt}[os.custom](){return Wt}toString(){return Wt}};function rt(t){return t instanceof Ue}i(rt,"isDpopPrivateJwk");var Gt=new TextEncoder;function ot(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return Buffer.from(n,"binary").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}i(ot,"b64url");function Yn(t){return Buffer.from(t,"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}i(Yn,"b64urlFromString");async function ss(t){let e=await G.subtle.digest("SHA-256",Gt.encode(t));return ot(e)}i(ss,"sha256B64Url");async function wc(){let t=await G.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),e=await G.subtle.exportKey("jwk",t.publicKey),n=await G.subtle.exportKey("jwk",t.privateKey);return{publicJwk:e,privateJwk:n}}i(wc,"generateDpopKeyPair");function is(t){let e={EC:["kty","crv","x","y"],RSA:["kty","n","e"],OKP:["kty","crv","x"]},n=t,r=typeof t.kty=="string"?e[t.kty]:void 0;if(r){let f={};for(let l of r)n[l]!==void 0&&(f[l]=n[l]);return f}let{d:o,key_ops:s,ext:c,use:a,alg:u,...d}=n;return d}i(is,"publicHalf");async function Qn(t){let e=t,n={EC:["crv","kty","x","y"],RSA:["e","kty","n"],OKP:["crv","kty","x"]},r=typeof e.kty=="string"?e.kty:"",o=n[r];if(!o)throw new TypeError(`jwkThumbprint: unsupported key type ${JSON.stringify(e.kty)}`);let s={};for(let a of o){if(typeof e[a]!="string"||e[a].length===0)throw new TypeError(`jwkThumbprint: the ${r} key carries no "${a}" member`);s[a]=e[a]}let c=await G.subtle.digest("SHA-256",Gt.encode(JSON.stringify(s)));return ot(c)}i(Qn,"jwkThumbprint");function as(t){if(t)return t();let e=G.getRandomValues(new Uint8Array(16));return ot(e)}i(as,"newJti");function cs(t){try{let e=new URL(t);return e.hash="",e.search="",e.toString()}catch{return t}}i(cs,"canonicalHtu");async function jt(t,e){let n=e.now?Math.floor(e.now()/1e3):Math.floor(Date.now()/1e3),r={typ:"dpop+jwt",alg:"ES256",jwk:is(t.publicJwk)},o={htm:e.method.toUpperCase(),htu:cs(e.url),iat:n,jti:as(e.randomJti)};e.accessToken&&(o.ath=await ss(e.accessToken)),e.nonce&&(o.nonce=e.nonce);let s=Yn(JSON.stringify(r)),c=Yn(JSON.stringify(o)),a=`${s}.${c}`,u=await us(t.privateJwk),d=await G.subtle.sign({name:"ECDSA",hash:"SHA-256"},u,Gt.encode(a));return`${a}.${ot(d)}`}i(jt,"signDpopProof");var Xn=new WeakMap;async function us(t){if(rt(t)){let e=Xn.get(t);if(e)return e;let n=await t.unsafeUse(r=>G.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]));return Xn.set(t,n),n}return G.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}i(us,"resolveSigningKey");var S=class extends Error{static{i(this,"NPayloadError")}code;requestId;status;constructor(e,n){super(e),this.name=this.constructor.name,this.code=n.code,this.requestId=n.requestId,this.status=n.status}isRetryable(){return this.status==null?!1:this.status===408||this.status===429?!0:this.status>=500&&this.status<600}},z=class extends S{static{i(this,"AuthError")}},me=class extends S{static{i(this,"AuthScopeError")}isRetryable(){return!1}},ke=class extends S{static{i(this,"NotFoundError")}isRetryable(){return!1}},Z=class extends S{static{i(this,"ValidationError")}details;constructor(e,n){super(e,n),this.details=n.details}isRetryable(){return!1}},st=class extends S{static{i(this,"RateLimitedError")}retryAfterMs;constructor(e,n){super(e,n),this.retryAfterMs=n.retryAfterMs}isRetryable(){return!0}},it=class extends S{static{i(this,"ConflictError")}isRetryable(){return!1}},at=class extends S{static{i(this,"ServerError")}isRetryable(){return!0}},fe=class extends S{static{i(this,"NetworkError")}isRetryable(){return!0}},le=class extends S{static{i(this,"TimeoutError")}isRetryable(){return!0}},ct=class extends S{static{i(this,"PlanRequiredError")}product;upgradeUrl;constructor(e,n){super(e,{code:n.code,status:402,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.product=n.product,this.upgradeUrl=n.upgradeUrl}isRetryable(){return!1}},ds=["source_network_not_allowed","source_network_not_declared"],fs=["thumbprint_not_bound"];function ft(t){return typeof t=="string"&&ds.includes(t.toLowerCase())}i(ft,"isSourceNotAllowedCode");function lt(t){return typeof t=="string"&&fs.includes(t.toLowerCase())}i(lt,"isFingerprintNotEnrolledCode");function te(t){if(t===null||typeof t!="object")return;let e=t,n=e.error!==null&&typeof e.error=="object"?e.error:void 0;for(let r of[n?.code,e.code,typeof e.error=="string"?e.error:void 0,e.reason])if(ft(r)||lt(r))return r}i(te,"networkRuleCodeOf");var ee=class extends S{static{i(this,"SourceNotAllowedError")}reason;constructor(e,n){super(e,{code:n.code,status:n.status??403,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.reason=n.code.toLowerCase()==="source_network_not_declared"?"not_declared":"not_allowed"}isRetryable(){return!1}},V=class extends S{static{i(this,"FingerprintNotEnrolledError")}fingerprint;constructor(e,n){super(e,{code:n.code,status:n.status??403,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.fingerprint=n.fingerprint}isRetryable(){return!1}},zn="npayload refused this call: it came from a network this app environment does not allow. An administrator can add the network in the dashboard under Settings > Security > Networks.",Zn="npayload refused this call: this app environment has no network yet, so its keys cannot be used. An administrator can add one in the dashboard under Settings > Security > Networks.",er="npayload refused this call: this instance's key fingerprint is not enrolled for this API key. An administrator can open the key's enrollment window in the dashboard under Developers > API keys, then start this instance again.",ut=class extends S{static{i(this,"CircuitOpenError")}isRetryable(){return!1}};var dt=class extends S{static{i(this,"ClockDriftError")}driftMs;maxDriftMs;constructor(e,n){let r=Math.round(Math.abs(e)/1e3);super(`local clock is ${r} s ${e>0?"behind":"ahead of"} the server (allowed skew ${Math.round(n/1e3)} s) \u2014 authenticated requests are refused until the clock is corrected`,{code:"clock_drift"}),this.driftMs=e,this.maxDriftMs=n}};function pt(t){let{status:e,body:n,headers:r}=t,o=r.get("x-request-id")??r.get("x-npayload-request-id")??ps(n)??void 0,s=typeof n=="object"&&n!==null?n:null,c=Re(ls(s)??hs(e)),a=Re(Xt(s)??Es(e)),u={code:c,status:e,...o!==void 0?{requestId:o}:{}};if(e===402||c==="PLAN_REQUIRED"){let f=Jt(s),l=Yt(f?.product),m=Yt(f?.upgradePath)??Yt(f?.upgradeUrl);return new ct(a,{code:c,...o!==void 0?{requestId:o}:{},...l!==void 0?{product:l}:{},...m!==void 0?{upgradeUrl:m}:{}})}let d=ft(c)||lt(c)?c:te(s);if(d!==void 0&&ft(d)){let f=d.toLowerCase()==="source_network_not_declared";return new ee(Re(Xt(s)??(f?Zn:zn)),{code:d,status:e,...o!==void 0?{requestId:o}:{}})}if(d!==void 0&<(d))return new V(Re(Xt(s)??er),{code:d,status:e,...o!==void 0?{requestId:o}:{}});switch(e){case 400:case 422:{let f=Jt(s);return new Z(a,{...u,...f!==void 0?{details:f}:{}})}case 401:return new z(a,u);case 403:{let f=Jt(s)?.reason;return c.toLowerCase().includes("scope")||typeof f=="string"&&f.toLowerCase().includes("scope")?new me(a,u):new z(a,u)}case 404:return new ke(a,u);case 409:return new it(a,u);case 429:{let f=gs(r,s);return new st(a,{...u,...f!==void 0?{retryAfterMs:f}:{}})}default:return e>=500&&e<600?new at(a,u):new S(a,u)}}i(pt,"errorFromResponse");function tr(t){if(t instanceof S)return t;if(t instanceof Error){let e=t.name;return e==="AbortError"?new le("Request aborted (timeout)",{code:"request_timeout"}):e==="TimeoutError"?new le("Request timed out",{code:"request_timeout"}):e==="TypeError"?new fe(`Network error: ${Re(t.message)}`,{code:"network_error"}):new fe(Re(t.message),{code:"network_error"})}return new fe("Unknown network error",{code:"network_error"})}i(tr,"errorFromException");function Pe(t){return t&&typeof t.error=="object"&&t.error!==null?t.error:void 0}i(Pe,"nestedError");function ls(t){if(!t)return null;let e=Pe(t);return e?.code?e.code:t.code?t.code:null}i(ls,"envelopeCode");function Jt(t){if(!t)return;let e=Pe(t)?.details;if(e&&typeof e=="object")return e;if(t.details&&typeof t.details=="object")return t.details}i(Jt,"envelopeDetails");function Yt(t){return typeof t=="string"&&t.length>0?t:void 0}i(Yt,"nonEmptyString");function Xt(t){if(!t)return null;let e=Pe(t);return e?.message?e.message:t.message?t.message:t.error_description?t.error_description:null}i(Xt,"envelopeMessage");function ps(t){if(typeof t!="object"||t===null)return;let e=Pe(t);return e?.request_id??e?.requestId??t.request_id??t.requestId}i(ps,"extractRequestId");function hs(t){switch(t){case 400:case 422:return"validation_error";case 401:return"unauthorized";case 402:return"payment_required";case 403:return"forbidden";case 404:return"not_found";case 409:return"conflict";case 429:return"rate_limited";default:return t>=500?"server_error":"request_failed"}}i(hs,"defaultCodeForStatus");function Es(t){return`Request failed with status ${t}`}i(Es,"defaultMessageForStatus");function gs(t,e){let n=t.get("retry-after");if(n){let s=Number(n);if(!Number.isNaN(s)&&s>=0)return Math.round(s*1e3);let c=Date.parse(n);if(!Number.isNaN(c)){let a=c-Date.now();if(a>0)return a}}let r=Pe(e),o=r?.retry_after_ms??r?.retryAfterMs??void 0;return typeof o=="number"&&o>=0?o:void 0}i(gs,"parseRetryAfterMs");function Re(t){return t.replace(/\bBearer\s+[A-Za-z0-9._-]+/gi,"Bearer [REDACTED]").replace(/\bDPoP\s+[A-Za-z0-9._-]+/gi,"DPoP [REDACTED]").replace(/\bBasic\s+[A-Za-z0-9+/=._-]+/gi,"Basic [REDACTED]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/g,"[JWT_REDACTED]").replace(/(\b(?:Set-)?Cookie:\s*)[^;\r\n]+/gi,"$1[REDACTED]").replace(/("d"\s*:\s*")[^"]+(")/g,"$1[REDACTED]$2").replace(/(["']?(?:hmac|secret|token|api[_-]?key|auth[_-]?token|private[_-]?key|key)["']?\s*[:=]\s*["'])[^"']+(["'])/gi,"$1[REDACTED]$2").replace(/\b([A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PWD)[A-Z0-9_]*)=\S+/g,"$1=[REDACTED]")}i(Re,"redactSecretLike");var nr=3e4,Et=class{static{i(this,"KernelAuthState")}config;fetchImpl;now;cache=null;inflight=new Map;nonces=new Map;fingerprintPromise;constructor(e){this.config=e,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now}async getAccessToken(e){let n=this.config.refreshMarginMs??nr,r=this.cache;if(r&&r.expiresAt-this.now()>n&&ht(r.scopes,e))return Qt(r);let o=ys(e),s=this.inflight.get(o);if(s)return Qt(await s);let c=this.fetchToken(e);this.inflight.set(o,c);try{let a=await c;return Qt(a)}finally{this.inflight.get(o)===c&&this.inflight.delete(o)}}async signDpopProof(e){let n=ws(e.url),r=n?this.nonces.get(n):void 0,o={method:e.method,url:e.url,...e.accessToken?{accessToken:e.accessToken}:{},...r?{nonce:r}:{},now:this.now};return jt(this.config.keys,o)}async requireScope(e){let n=await this.getAccessToken([e]);if(!ht(n.scopes,[e]))throw new me(`Missing required scope: ${e}. Granted: ${n.scopes.join(",")}`,{code:"insufficient_scope",status:403})}cacheNonce(e,n){this.nonces.set(e,n)}peekCache(){return this.cache}invalidate(){this.cache=null}fingerprint(){return this.fingerprintPromise||(this.fingerprintPromise=Qn(this.config.keys.publicJwk).catch(e=>{throw this.fingerprintPromise=void 0,e})),this.fingerprintPromise}async fetchToken(e){let n=this.config.authServerUrl,r=await jt(this.config.keys,{method:"POST",url:n,now:this.now}),o=new URLSearchParams({grant_type:"client_credentials",client_id:this.config.clientId,scope:e.join(" ")});this.config.appId&&o.set("app_id",this.config.appId),this.config.env&&o.set("env_id",this.config.env),this.config.clientSecret&&o.set("client_secret",this.config.clientSecret);let s=await this.fetchImpl(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",DPoP:r},body:o.toString()});if(!s.ok){let w={};try{w=await s.json()}catch{}let R=typeof w.error=="object"&&w.error!==null?w.error:void 0,C=typeof w.error=="string"?w.error:void 0;if(te(w)!==void 0){let b=pt({status:s.status,body:w,headers:s.headers??new Headers});if(b instanceof V){let O=await this.fingerprint().catch(()=>{});throw new V(b.message,{code:b.code,...b.status!==void 0?{status:b.status}:{},...b.requestId!==void 0?{requestId:b.requestId}:{},...O!==void 0?{fingerprint:O}:{}})}if(b instanceof ee)throw b}throw new z(w.error_description??C??R?.message??`OAuth token request failed (${s.status})`,{code:C??R?.code??"oauth_failed",status:s.status})}let c=await s.json();if(!c.access_token)throw new z("OAuth token response missing access_token",{code:"oauth_missing_token"});if(c.token_type&&c.token_type.toLowerCase()!=="dpop")throw new S(`Refusing non-DPoP token (got ${c.token_type})`,{code:"non_dpop_token"});let a=this.now()+(c.expires_in??600)*1e3,u=c.scope?c.scope.split(/\s+/).filter(Boolean):Array.from(e),d={token:c.access_token,expiresAt:a,scopes:u},f=this.cache,l=this.config.refreshMarginMs??nr;return f&&f.expiresAt-this.now()>l&&!ht(d.scopes,f.scopes)||(this.cache=d),d}};function Qt(t){return{token:t.token,tokenType:"DPoP",expiresAt:t.expiresAt,scopes:t.scopes}}i(Qt,"toAccessToken");function Oc(t,e){return ht(t,[e])}i(Oc,"scopesCover");function ht(t,e){return t.includes("*")?!0:e.every(n=>Gn(t,n)||Jn(t,n)||jn(t,n))}i(ht,"hasAllScopes");function ws(t){try{return new URL(t).origin}catch{return null}}i(ws,"safeOrigin");function ys(t){return[...t].sort().join(" ")}i(ys,"scopeKey");var ms="NPAYLOAD_TEST_RESTART_WINDOW_MS";function or(t=globalThis.process?.env){if(!t||t.VITEST!=="true")return;let e=t[ms];if(e===void 0||e==="")return;let n=Number(e);return Number.isFinite(n)&&n>=0?n:void 0}i(or,"harnessRestartWindowMs");function rr(t,e,n){let r=0;for(let o=0;o<e;o++){let s=Math.min(o,8);r+=gt(Math.round(t*2**s*.8),0,n)}return r}i(rr,"lowestScheduleSum");function sr(t,e,n=3e4){let r=Math.max(0,t-1);if(r===0||e<=0)return 200;let o=Math.ceil(n/.8);if(rr(o,r,n)<e)return o;let s=1,c=o;for(;s<c;){let a=Math.floor((s+c)/2);rr(a,r,n)>=e?c=a:s=a+1}return s}i(sr,"baseDelayForWindow");var ir=new Set([408,425,429,500,502,503,504]);function wt(t){let e=t.maxAttempts??5,n=t.attempt,r=t.status,o=t.jitter??Math.random,s=t.now??Date.now;if(n>=e)return{retryable:!1,delayMs:0,attempt:n,reason:`max attempts reached (${e})`};if(r!==void 0&&!ir.has(r)&&!(r>=500&&r<600))return{retryable:!1,delayMs:0,attempt:n,reason:`non-retryable status ${r}`};let c=Rs(t.retryAfterHeader,s);if(c!==void 0)return{retryable:!0,delayMs:gt(c,0,3e4),attempt:n,reason:"retry-after header"};if(t.retryAfterMs!==void 0&&t.retryAfterMs>=0)return{retryable:!0,delayMs:gt(t.retryAfterMs,0,3e4),attempt:n,reason:"retry-after envelope"};let u=(t.restartWindowMs!==void 0?sr(e,t.restartWindowMs):200)*2**Math.min(n-1,8),d=1+(o()*.4-.2),f=gt(Math.round(u*d),0,3e4),l=r!==void 0?`status ${r}`:"transport error";return{retryable:!0,delayMs:f,attempt:n,reason:`${l} (backoff)`}}i(wt,"defaultRetryPolicy");function Rs(t,e){if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(t);if(!Number.isNaN(r)){let o=r-e();return o>0?o:0}}i(Rs,"parseRetryAfter");function gt(t,e,n){return Math.max(e,Math.min(n,t))}i(gt,"clamp");function zt(t){return ir.has(t)||t>=500&&t<600}i(zt,"isRetryableStatus");var bs=5,Ls=3e4,pe=class{static{i(this,"KernelCircuitBreaker")}hosts=new Map;threshold;probeAfterMs;now;openHandlers=new Set;closeHandlers=new Set;deferUntil=new Map;constructor(e={}){this.threshold=e.failureThreshold??bs,this.probeAfterMs=e.probeAfterMs??Ls,this.now=e.now??Date.now}shouldAllow(e){let n=this.get(e);if(n.state==="closed")return!0;if(n.state==="open"){let r=n.openedAt??this.now();return this.now()-r>=this.probeAfterMs?(n.state="half-open",n.probeInFlight=!0,!0):!1}return n.probeInFlight?!1:(n.probeInFlight=!0,!0)}onOpen(e){return this.openHandlers.add(e),()=>{this.openHandlers.delete(e)}}onClose(e){return this.closeHandlers.add(e),()=>{this.closeHandlers.delete(e)}}noteRateLimit(e,n){this.deferUntil.set(e,n)}rateLimitedUntil(e){let n=this.deferUntil.get(e);if(n!==void 0){if(n<=this.now()){this.deferUntil.delete(e);return}return n}}fire(e,n){for(let r of e)try{r(n)}catch{}}recordSuccess(e){let n=this.get(e),r=n.state!=="closed";n.state="closed",n.failures=0,delete n.openedAt,delete n.lastFailureAt,n.probeInFlight=!1,r&&this.fire(this.closeHandlers,e)}recordFailure(e,n){let r=this.get(e);if(r.probeInFlight=!1,n===void 0||n>=500){if(r.lastFailureAt=this.now(),r.state==="half-open"){r.state="open",r.openedAt=this.now(),this.fire(this.openHandlers,e);return}r.failures+=1,r.failures>=this.threshold&&(r.state="open",r.openedAt=this.now(),this.fire(this.openHandlers,e))}}state(e){let n=this.get(e),r={state:n.state,failures:n.failures};return n.openedAt!==void 0&&n.lastFailureAt!==void 0?{...r,openedAt:n.openedAt,lastFailureAt:n.lastFailureAt}:n.openedAt!==void 0?{...r,openedAt:n.openedAt}:n.lastFailureAt!==void 0?{...r,lastFailureAt:n.lastFailureAt}:r}guard(e){if(!this.shouldAllow(e))throw new ut(`Circuit open for ${e}`,{code:"circuit_open"})}get(e){let n=this.hosts.get(e);return n||(n={state:"closed",failures:0,probeInFlight:!1},this.hosts.set(e,n)),n}};import{randomBytes as _s}from"crypto";function he(t=Date.now){let n=BigInt(t()).toString(16).padStart(12,"0"),r=_s(10),o=(r[0]&15|112).toString(16).padStart(2,"0")+r[1].toString(16).padStart(2,"0"),s=(r[2]&63|128).toString(16).padStart(2,"0")+r[3].toString(16).padStart(2,"0")+r[4].toString(16).padStart(2,"0")+r[5].toString(16).padStart(2,"0")+r[6].toString(16).padStart(2,"0")+r[7].toString(16).padStart(2,"0")+r[8].toString(16).padStart(2,"0")+r[9].toString(16).padStart(2,"0");return[n.slice(0,8),n.slice(8,12),o,s.slice(0,4),s.slice(4,16)].join("-")}i(he,"newIdempotencyKey");var Ss=new Set(["POST","PUT","PATCH","DELETE"]);function Ts(t,e){let n=e.toLowerCase();return Object.keys(t).some(r=>r.toLowerCase()===n)}i(Ts,"hasHeader");function As(t,e){if(!t)return{};if(!e)return{...t};let n=e.toLowerCase();return Object.fromEntries(Object.entries(t).filter(([r])=>r.toLowerCase()!==n))}i(As,"withoutHeader");function vs(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t))if(r.toLowerCase()===n&&typeof o=="string"&&o!=="")return o}i(vs,"headerValue");function Ns(t){return new Promise(e=>setTimeout(e,t))}i(Ns,"defaultSleep");async function Os(t,e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError");return e?new Promise((n,r)=>{let o=setTimeout(()=>{e.removeEventListener("abort",s),n()},t),s=i(()=>{clearTimeout(o),r(e.reason??new DOMException("Aborted","AbortError"))},"onAbort");e.addEventListener("abort",s,{once:!0})}):Ns(t)}i(Os,"abortableSleep");function Cs(t){try{return new URL(t).host}catch{return t}}i(Cs,"hostOf");function Is(t){try{return new URL(t).origin}catch{return t}}i(Is,"originOf");function ar(t){if(!t)return null;let e=/\bnonce="([^"]+)"/.exec(t);return e?e[1]:null}i(ar,"readNonceFromHeader");async function Zt(t){try{if((t.headers.get("content-type")??"").includes("application/json"))return await t.json();let n=await t.text();if(!n)return null;try{return JSON.parse(n)}catch{return n}}catch{return null}}i(Zt,"readResponseBody");function Ds(t,e=Date.now){let n={},r=t.get("x-ratelimit-remaining");r!==null&&r.trim()!==""&&!Number.isNaN(Number(r))&&(n.remaining=Number(r));let o=t.get("x-ratelimit-reset");if(o!==null&&o.trim()!==""&&!Number.isNaN(Number(o))){let c=Number(o);n.resetAt=c>1e12?c:c*1e3}let s=t.get("retry-after");if(s!==null&&s.trim()!==""){let c=Number(s);if(!Number.isNaN(c))n.retryAfterMs=Math.max(0,c*1e3);else{let a=Date.parse(s);Number.isNaN(a)||(n.retryAfterMs=Math.max(0,a-e()))}}return n}i(Ds,"parseRateLimit");function Us(t){return t.get("x-request-id")??t.get("x-npayload-request-id")}i(Us,"requestIdOf");async function en(t,e){let n=t.fetchImpl??globalThis.fetch,r=t.circuit??new pe,o=t.sleep??((O,T)=>Os(O,T)),s=t.now??Date.now,c=t.httpClient,a=c?async(O,T)=>c.fetch({method:T.method,url:O,headers:T.headers,body:T.body,...T.signal?{signal:T.signal}:{}}):async(O,T)=>n(O,t.dispatcher?{...T,dispatcher:t.dispatcher}:T),u=Cs(e.url),d=e.method.toUpperCase(),l=Ss.has(d)?e.idempotencyKey??vs(e.headers,"Idempotency-Key")??he():null;e.scope&&await t.auth.requireScope(e.scope);let m=0,g=!0,w=!0,R=!0;r.guard(u);let C=e.restartWindowMs??or()??6e4,b=null;try{for(;;){m+=1;let O=r.rateLimitedUntil(u);if(O!==void 0){let N=O-s();N>0&&await o(N,e.signal)}t.clockDrift?.check();let T=await t.auth.getAccessToken(e.scope?[e.scope]:[]),I=await t.auth.signDpopProof({method:d,url:e.url,accessToken:T.token}),H={...As(e.headers,l?"Idempotency-Key":void 0),Authorization:`DPoP ${T.token}`,DPoP:I,Accept:"application/json"};if(l&&(H["Idempotency-Key"]=l),e.traceparent&&(H.traceparent=e.traceparent),e.tracestate&&(H.tracestate=e.tracestate),e.body!=null&&!Ts(H,"content-type")&&(H["Content-Type"]="application/json"),e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");let _=e.timeoutMs!=null&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0,L=[e.signal,_].filter(N=>N!=null),v=L.length>1?AbortSignal.any(L):L[0],p;try{p=await a(e.url,{method:d,headers:H,body:e.body??null,...v?{signal:v}:{}})}catch(N){if(N instanceof Error&&N.name==="AbortError")throw N;let tt=N instanceof Error&&N.name==="TimeoutError",nt=wt({attempt:m,...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},restartWindowMs:C});if(b={},nt.retryable){t.onRetry?.({attempt:m,reason:nt.reason,nextDelayMs:nt.delayMs}),await o(nt.delayMs,e.signal);continue}throw tt?new le(`Request timed out after ${e.timeoutMs}ms`,{code:"timeout"}):tr(N)}if(p.status===401&&g){let N=p.headers.get("www-authenticate"),tt=ar(N);if(tt){t.auth.cacheNonce(Is(e.url),tt),g=!1,m-=1;continue}}let P;if(p.status===401&&w&&!ar(p.headers.get("www-authenticate"))&&(P={body:await Zt(p)},te(P.body)===void 0)){w=!1,t.auth.invalidate();continue}t.clockDrift?.observe(p.headers.get("date"),s());let U=Ds(p.headers,s);U.remaining===0&&(U.resetAt!==void 0?r.noteRateLimit(u,U.resetAt):U.retryAfterMs!==void 0&&r.noteRateLimit(u,s()+U.retryAfterMs),t.onRateLimit?.(U));let et=Us(p.headers);if(p.status>=200&&p.status<300)return r.recordSuccess(u),{data:await Zt(p),response:p,idempotencyKey:l,requestId:et,rateLimit:U};let rs=P!==void 0?P.body:await Zt(p),x=pt({status:p.status,body:rs,headers:p.headers,url:e.url});if(b={status:p.status},x instanceof ee&&R){R=!1,t.auth.peekCache()?.token===T.token&&t.auth.invalidate();continue}if(x instanceof V&&x.fingerprint===void 0){let N=await t.auth.fingerprint().catch(()=>{});x=new V(x.message,{code:x.code,...x.status!==void 0?{status:x.status}:{},...x.requestId!==void 0?{requestId:x.requestId}:{},...N!==void 0?{fingerprint:N}:{}})}if(zt(p.status)){let N=wt({attempt:m,status:p.status,retryAfterHeader:p.headers.get("retry-after"),...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},restartWindowMs:C});if(N.retryable){t.onRetry?.({attempt:m,reason:N.reason,nextDelayMs:N.delayMs}),await o(N.delayMs,e.signal);continue}}throw x instanceof S?x:new S(String(x),{code:"unknown"})}}catch(O){throw b&&r.recordFailure(u,b.status),O}}i(en,"kernelSend");import{promises as ur}from"dns";import*as rn from"tls";import{Agent as ks,Dispatcher as Ps,ProxyAgent as xs,interceptors as Ms}from"undici";var dr=20,fr=3e4,lr=1e4;function pr(t,e,n){if(!n)return!1;let r=t.toLowerCase();for(let o of n.split(/[\s,]+/)){let s=o.trim().toLowerCase();if(!s)continue;if(s==="*")return!0;let[c,a]=s.startsWith("[")?[s.slice(0,s.indexOf("]")+1),s.slice(s.indexOf("]")+2)]:s.split(":"),u=c.startsWith(".")?c.slice(1):c;if((r===u||r.endsWith(`.${u}`))&&!(a&&a!==e))return!0}return!1}i(pr,"noProxyMatches");function tn(t,...e){for(let n of e){let r=t[n];if(r&&r.trim())return r.trim()}}i(tn,"pick");function hr(t,e){let n=t.port||(t.protocol==="https:"?"443":"80");if(pr(t.hostname,n,tn(e,"NO_PROXY","no_proxy")))return;let r=t.protocol==="https:"?tn(e,"HTTPS_PROXY","https_proxy","ALL_PROXY","all_proxy"):tn(e,"HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy");if(r)try{return new URL(r).origin}catch{return}}i(hr,"proxyFor");function $s(t){return typeof t=="string"?new URL(t):t}i($s,"originUrl");var nn,Er=i(async t=>{nn??=new ur.Resolver({timeout:2e3,tries:2});let[e,n]=await Promise.allSettled([nn.resolve4(t,{ttl:!0}),nn.resolve6(t,{ttl:!0})]),r=[];if(e.status==="fulfilled")for(let s of e.value)r.push({address:s.address,family:4,ttlMs:s.ttl*1e3});if(n.status==="fulfilled")for(let s of n.value)r.push({address:s.address,family:6,ttlMs:s.ttl*1e3});return r.length>0?r:(await ur.lookup(t,{all:!0})).map(s=>({address:s.address,family:s.family===6?6:4,ttlMs:0}))},"resolveWithServerTtl");function Bs(){let t=rn;return typeof t.getCACertificates=="function"?t.getCACertificates("default"):rn.rootCertificates}i(Bs,"defaultTrustStore");var xe=class extends Ps{static{i(this,"KernelDispatcher")}pool;tunnels=new Map;env;connections;tlsMin;ca;allowH2;constructor(e={}){super(),this.connections=e.connections??dr,this.tlsMin=e.tlsMin??"TLSv1.3",this.ca=e.ca,this.allowH2=e.allowH2??!0,this.env=e.env??process.env;let n=e.dns?.lookup??Er,r=Ms.dns({maxTTL:e.dns?.maxTtlMs??lr,dualStack:!0,lookup:i((o,s,c)=>{n(o.hostname).then(a=>c(null,a.map(u=>({address:u.address,family:u.family,ttl:u.ttlMs}))),a=>c(a instanceof Error?a:new Error(String(a)),[]))},"lookup")});this.pool=new ks({connections:this.connections,pipelining:1,keepAliveTimeout:e.keepAliveTimeoutMs??fr,allowH2:this.allowH2,connect:this.tlsOptions()}).compose(r)}tlsOptions(){return this.ca!==void 0?{minVersion:this.tlsMin,ca:[...Bs(),...this.ca]}:{minVersion:this.tlsMin}}dispatch(e,n){if(e.origin===void 0)return this.pool.dispatch(e,n);let r=$s(e.origin),o=hr(r,this.env);if(!o)return this.pool.dispatch(e,n);if(r.protocol==="http:")return this.pool.dispatch({...e,origin:o,path:`${r.origin}${e.path}`},n);let s=this.tunnels.get(o);return s||(s=new xs({uri:o,connections:this.connections,allowH2:this.allowH2,proxyTls:{minVersion:this.tlsMin},requestTls:this.tlsOptions()}),this.tunnels.set(o,s)),s.dispatch(e,n)}everyDispatcher(){return[this.pool,...this.tunnels.values()]}close(e){let n=Promise.all(this.everyDispatcher().map(r=>r.close())).then(()=>{this.tunnels.clear()});if(e){n.then(e,e);return}return n}destroy(e,n){let r=typeof e=="function"?null:e??null,o=typeof e=="function"?e:n,s=Promise.all(this.everyDispatcher().map(c=>c.destroy(r))).then(()=>{this.tunnels.clear()});if(o){s.then(o,o);return}return s}};var gr=6e4,Me=class{static{i(this,"ClockDriftGuard")}maxDriftMs;drift;constructor(e=gr){this.maxDriftMs=e}get driftMs(){return this.drift}observe(e,n){if(!e)return;let r=Date.parse(e);Number.isNaN(r)||(this.drift=r-n)}check(){if(this.drift!==void 0&&Math.abs(this.drift)>this.maxDriftMs)throw new dt(this.drift,this.maxDriftMs)}};import{AsyncLocalStorage as Ys}from"async_hooks";var j="1.9.1";var wr=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ks(t){let e=new Set([t]),n=new Set,r=t.match(wr);if(!r)return()=>!1;let o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(u){return u===t},"isExactmatch");function s(a){return n.add(a),!1}i(s,"_reject");function c(a){return e.add(a),!0}return i(c,"_accept"),i(function(u){if(e.has(u))return!0;if(n.has(u))return!1;let d=u.match(wr);if(!d)return s(u);let f={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};return f.prerelease!=null||o.major!==f.major?s(u):o.major===0?o.minor===f.minor&&o.patch<=f.patch?c(u):s(u):o.minor<=f.minor?c(u):s(u)},"isCompatible")}i(Ks,"_makeCompatibilityCheck");var yr=Ks(j);var Hs=j.split(".")[0],$e=Symbol.for(`opentelemetry.js.api.${Hs}`),Be=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function be(t,e,n,r=!1){var o;let s=Be[$e]=(o=Be[$e])!==null&&o!==void 0?o:{version:j};if(!r&&s[t]){let c=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return n.error(c.stack||c.message),!1}if(s.version!==j){let c=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${j}`);return n.error(c.stack||c.message),!1}return s[t]=e,n.debug(`@opentelemetry/api: Registered a global for ${t} v${j}.`),!0}i(be,"registerGlobal");function J(t){var e,n;let r=(e=Be[$e])===null||e===void 0?void 0:e.version;if(!(!r||!yr(r)))return(n=Be[$e])===null||n===void 0?void 0:n[t]}i(J,"getGlobal");function Le(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${j}.`);let n=Be[$e];n&&delete n[t]}i(Le,"unregisterGlobal");var yt=class{static{i(this,"DiagComponentLogger")}constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Ke("debug",this._namespace,e)}error(...e){return Ke("error",this._namespace,e)}info(...e){return Ke("info",this._namespace,e)}warn(...e){return Ke("warn",this._namespace,e)}verbose(...e){return Ke("verbose",this._namespace,e)}};function Ke(t,e,n){let r=J("diag");if(r)return r[t](e,...n)}i(Ke,"logProxy");var k;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(k||(k={}));function mr(t,e){t<k.NONE?t=k.NONE:t>k.ALL&&(t=k.ALL),e=e||{};function n(r,o){let s=e[r];return typeof s=="function"&&t>=o?s.bind(e):function(){}}return i(n,"_filterFunc"),{error:n("error",k.ERROR),warn:n("warn",k.WARN),info:n("info",k.INFO),debug:n("debug",k.DEBUG),verbose:n("verbose",k.VERBOSE)}}i(mr,"createLogLevelDiagLogger");var Fs="diag",ne=class t{static{i(this,"DiagAPI")}static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(o){return function(...s){let c=J("diag");if(c)return c[o](...s)}}i(e,"_logProxy");let n=this,r=i((o,s={logLevel:k.INFO})=>{var c,a,u;if(o===n){let l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((c=l.stack)!==null&&c!==void 0?c:l.message),!1}typeof s=="number"&&(s={logLevel:s});let d=J("diag"),f=mr((a=s.logLevel)!==null&&a!==void 0?a:k.INFO,o);if(d&&!s.suppressOverrideMessage){let l=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";d.warn(`Current logger will be overwritten from ${l}`),f.warn(`Current logger will overwrite one already registered from ${l}`)}return be("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=()=>{Le(Fs,n)},n.createComponentLogger=o=>new yt(o),n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}};function sn(t){return Symbol.for(t)}i(sn,"createContextKey");var on=class t{static{i(this,"BaseContext")}constructor(e){let n=this;n._currentContext=e?new Map(e):new Map,n.getValue=r=>n._currentContext.get(r),n.setValue=(r,o)=>{let s=new t(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=r=>{let o=new t(n._currentContext);return o._currentContext.delete(r),o}}},He=new on;var mt=class{static{i(this,"NoopContextManager")}active(){return He}with(e,n,r,...o){return n.call(r,...o)}bind(e,n){return n}enable(){return this}disable(){return this}};var an="context",Vs=new mt,re=class t{static{i(this,"ContextAPI")}constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return be(an,e,ne.instance())}active(){return this._getContextManager().active()}with(e,n,r,...o){return this._getContextManager().with(e,n,r,...o)}bind(e,n){return this._getContextManager().bind(e,n)}_getContextManager(){return J(an)||Vs}disable(){this._getContextManager().disable(),Le(an,ne.instance())}};var Rt;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Rt||(Rt={}));var cn="0000000000000000",un="00000000000000000000000000000000",Rr={traceId:un,spanId:cn,traceFlags:Rt.NONE};var q=class{static{i(this,"NonRecordingSpan")}constructor(e=Rr){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,n){return this}setAttributes(e){return this}addEvent(e,n){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,n){}};var dn=sn("OpenTelemetry Context Key SPAN");function bt(t){return t.getValue(dn)||void 0}i(bt,"getSpan");function br(){return bt(re.getInstance().active())}i(br,"getActiveSpan");function Fe(t,e){return t.setValue(dn,e)}i(Fe,"setSpan");function Lr(t){return t.deleteValue(dn)}i(Lr,"deleteSpan");function _r(t,e){return Fe(t,new q(e))}i(_r,"setSpanContext");function Lt(t){var e;return(e=bt(t))===null||e===void 0?void 0:e.spanContext()}i(Lt,"getSpanContext");var _t=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Sr(t,e){if(typeof t!="string"||t.length!==e)return!1;let n=0;for(let r=0;r<t.length;r+=4)n+=(_t[t.charCodeAt(r)]|0)+(_t[t.charCodeAt(r+1)]|0)+(_t[t.charCodeAt(r+2)]|0)+(_t[t.charCodeAt(r+3)]|0);return n===e}i(Sr,"isValidHex");function qs(t){return Sr(t,32)&&t!==un}i(qs,"isValidTraceId");function Ws(t){return Sr(t,16)&&t!==cn}i(Ws,"isValidSpanId");function St(t){return qs(t.traceId)&&Ws(t.spanId)}i(St,"isSpanContextValid");function Tr(t){return new q(t)}i(Tr,"wrapSpanContext");var fn=re.getInstance(),_e=class{static{i(this,"NoopTracer")}startSpan(e,n,r=fn.active()){if(!!n?.root)return new q;let s=r&&Lt(r);return Gs(s)&&St(s)?new q(s):new q}startActiveSpan(e,n,r,o){let s,c,a;if(arguments.length<2)return;arguments.length===2?a=n:arguments.length===3?(s=n,a=r):(s=n,c=r,a=o);let u=c??fn.active(),d=this.startSpan(e,s,u),f=Fe(u,d);return fn.with(f,a,void 0,d)}};function Gs(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}i(Gs,"isSpanContext");var js=new _e,Tt=class{static{i(this,"ProxyTracer")}constructor(e,n,r,o){this._provider=e,this.name=n,this.version=r,this.options=o}startSpan(e,n,r){return this._getTracer().startSpan(e,n,r)}startActiveSpan(e,n,r,o){let s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):js}};var At=class{static{i(this,"NoopTracerProvider")}getTracer(e,n,r){return new _e}};var Js=new At,Ve=class{static{i(this,"ProxyTracerProvider")}getTracer(e,n,r){var o;return(o=this.getDelegateTracer(e,n,r))!==null&&o!==void 0?o:new Tt(this,e,n,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Js}setDelegate(e){this._delegate=e}getDelegateTracer(e,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,n,r)}};var qe;(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(qe||(qe={}));var Se;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Se||(Se={}));var vt=re.getInstance();var ln="trace",Nt=class t{static{i(this,"TraceAPI")}constructor(){this._proxyTracerProvider=new Ve,this.wrapSpanContext=Tr,this.isSpanContextValid=St,this.deleteSpan=Lr,this.getSpan=bt,this.getActiveSpan=br,this.getSpanContext=Lt,this.setSpan=Fe,this.setSpanContext=_r}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let n=be(ln,this._proxyTracerProvider,ne.instance());return n&&this._proxyTracerProvider.setDelegate(e),n}getTracerProvider(){return J(ln)||this._proxyTracerProvider}getTracer(e,n){return this.getTracerProvider().getTracer(e,n)}disable(){Le(ln,ne.instance()),this._proxyTracerProvider=new Ve}};var Ot=Nt.getInstance();var vr="@npayload/sdk",pn=class{static{i(this,"AsyncLocalStorageContextManager")}storage=new Ys;active(){return this.storage.getStore()??He}with(e,n,r,...o){return this.storage.run(e,()=>n.call(r,...o))}bind(e,n){if(typeof n!="function")return n;let r=this,o=n;return function(...s){return r.with(e,()=>o.apply(this,s))}}enable(){return this}disable(){return this.storage.disable(),this}},Ar=!1;function Xs(){let t=Ot.getTracerProvider(),n=(typeof t.getDelegate=="function"?t.getDelegate():t)?.constructor?.name??"";return n!==""&&n!=="NoopTracerProvider"}i(Xs,"hostHasTracerProvider");function Qs(){Ar||Xs()&&(Ar=!0,vt.setGlobalContextManager(new pn))}i(Qs,"ensureContextManager");function hn(t){Qs();let e=Ot.getTracer(vr,t.kernelVersion),n="";try{n=new URL(t.url).host}catch{}let r=e.startSpan("http.client",{kind:qe.CLIENT,attributes:{"http.request.method":t.method,"url.full":t.url,"server.address":n,"npayload.sdk":"node-kernel","npayload.kernel_version":t.kernelVersion,"npayload.client_id":t.clientId,"npayload.path":t.path,"npayload.traceparent":t.traceparent,...t.env!==void 0?{"npayload.env":t.env}:{}}},vt.active());return{span:r,end(o){o.status!==void 0&&r.setAttribute("http.response.status_code",o.status),o.requestId&&r.setAttribute("npayload.request_id",o.requestId),o.error!==void 0?(r.setStatus({code:Se.ERROR,message:o.error instanceof Error?o.error.message:String(o.error)}),o.error instanceof Error&&r.recordException(o.error)):r.setStatus({code:Se.OK}),r.end()}}}i(hn,"startHttpClientSpan");import{randomBytes as zs}from"crypto";var Zs=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/i;function En(t){return zs(t).toString("hex")}i(En,"hex");function Nr(){return`00-${En(16)}-${En(8)}-01`}i(Nr,"generateTraceparent");function Or(t){if(!t||!Zs.test(t))return Nr();let n=t.split("-")[1],r=En(8);return`00-${n}-${r}-01`}i(Or,"propagateTraceparent");var We=class{static{i(this,"KernelObserver")}handlers=new Map;on(e,n){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(n),()=>{this.handlers.get(e)?.delete(n)}}traceparent(e){return Or(e)}emit(e){let n=this.handlers.get(e.type);if(n)for(let r of n)try{r(e)}catch{}}};function gn(t){let e,n="message",r=[],o;for(let a of t.split(/\r?\n/)){if(a===""||a.startsWith(":"))continue;let u=a.indexOf(":"),d=u===-1?a:a.slice(0,u),f=u===-1?"":a.slice(u+1);switch(f.startsWith(" ")&&(f=f.slice(1)),d){case"id":e=f;break;case"event":n=f;break;case"data":r.push(f);break;case"retry":{let l=Number(f);!Number.isNaN(l)&&l>=0&&(o=l);break}default:break}}if(r.length===0)return null;let s=r.join(`
|
|
2
|
+
`),c;try{c=JSON.parse(s)}catch{c=s}return e!==void 0?o!==void 0?{id:e,event:n,data:c,raw:s,retryAfterMs:o}:{id:e,event:n,data:c,raw:s}:o!==void 0?{event:n,data:c,raw:s,retryAfterMs:o}:{event:n,data:c,raw:s}}i(gn,"parseSseBlock");async function*ei(t){let e=t.getReader(),n=new TextDecoder("utf-8"),r="";try{for(;;){let{done:o,value:s}=await e.read();s&&(r+=n.decode(s,{stream:!0}));let c=r.split(/\r?\n\r?\n/);r=c.pop()??"";for(let a of c){let u=gn(a);u&&(yield u)}if(o){if(r.trim().length>0){let a=gn(r);a&&(yield a)}return}}}finally{e.releaseLock()}}i(ei,"parseEventStream");import{createHmac as cf,timingSafeEqual as uf}from"crypto";import{readFileSync as yf,writeFileSync as mf}from"fs";var Ct="0.2.0",Dr="https://api.npayload.com";function ti(t){return`${(t.authUrl??t.baseUrl??Dr).replace(/\/+$/,"")}/oauth/token`}i(ti,"tokenEndpointOf");var ni="X-NPayload-Env",ri=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/i,Cr=class{static{i(this,"Kernel")}config;auth;observer;circuit;dispatcher;clockDrift;clockNow;methods=new Set;constructor(e){let n=e.config;si(n);let r=rt(n.dpopPrivateJwk)?n.dpopPrivateJwk:new Ue(n.dpopPrivateJwk),o=n.tlsMin??"TLSv1.3";if(o!=="TLSv1.3"&&o!=="TLSv1.2")throw new Z(`tlsMin must be "TLSv1.3" or "TLSv1.2" (TLS 1.2 is the floor); got ${String(o)}`,{code:"tls_min_below_floor"});let s={...n,tlsMin:o,dpopPrivateJwk:r};this.config=s,this.observer=new We;let c=n.testClock!==void 0?()=>n.testClock.now():void 0;this.circuit=new pe(c!==void 0?{now:c}:{}),this.clockDrift=new Me(n.maxClockDriftMs),this.clockNow=c,this.dispatcher=new xe({tlsMin:o,...n.tlsCa!==void 0?{ca:n.tlsCa}:{},...n.dns!==void 0?{dns:n.dns}:{}}),this.auth=new Et({clientId:n.clientId,keys:{publicJwk:r.publicJwk,privateJwk:r},authServerUrl:ti(n),...n.appId!==void 0?{appId:n.appId}:{},...n.clientSecret!==void 0?{clientSecret:n.clientSecret}:{},...n.env!==void 0?{env:n.env}:{},...c!==void 0?{now:c}:{}})}async send(e){if(this.config.mockMode)throw new Error("Kernel.send called in mockMode \u2014 use the resource-layer mock helpers");ui(e);let n=ii(this.config.baseUrl??Dr,e),r=e.traceparent!==void 0&&ri.test(e.traceparent)?e.traceparent:this.observer.traceparent(void 0),o=Date.now();this.observer.emit({type:"request",method:e.method,path:e.path,traceparent:r,...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{}});let c={...this.config.env?{[ni]:this.config.env}:{},...e.headers??{}},a=this.config.telemetry===!1?void 0:hn({method:e.method,url:n,path:e.path,clientId:this.config.clientId,kernelVersion:Ct,traceparent:r,...this.config.env!==void 0?{env:this.config.env}:{}});try{let u=await en({auth:this.auth,circuit:this.circuit,clockDrift:this.clockDrift,...this.clockNow!==void 0?{now:this.clockNow}:{},...this.config.httpClient!==void 0?{httpClient:this.config.httpClient}:{dispatcher:this.dispatcher},onRetry:i(g=>this.observer.emit({type:"retry",...g}),"onRetry"),onRateLimit:i(g=>{for(let w of this.rateLimitHandlers)try{w(g.remaining??0,g.resetAt??0)}catch{}},"onRateLimit")},{method:e.method,url:n,...Object.keys(c).length>0?{headers:c}:{},...e.body!==void 0?{body:ai(e.body)}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},...e.restartWindowMs!==void 0?{restartWindowMs:e.restartWindowMs}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},traceparent:r,...e.tracestate!==void 0?{tracestate:e.tracestate}:{},...e.signal!==void 0?{signal:e.signal}:{},...e.scope!==void 0?{scope:e.scope}:{}}),d=u.response,f=d.status??200,l=d.headers?.get("content-length"),m=l&&Number.parseInt(l,10)||0;return this.observer.emit({type:"response",status:f,durationMs:Date.now()-o,...u.requestId!==null?{requestId:u.requestId}:{},bytes:m}),a?.end({status:f,requestId:u.requestId}),u.data}catch(u){this.observer.emit({type:"error",code:Ir(u),durationMs:Date.now()-o});let d=di(u);throw a?.end({error:u,...d!==void 0?{status:d}:{}}),u}}newIdempotencyKey(){return he()}rateLimitHandlers=new Set;onCircuitOpen(e){return this.circuit.onOpen(e)}onCircuitClose(e){return this.circuit.onClose(e)}onRateLimited(e){return this.rateLimitHandlers.add(e),()=>{this.rateLimitHandlers.delete(e)}}registerMethod(e){this.methods.add(e)}listMethods(){return Array.from(this.methods).sort()}async health(){if(this.config.mockMode)return{ok:!0,serverVersion:"mock",sdkVersion:Ct};try{let e=await this.send({method:"GET",path:"/v1/_health"});return{ok:e.ok,serverVersion:e.version??"unknown",sdkVersion:Ct}}catch(e){return{ok:!1,serverVersion:"unknown",sdkVersion:Ct,error:Ir(e)}}}},oi=["apiKey","api_key","orgId","org_id","tenantId","tenant_id","ownerId","hmacSecret","hmac_secret","secret","bearer"];function si(t){for(let e of oi)if(e in t)throw new Error(`KernelConfig MUST NOT include "${e}". The npayload kernel uses DPoP-bound OAuth tokens \u2014 never an API key, secret, or org id.`)}i(si,"rejectForbiddenFields");function ii(t,e){let n=e.path;if(e.pathParams)for(let[o,s]of Object.entries(e.pathParams))n=n.replace(`{${o}}`,encodeURIComponent(s));let r=t.replace(/\/+$/,"")+n;if(e.query&&Object.keys(e.query).length>0){let o=new URLSearchParams;for(let[s,c]of Object.entries(e.query))o.set(s,String(c));r+=`?${o.toString()}`}return r}i(ii,"composeUrl");function ai(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch(e){let n=e instanceof Error?e.message:String(e);throw new Z(`Failed to serialise request body: ${n}`,{code:"body_serialisation_failed"})}}i(ai,"serialiseBody");function Ir(t){return t&&typeof t=="object"&&"code"in t?String(t.code):"unknown"}i(Ir,"getCode");var ci=new Set(["orgid","org_id","organizationid","organization_id","tenantid","tenant_id","ownerid","owner_id","x-org-id","x-tenant-id","x-owner-id","x-organization-id"]);function ui(t){let e=[];for(let n of[t.headers,t.query])if(n)for(let r of Object.keys(n))ci.has(r.toLowerCase())&&e.push(r);if(e.length>0)throw new Z(`Org-shaped request fields are never sent by the kernel (the org is the credential's): ${e.join(", ")}`,{code:"org_context_forbidden"})}i(ui,"rejectOrgShapedRequestFields");function di(t){let e=t?.status;return typeof e=="number"?e:void 0}i(di,"getStatus");var h=16,Ge=144,K=64,fi=128;function xr(t){return(t&W.PQ_HYBRID)!==0?fi:K}i(xr,"publishSignatureLen");var Ae=32,dl=new Uint8Array([78,80,80,1]),oe=new Uint8Array([78,80,80,1]),y={HELLO:0,HELLO_ACK:1,PUBLISH:2,PUBLISH_BATCH:3,BULK_ACK:4,SUBSCRIBE:5,DELIVER:6,DELIVER_BATCH:7,ACK:8,SEEK:9,FLOW_CREDIT:13,PING:14,PONG:15,GOODBYE:16,ERROR:17,SYS_EVENT:18,REKEY:19},Mr={ZSTD:1,E2E:2,HLC:4,PQ_HYBRID:64};var $r=1,Br=0,Kr={AT_MOST_ONCE:0,AT_LEAST_ONCE:1,EXACTLY_ONCE:2},fl=Kr.EXACTLY_ONCE;var W={COMPRESSED:1,ENCRYPTED:2,BATCH:4,URGENT:8,RESERVED_V2:16,EXTENDED_HEADER:32,PQ_HYBRID:64,SESSION_PARAMS:128},ve={ACCEPTED:0,ACCEPTED_DUPLICATE:1,REJECTED_GAP:16,REJECTED_DUPLICATE:17,REJECTED_SIGNATURE:32,REJECTED_AUTH:33,REJECTED_SCHEMA:48,REJECTED_PAYLOAD:49,REJECTED_INVALID_FILTER:50,REJECTED_QUOTA:64,REJECTED_GRANT:65,DEFERRED_RETRY:80,REJECTED_OTHER:255},Hr={REJECTED_HW_ATTESTATION:144};function Y(t){if(t.headerLen<h)throw new RangeError(`headerLen must be \u2265 ${h}, got ${t.headerLen}`);if(t.frameType<0||t.frameType>255)throw new RangeError(`frameType out of range: ${t.frameType}`);if(t.flags<0||t.flags>255)throw new RangeError(`flags out of range: ${t.flags}`);if(t.headerLen>65535)throw new RangeError(`headerLen exceeds u16: ${t.headerLen}`);if(t.sessionId<0||t.sessionId>4294967295)throw new RangeError(`sessionId out of range: ${t.sessionId}`);if(t.payloadLen<0||t.payloadLen>4294967295)throw new RangeError(`payloadLen out of range: ${t.payloadLen}`);let e=new Uint8Array(h);e.set(oe,0),e[4]=t.frameType,e[5]=t.flags;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setUint16(6,t.headerLen,!1),n.setUint32(8,t.sessionId,!1),n.setUint32(12,t.payloadLen,!1),e}i(Y,"encodeCommonHeader");function M(t){if(t.byteLength<h)throw new RangeError(`frame too short for common header: ${t.byteLength} < ${h}`);for(let a=0;a<4;a+=1)if(t[a]!==oe[a])throw new Error("npp: bad magic \u2014 not an NPP frame");let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=t[4],r=t[5],o=e.getUint16(6,!1),s=e.getUint32(8,!1),c=e.getUint32(12,!1);if(o<h)throw new RangeError(`headerLen below minimum: ${o} < ${h}`);return{frameType:n,flags:r,headerLen:o,sessionId:s,payloadLen:c}}i(M,"decodeCommonHeader");var Ur=5;function Fr(t){if(t.nppVersionMajor<0||t.nppVersionMajor>255)throw new RangeError(`nppVersionMajor out of u8 range: ${t.nppVersionMajor}`);if(t.nppVersionMinor<0||t.nppVersionMinor>255)throw new RangeError(`nppVersionMinor out of u8 range: ${t.nppVersionMinor}`);if(t.capabilityFlags<0||t.capabilityFlags>65535)throw new RangeError(`capabilityFlags out of u16 range: ${t.capabilityFlags}`);let e=t.qosCapabilities??Kr.AT_LEAST_ONCE;if(e<0||e>255)throw new RangeError(`qosCapabilities out of u8 range: ${e}`);let n=t.authBody??new Uint8Array(0),r=Ur+n.byteLength,o=new Uint8Array(h+r);return o.set(Y({frameType:y.HELLO,flags:0,headerLen:h,sessionId:t.sessionId??0,payloadLen:r}),0),o[16]=t.nppVersionMajor,o[17]=t.nppVersionMinor,new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(18,t.capabilityFlags,!1),o[20]=e,n.byteLength>0&&o.set(n,h+Ur),o}i(Fr,"encodeHello");var wn=6,Te=32,bn=32,li=8+bn,pi=1,hi=8,yn=4+hi,kr=5;function Ei(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r,o=e;for(;o<t.byteLength;){if(o+kr>t.byteLength)throw new RangeError(`HELLO_ACK SESSION_PARAMS entry header runs past the frame at ${o}`);let s=t[o],c=n.getUint32(o+1,!1),a=o+kr,u=a+c;if(u>t.byteLength)throw new RangeError(`HELLO_ACK SESSION_PARAMS entry 0x${s.toString(16).padStart(2,"0")} runs past the frame: have ${t.byteLength}, need ${u}`);if(s===pi){if(r!==void 0)throw new RangeError("HELLO_ACK SESSION_PARAMS carries two identity lists");r=gi(t,n,a,u)}o=u}return r}i(Ei,"decodeSessionParamsEntries");function gi(t,e,n,r){let o=n,s=i(u=>{if(o+2>r)throw new RangeError("HELLO_ACK identity list shorter than its counts");let d=e.getUint16(o,!1);o+=2;let f=[];for(let l=0;l<d;l+=1){if(o+yn>r)throw new RangeError("HELLO_ACK identity list shorter than its tuples");f.push(u(e.getUint32(o,!1),t.slice(o+4,o+yn))),o+=yn}return f},"tuples"),c=s((u,d)=>({channelId:u,gidHash:d})),a=s((u,d)=>({schemaFingerprint:u,schemaGidHash:d}));if(o!==r)throw new RangeError("HELLO_ACK identity list longer than its tuples");return{channels:c,schemas:a}}i(gi,"decodeIdentityList");function Vr(t){let e=wi(t),n=mn(e.prefix,e.nonce);return t.byteLength<=e.sigEnd?[n]:[mn(n,t.slice(e.sigEnd)),n]}i(Vr,"helloAckSigningInputs");function wi(t){let e=M(t),n=e.headerLen,r=n+e.payloadLen,o=r+Te,s=o+K;if(t.byteLength<s)throw new RangeError(`HELLO_ACK truncated for signing input: have ${t.byteLength}, need ${s}`);return{prefix:mn(t.slice(8,h),t.slice(n,r)),nonce:t.slice(r,o),sigEnd:s}}i(wi,"helloAckSignedParts");function mn(...t){let e=0;for(let o of t)e+=o.byteLength;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n}i(mn,"concatBytes");function qr(t){if(t.byteLength<h+wn)throw new RangeError(`HELLO_ACK too short: ${t.byteLength} < ${h+wn}`);let e=M(t);if(e.frameType!==y.HELLO_ACK)throw new Error(`decodeHelloAck: expected frameType=HELLO_ACK (0x01), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r={sessionId:e.sessionId,nppVersionMajor:t[16],nppVersionMinor:t[17],negotiatedCapabilities:n.getUint16(20,!1)},o=h+wn,s=(e.flags&W.EXTENDED_HEADER)!==0,c=o+Te+K;if(s&&t.byteLength>=c&&(r.nonceEcho=t.slice(o,o+Te),r.serverSignature=t.slice(o+Te,c)),(e.flags&W.SESSION_PARAMS)!==0){let a=o+(s?Te+K:0),u=a+li;if(t.byteLength<u)throw new RangeError(`HELLO_ACK SESSION_PARAMS truncated: have ${t.byteLength}, need ${u}`);r.sessionTtlSec=n.getUint32(a,!1),r.publishWindowMs=n.getUint32(a+4,!1),r.ephemeralPublicKey=t.slice(a+8,a+8+bn);let d=Ei(t,u);d!==void 0&&(r.identities=d)}return r}i(qr,"decodeHelloAck");function Ln(t,e){if(t.frameType!==y.PUBLISH)throw new Error(`encodePublishEnvelope: expected frameType=PUBLISH (0x02), got 0x${t.frameType.toString(16).padStart(2,"0")}`);if(e.payloadHash.byteLength!==Ae)throw new RangeError(`payloadHash must be ${Ae} bytes, got ${e.payloadHash.byteLength}`);let n=xr(t.flags);if(e.detachedSignature.byteLength!==n)throw new RangeError(`detachedSignature must be ${n} bytes for ${(t.flags&W.PQ_HYBRID)!==0?"PQ_HYBRID":"classical"} mode, got ${e.detachedSignature.byteLength}`);if(e.qosLevel<0||e.qosLevel>2)throw new RangeError(`qosLevel must be 0..2, got ${e.qosLevel}`);if(e.encryptionMode<0||e.encryptionMode>3)throw new RangeError(`encryptionMode must be 0..3, got ${e.encryptionMode}`);if(e.attributesCount<0||e.attributesCount>65535)throw new RangeError(`attributesCount out of range: ${e.attributesCount}`);let r=e.priority!==void 0;if(r&&(e.priority<0||e.priority>9))throw new RangeError(`priority must be 0..9, got ${e.priority}`);let o=48+Ae+n,s=o+(r?1:0),c=r?t.flags|W.EXTENDED_HEADER:t.flags,a=new Uint8Array(s);a.set(Y({...t,flags:c}),0);let u=new DataView(a.buffer,a.byteOffset,a.byteLength);return u.setUint32(16,e.channelId,!1),u.setUint32(20,e.partitionId,!1),u.setBigUint64(24,e.sequence,!1),u.setBigUint64(32,e.hlcTimestamp,!1),u.setUint32(40,e.schemaFingerprint,!1),a[44]=e.qosLevel,a[45]=e.encryptionMode,u.setUint16(46,e.attributesCount,!1),a.set(e.payloadHash,48),a.set(e.detachedSignature,80),r&&(a[o]=e.priority),a}i(Ln,"encodePublishEnvelope");function kt(t){if(t.byteLength<80)throw new RangeError(`envelope bytes too short for signing input: ${t.byteLength}`);return t.slice(8,80)}i(kt,"canonicalPublishSigningInput");var yi=10;function Wr(t){let e=M(t);if(e.frameType!==y.BULK_ACK)throw new Error(`decodeBulkAck: expected frameType=BULK_ACK (0x04), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=yi,r=h+e.payloadLen;if(t.byteLength<r)throw new RangeError(`BULK_ACK truncated: have ${t.byteLength}, need ${r}`);if(e.payloadLen%n!==0)throw new RangeError(`BULK_ACK payloadLen not a multiple of ${n}: ${e.payloadLen}`);let o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=e.payloadLen/n,c=[];for(let u=0;u<s;u+=1){let d=h+u*n;c.push({seq:o.getBigUint64(d,!1),status:o.getUint16(d+8,!1)})}let a;return(e.flags&W.EXTENDED_HEADER)!==0&&t.byteLength>=r+K&&(a=t.slice(r,r+K)),{header:e,records:c,serverSignature:a}}i(Wr,"decodeBulkAck");var se=48,$={LOG:0,QUEUE:1,TOPIC:2,TAIL:3,OUTCOMES:4,DEAD_LETTERS:5,TABLE_HEAD:6,WINDOW:7,COUNTERS:8,UNIT_HEAD:9},Ee={PUSH:0,PULL:1,HYBRID:2},It={NONE:0,JSONPATH:1,CEL:2,ROUTING_KEY_PREFIX:3},ll=new Set([It.NONE,It.JSONPATH,It.CEL,It.ROUTING_KEY_PREFIX]);function Gr(t,e){return t===$.TOPIC&&(e===Ee.PULL||e===Ee.HYBRID)?"TOPIC mode is push-only (no cursor)":t===$.TAIL&&(e===Ee.PULL||e===Ee.HYBRID)?"TAIL mode is push-only (subscribe-from-now)":mi(t)&&e!==Ee.PUSH?"a view mode (OUTCOMES, DEAD_LETTERS, TABLE_HEAD, WINDOW, COUNTERS, UNIT_HEAD) is push-only":null}i(Gr,"validateSubscribeModeCompat");function Ne(t){let e=t.envelope;if(e.mode<0||e.mode>255)throw new RangeError(`mode out of range: ${e.mode}`);if(e.deliveryPreference<0||e.deliveryPreference>255)throw new RangeError(`deliveryPreference out of range: ${e.deliveryPreference}`);let n=Gr(e.mode,e.deliveryPreference);if(n)throw new RangeError(`SUBSCRIBE compat: ${n}`);if(e.qosCapabilities<0||e.qosCapabilities>65535)throw new RangeError(`qosCapabilities out of range: ${e.qosCapabilities}`);if(e.partitionFilter<0||e.partitionFilter>4294967295)throw new RangeError(`partitionFilter out of range: ${e.partitionFilter}`);if(e.filters.length>255)throw new RangeError(`too many filters (filterCount is u8): ${e.filters.length}`);let r=0;for(let f of e.filters){if(f.value.byteLength>65535)throw new RangeError(`filter value too large: ${f.value.byteLength}`);r+=3+f.value.byteLength}let o=t.consumerSignature??new Uint8Array(0);if(o.byteLength>65535)throw new RangeError(`consumerSignature too large: ${o.byteLength}`);let c=se-h+r+o.byteLength,a=new Uint8Array(h+c);a.set(Y({frameType:y.SUBSCRIBE,flags:0,headerLen:h,sessionId:t.sessionId,payloadLen:c}),0);let u=new DataView(a.buffer,a.byteOffset,a.byteLength);u.setUint32(16,e.channelId,!1),u.setUint32(20,e.partitionFilter,!1),a[24]=e.mode,a[25]=e.deliveryPreference,u.setUint16(26,e.qosCapabilities,!1),u.setBigUint64(28,e.startCursor,!1),u.setBigUint64(36,e.startHlc,!1),a[44]=e.filters.length;let d=se;for(let f of e.filters)a[d]=f.type&255,u.setUint16(d+1,f.value.byteLength,!1),a.set(f.value,d+3),d+=3+f.value.byteLength;return a.set(o,d),a}i(Ne,"encodeSubscribeFrame");function _n(t){if(t.byteLength<se)throw new RangeError(`envelope too short for SUBSCRIBE signing input: ${t.byteLength}`);let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=Math.min(t.byteLength,h+e.getUint32(12,!1)),r=se;for(let o=0;o<t[44];o+=1){if(r+3>n)throw new RangeError(`SUBSCRIBE filter ${o} header truncated: no signing input`);if(r+=3+e.getUint16(r+1,!1),r>n)throw new RangeError(`SUBSCRIBE filter ${o} value truncated: no signing input`)}return t.slice(8,r)}i(_n,"canonicalSubscribeSigningInput");var pl=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),jr=new TextEncoder;function mi(t){return Number.isInteger(t)&&t>=$.OUTCOMES&&t<=$.UNIT_HEAD}i(mi,"isViewMode");var B={RECORD:0,OUTCOME:1,DEAD_LETTER:2,TABLE_HEAD:3,WINDOW:4,COUNTERS:5,UNIT_HEAD:6},Ri="npk_view",bi={[B.OUTCOME]:"outcome",[B.DEAD_LETTER]:"dead_letter",[B.TABLE_HEAD]:"table_head",[B.WINDOW]:"window",[B.COUNTERS]:"counters",[B.UNIT_HEAD]:"unit_head"},hl=jr.encode(Ri),El=[B.OUTCOME,B.DEAD_LETTER,B.TABLE_HEAD,B.WINDOW,B.COUNTERS,B.UNIT_HEAD].map(t=>[t,jr.encode(bi[t])]);var gl={[$.OUTCOMES]:"kernel:outcomes:",[$.DEAD_LETTERS]:"kernel:dead_letters:",[$.TABLE_HEAD]:"kernel:head:",[$.WINDOW]:"kernel:window:",[$.COUNTERS]:"kernel:counters:",[$.UNIT_HEAD]:"kernel:unit_head:"};var Li=22,_i=27,Si=27;function Ti(t){let e=M(t);if(e.headerLen>t.byteLength)throw new RangeError(`headerLen ${e.headerLen} beyond the frame's ${t.byteLength} bytes`);let n=[],r=h;for(;r<e.headerLen;){if(r+2>e.headerLen)throw new RangeError("TLV region does not fill 16..headerLen exactly: a type without its length");let s=t[r+1];if(r+2+s>e.headerLen)throw new RangeError(`TLV 0x${t[r].toString(16)} of ${s} bytes runs past headerLen ${e.headerLen}`);n.push({type:t[r],value:t.slice(r+2,r+2+s)}),r+=2+s}for(let s=0;s<n.length;s+=1){let c=n[s].type;if(c>=1&&c<=Si&&c!==Li&&c!==_i&&n.slice(0,s).some(a=>a.type===c))throw new RangeError(`TLV 0x${c.toString(16)} repeated: a registered TLV appears once in a frame`)}if(e.headerLen===h)return{canonical:t,tlvs:n};let o=new Uint8Array(t.byteLength-(e.headerLen-h));return o.set(t.subarray(0,h),0),o.set(t.subarray(e.headerLen),h),new DataView(o.buffer).setUint16(6,h,!1),{canonical:o,tlvs:n}}i(Ti,"splitHeaderTlvs");var Ai=10,vi=26;function Jr(t,e,n){if(n.length===0)throw new RangeError("ACK must contain at least one record");let r=n.some(f=>f.deliveryToken!==void 0),o=r?vi:Ai,s=4,c=s+n.length*o,a=new Uint8Array(h+c);a.set(Y({frameType:y.ACK,flags:r?W.EXTENDED_HEADER:0,headerLen:h,sessionId:t,payloadLen:c}),0);let u=new DataView(a.buffer,a.byteOffset,a.byteLength);u.setUint32(16,e,!1);let d=h+s;for(let f of n){if(f.disposition<0||f.disposition>65535)throw new RangeError(`disposition out of range: ${f.disposition}`);if(u.setBigUint64(d,f.seq,!1),u.setUint16(d+8,f.disposition,!1),r){let l=f.deliveryToken??{hi:0n,lo:0n};u.setBigUint64(d+10,l.hi,!1),u.setBigUint64(d+18,l.lo,!1)}d+=o}return a}i(Jr,"encodeAck");var Ni=16;function Dt(t,e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new RangeError(`FLOW_CREDIT ${t} out of u32 range: ${e}`)}i(Dt,"assertU32");function Yr(t,e){Dt("channelId",e.channelId),Dt("creditDelta",e.creditDelta),Dt("projectedLagMs",e.projectedLagMs),Dt("bandwidthBudgetBps",e.bandwidthBudgetBps);let n=Ni,r=new Uint8Array(h+n);r.set(Y({frameType:y.FLOW_CREDIT,flags:0,headerLen:h,sessionId:t,payloadLen:n}),0);let o=new DataView(r.buffer,r.byteOffset,r.byteLength);return o.setUint32(h+0,e.channelId,!1),o.setUint32(h+4,e.creditDelta,!1),o.setUint32(h+8,e.projectedLagMs,!1),o.setUint32(h+12,e.bandwidthBudgetBps,!1),r}i(Yr,"encodeFlowCredit");function Xr(t){let e=M(t);if(e.frameType!==y.SYS_EVENT)throw new Error(`expected SYS_EVENT (0x12), got 0x${e.frameType.toString(16)}`);if(e.payloadLen<16)throw new RangeError("SYS_EVENT payload too small");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(16,!1),o=n.getUint32(20,!1),s=n.getBigUint64(24,!1),c=t.slice(h+16,h+e.payloadLen);return{header:e,frame:{channelId:r,eventCode:o,hlcTimestamp:s,payload:c}}}i(Xr,"decodeSysEvent");var Ut=10;function Qr(t){let e=M(t);if(e.frameType!==y.ERROR)throw new Error(`decodeError: expected frameType=ERROR (0x11), got 0x${e.frameType.toString(16).padStart(2,"0")}`);if(e.payloadLen<Ut)throw new RangeError(`ERROR payload too small: ${e.payloadLen}`);e.headerLen!==h&&Ti(t);let n=e.headerLen;if(t.byteLength<n+e.payloadLen)throw new RangeError("ERROR frame truncated");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),o=n+Ut,s=n+e.payloadLen;return{header:e,frame:{seq:r.getBigUint64(n,!1),reasonCode:r.getUint16(n+8,!1),detail:t.slice(o,s)}}}i(Qr,"decodeError");var Oe={FRAME_MALFORMED:498,PROTOCOL_VIOLATION:499,UPSTREAM_REFUSED:500};function Rn(t){for(let[e,n]of Object.entries(Oe))if(n===t)return e}i(Rn,"nppErrorCodeName");function Pt(t){for(let[e,n]of Object.entries(ve))if(n===t)return e}i(Pt,"bulkAckStatusName");function ie(t,e){let n=M(t);if(n.frameType!==y.ERROR)throw new Error(`decodeErrorSideband: expected frameType=ERROR (0x11), got 0x${n.frameType.toString(16).padStart(2,"0")}`);if(n.payloadLen<2)throw new RangeError(`ERROR sideband payload too small: ${n.payloadLen}`);let r=n.headerLen,o=r+n.payloadLen;if(t.byteLength<o)throw new RangeError("ERROR sideband truncated");let s=new DataView(t.buffer,t.byteOffset,t.byteLength),c=new TextDecoder("utf-8",{fatal:!1});if(e!==void 0&&n.payloadLen>=Ut&&s.getBigUint64(r,!1)===e){let d=s.getUint16(r+8,!1);return{header:n,layout:"seq-linked",seq:e,code:d,name:Rn(d)??Pt(d),reason:c.decode(t.subarray(r+Ut,o))}}let a=s.getUint16(r,!1),u=c.decode(t.subarray(r+2,o));return{header:n,layout:"sideband",code:a,name:Rn(a),reason:u}}i(ie,"decodeErrorSideband");function Oi(t,e){if(t.byteLength-e<h)return;for(let u=0;u<oe.length;u+=1)if(t[e+u]!==oe[u])return;let n=new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),r=t[e+4],o=t[e+5],s=n.getUint16(6,!1),c=n.getUint32(12,!1);if(s<h)return;let a=s+c;if((o&W.EXTENDED_HEADER)!==0&&(a+=xr(o),r===y.HELLO_ACK&&(a+=Te)),r===y.HELLO_ACK&&(o&W.SESSION_PARAMS)!==0&&(a+=8+bn),!(e+a>t.byteLength))return a}i(Oi,"frameByteLengthAt");function xt(t){let e=[],n=0;for(;n<t.byteLength;){let r=Oi(t,n);if(r===void 0)return e.push(t.subarray(n)),e;e.push(t.subarray(n,n+r)),n+=r}return e.length>0?e:[t]}i(xt,"splitFrames");var wl=Ge-h;var yl=64*1024;function zr(t,e=15){let n=new Uint16Array(e+1);for(let s of t)n[s]+=1;n[0]=0;let r=new Uint16Array(e+2);for(let s=1;s<=e;s+=1)r[s+1]=r[s]+n[s];let o=new Uint16Array(t.length);for(let s=0;s<t.length;s+=1)t[s]!==0&&(o[r[t[s]]]=s,r[t[s]]+=1);return{counts:n,symbols:o}}i(zr,"buildHuffTable");var ml=(()=>{let t=new Uint8Array(288);for(let e=0;e<=143;e+=1)t[e]=8;for(let e=144;e<=255;e+=1)t[e]=9;for(let e=256;e<=279;e+=1)t[e]=7;for(let e=280;e<=287;e+=1)t[e]=8;return zr(t)})(),Rl=(()=>{let t=new Uint8Array(30).fill(5);return zr(t)})();var Pr=2;function Zr(t,e){if(e.reasonCode<0||e.reasonCode>65535)throw new RangeError(`GOODBYE reasonCode out of u16 range: ${e.reasonCode}`);let n=new Uint8Array(h+Pr);return n.set(Y({frameType:y.GOODBYE,flags:0,headerLen:h,sessionId:t,payloadLen:Pr}),0),new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(16,e.reasonCode,!1),n}i(Zr,"encodeGoodbye");function eo(t,e=new Uint8Array(0)){let n=new Uint8Array(h+e.byteLength);return n.set(Y({frameType:y.PONG,flags:0,headerLen:h,sessionId:t,payloadLen:e.byteLength}),0),e.byteLength>0&&n.set(e,h),n}i(eo,"encodePong");var bl=1024*1024;var je=16,Ci=144;var Ii=new Uint8Array([78,80,80,1]),Di={HELLO:0,HELLO_ACK:1,PUBLISH:2,PUBLISH_BATCH:3,BULK_ACK:4,SUBSCRIBE:5,DELIVER:6,DELIVER_BATCH:7,ACK:8,SEEK:9,FLOW_CREDIT:13,PING:14,PONG:15,GOODBYE:16,ERROR:17,SYS_EVENT:18,REKEY:19},Ui={COMPRESSED:1,ENCRYPTED:2,BATCH:4,URGENT:8,RESERVED_V2:16,EXTENDED_HEADER:32,PQ_HYBRID:64};function ki(t){if(t.byteLength<je)throw new RangeError(`frame too short for common header: ${t.byteLength} < ${je}`);for(let a=0;a<4;a+=1)if(t[a]!==Ii[a])throw new Error("npp: bad magic \u2014 not an NPP frame");let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=t[4],r=t[5],o=e.getUint16(6,!1),s=e.getUint32(8,!1),c=e.getUint32(12,!1);if(o<je)throw new RangeError(`headerLen below minimum: ${o} < ${je}`);return{frameType:n,flags:r,headerLen:o,sessionId:s,payloadLen:c}}i(ki,"decodeCommonHeader");var ae=Ci,Pi=3309;var xi=32,Mi="traceparent",Mt={STRING:0,NUMBER:1,BOOL:2,NULL:3};function $i(t,e){let n=new TextDecoder;switch(t){case Mt.STRING:return n.decode(e);case Mt.NUMBER:return Number(n.decode(e));case Mt.BOOL:return e[0]===1;case Mt.NULL:return null;default:throw new RangeError(`DELIVER attribute: unknown value tag 0x${t.toString(16)}`)}}i($i,"decodeAttrValue");function Bi(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new TextDecoder,o=[],s=0;for(let c=0;c<e;c+=1){if(s+4>t.byteLength)throw new RangeError(`DELIVER attribute ${c} header truncated`);let a=n.getUint16(s,!1),u=n.getUint16(s+2,!1);if(s+=4,u<1||s+a+u>t.byteLength)throw new RangeError(`DELIVER attribute ${c} body truncated`);let d=r.decode(t.slice(s,s+a));s+=a;let f=t[s],l=$i(f,t.slice(s+1,s+u));s+=u,o.push({key:d,value:l})}return{attributes:o,byteLength:s}}i(Bi,"decodeDeliverAttributes");var Nl=new Uint8Array([78,80,80,84]);function Ki(t){if(t.byteLength<80)throw new RangeError(`envelope too short for signing input: ${t.byteLength}`);return t.slice(8,80)}i(Ki,"canonicalDeliverSigningInput");function Hi(t){if(t.byteLength<ae)throw new RangeError(`bytes too short for DELIVER envelope: ${t.byteLength} < ${ae}`);let e=ki(t);if(e.frameType!==Di.DELIVER)throw new Error(`decodeDeliverFrame: expected frameType=DELIVER (0x06), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(16,!1),o=n.getUint32(20,!1),s=n.getBigUint64(24,!1),c=n.getBigUint64(32,!1),a=n.getUint32(40,!1),u=t[44],d=t[45],f=n.getUint16(46,!1),l=t.slice(48,80),m=t.slice(80,144),g=ae-je,w=e.payloadLen-g;if(w<0)throw new RangeError(`DELIVER payloadLen header (${e.payloadLen}) smaller than envelope body (${g})`);let R=ae+w;if(t.byteLength<R)throw new RangeError(`DELIVER frame truncated: have ${t.byteLength}, expected >= ${R}`);let C=[],b=ae;if(f>0&&(e.flags&xi)!==0){let v=Bi(t.slice(ae,R),f);C=v.attributes,b=ae+v.byteLength}let O=R,T=t.slice(b,O),I=C.find(v=>v.key===Mi),H=typeof I?.value=="string"?I.value:void 0,_=null;if(e.flags&Ui.PQ_HYBRID){let v=O,p=v+Pi;if(t.byteLength<p)throw new RangeError(`DELIVER frame PQ_HYBRID flag set but Dilithium sig truncated: have ${t.byteLength}, expected >= ${p}`);_=t.slice(v,p)}let L=Ki(t.slice(0,ae));return{flags:e.flags,sessionId:e.sessionId,channelId:r,partitionId:o,sequence:s,hlcTimestamp:c,schemaFingerprint:a,qosLevel:u,encryptionMode:d,attributesCount:f,attributes:C,traceparent:H,payloadHash:l,detachedSignature:m,payload:T,dilithiumSignature:_,signingInput:L}}i(Hi,"decodeDeliverFrame");var co=class extends Error{static{i(this,"CellError")}code;statusCode;constructor(t,e="CELL_ERROR",n=500){super(t),this.name="CellError",this.code=e,this.statusCode=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,statusCode:this.statusCode}}};var Fi=class extends co{static{i(this,"CellPlanRequiredError")}product;upgradeUrl;constructor(t,e={}){super(t,e.code??"PLAN_REQUIRED",402),this.name="CellPlanRequiredError",this.product=e.product,this.upgradeUrl=e.upgradeUrl}toJSON(){return{...super.toJSON(),...this.product!==void 0?{product:this.product}:{},...this.upgradeUrl!==void 0?{upgradeUrl:this.upgradeUrl}:{}}}},Vi=class extends co{static{i(this,"CellQuotaExceededError")}upgradeUrl;constructor(t,e={}){super(t,e.code??"QUOTA_EXCEEDED",429),this.name="CellQuotaExceededError",this.upgradeUrl=e.upgradeUrl}toJSON(){return{...super.toJSON(),...this.upgradeUrl!==void 0?{upgradeUrl:this.upgradeUrl}:{}}}};function kn(t){return`${t.thumbprint}\0${t.channelGid}`}i(kn,"nppSequenceKeyId");var Pn=class{static{i(this,"InMemoryNppSequenceStore")}states=new Map;tails=new Map;async exclusive(t,e){let n=kn(t),r=this.tails.get(n)??Promise.resolve(),o,s=new Promise(a=>{o=a}),c=r.then(()=>s);this.tails.set(n,c),await r;try{return await e({load:i(async()=>({...this.states.get(n)??{lastAccepted:0n}}),"load"),save:i(async a=>{this.states.set(n,{...a})},"save")})}finally{o(),this.tails.get(n)===c&&this.tails.delete(n)}}},ze=new Pn,qi=0,Wi=1,Gi=2,ji=3,Ji=16,Yi=17,Xi="another process signing with this credential's key already stored this sequence on the channel with an identical payload; this publish was NOT stored as a new message. The producer moved past it \u2014 publish again to store it.",Qi="another process signing with this credential's key already used this sequence on the channel (a different HOME, container or host holding the same credential); this publish was NOT stored. The producer moved past it.",zi="the broker's last accepted sequence for this producer on the channel is lower than this producer recorded; the producer rewound, and the next publish restarts the sequence.";async function Ze(t,e,n){return t.exclusive(e,async r=>{let o=await r.load();for(let s=!1;;s=!0){let c=o.lastAccepted+1n,a=o.inFlight===c;await r.save({lastAccepted:o.lastAccepted,inFlight:c});let u=await n(c);switch(u.status){case qi:case Gi:case ji:return await r.save({lastAccepted:c}),{answer:u,sequence:c,verdict:{kind:"stored"}};case Wi:return await r.save({lastAccepted:c}),a||u.retried===!0?{answer:u,sequence:c,verdict:{kind:"stored"}}:{answer:u,sequence:c,verdict:{kind:"conflict",reason:Xi}};case Yi:if(await r.save({lastAccepted:c}),a&&!s){o={lastAccepted:c};continue}return{answer:u,sequence:c,verdict:{kind:"conflict",reason:Qi}};case Ji:return await r.save({lastAccepted:0n}),{answer:u,sequence:c,verdict:{kind:"rewound",reason:zi}};default:return{answer:u,sequence:c,verdict:{kind:"unsettled"}}}}})}i(Ze,"publishAtNextSequence");var $t="KERNEL_DOOR_URL",Qe=8,D={ACK_CLASS:1,PRODUCER_EPOCH:2,BYTE_CREDIT:4,SUBSCRIPTION_HANDLE:5,POSITION:6,PARTITION:7,ROUTE_EPOCH:8,ENGINE_INFO:9,ACK_STRIDE:11,RECORD_KEY:16,TENANT_SELECT:17,CURSOR_ID:18,NACK_DELAY_MS:19,INITIAL_CREDIT:20,LINK_ORIGIN:21,MESSAGE_GID:22},Zi={2:"ACCEPTED_LOCAL",3:"ACCEPTED_GEO",81:"DEFERRED_UNDER_REPLICATED",82:"REJECTED_ROUTE_EPOCH",83:"REJECTED_CLASS_UNAVAILABLE",84:"REJECTED_WRONG_PARTITION",85:"REJECTED_NOT_PRIMARY",105:"REJECTED_PRODUCER_EPOCH"},to=85,no=255,ro=250,ea=1e3,uo="plan_required",fo="internal_apps",Nn="/settings/billing";function lo(t){let e=t.indexOf(":");return e<0?t:t.slice(0,e)}i(lo,"reasonToken");function po(t){return lo(t)===uo}i(po,"isKernelPlanRefusal");var ho="quota_exceeded",On="/settings/billing";function Eo(t){return lo(t)===ho}i(Eo,"isKernelQuotaRefusal");var go=class extends Fi{static{i(this,"KernelPlanRequiredError")}kernelStatus;kernelStatusName;kernelReason;constructor(t,e){super("PLAN_REQUIRED: this app publishes only on a plan, so the message was not published; choose a plan at "+Nn,{code:"PLAN_REQUIRED",product:fo,upgradeUrl:Nn}),this.name="KernelPlanRequiredError",this.kernelStatus=t,this.kernelStatusName=Q(t)??Ye(t),this.kernelReason=e}},wo=class extends Vi{static{i(this,"KernelQuotaExceededError")}kernelStatus;kernelStatusName;kernelReason;constructor(t,e){super(`QUOTA_EXCEEDED: this organization's usage is past its allowance and it has no payment method on file, so the message was not published; add a payment method or choose a plan at ${On}`,{code:"QUOTA_EXCEEDED",upgradeUrl:On}),this.name="KernelQuotaExceededError",this.kernelStatus=t,this.kernelStatusName=Q(t)??Ye(t),this.kernelReason=e}},ta=258,yo=3,Je=new Set([0,1,2,3]);function Q(t){return Pt(t)??Zi[t]}i(Q,"kernelStatusName");var A=16,Sn=22,oo=0xffffffffffffffffn,E=class extends Error{static{i(this,"KernelDoorError")}code;reasonCode;reasonName;constructor(t,e,n){if(super(e),this.name="KernelDoorError",this.code=t,n!==void 0){this.reasonCode=n;let r=Q(n)??mo[n];r!==void 0&&(this.reasonName=r)}}},mo={1:"REJECTED_VERSION",2:"REJECTED_QOS",498:"FRAME_MALFORMED",499:"PROTOCOL_VIOLATION",500:"UPSTREAM_REFUSED",501:"UNSUPPORTED",502:"SESSION_EXPIRED"};function Ye(t){return`0x${t.toString(16).padStart(4,"0")}`}i(Ye,"hex16");function na(){return globalThis.process?.env??{}}i(na,"processEnv");function so(t,e){let n=e==="option"?"the door option":$t,r;try{r=new URL(t)}catch{throw new E("KERNEL_DOOR_CONFIG",`${n} is not a URL: ${JSON.stringify(t)}`)}if(r.protocol==="wss:")return{kind:"kernel",url:r.toString(),source:e};if(e==="option"&&(r.protocol==="https:"||r.protocol==="http:"))return{kind:"edge",url:t,source:e};throw new E("KERNEL_DOOR_CONFIG",`${n} must be a wss:// kernel door (TLS 1.3)${e==="option"?" or the http(s):// edge door":""}; got ${r.protocol}//`)}i(so,"classifyDoor");function Ro(t={}){if(t.door!==void 0&&t.door.trim()!=="")return so(t.door.trim(),"option");let n=(t.env??na())[$t];return n!==void 0&&n.trim()!==""?so(n.trim(),"env"):{kind:"edge",url:t.edgeUrl,source:"default"}}i(Ro,"resolveDoor");function de(t){if(t.byteLength<A)throw new RangeError("frame shorter than the common header");let n=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(6,!1);if(n<A||n>t.byteLength)throw new RangeError(`bad headerLen ${n}`);let r=[],o=A;for(;o<n;){if(o+2>n)throw new RangeError("TLV region does not fill headerLen exactly");let c=t[o],a=t[o+1];if(o+2+a>n)throw new RangeError("TLV region does not fill headerLen exactly");r.push({type:c,value:t.slice(o+2,o+2+a)}),o+=2+a}if(n===A)return{canonical:t,tlvs:r};let s=new Uint8Array(t.byteLength-(n-A));return s.set(t.subarray(0,A),0),s.set(t.subarray(n),A),new DataView(s.buffer).setUint16(6,A,!1),{canonical:s,tlvs:r}}i(de,"stripKernelTlvs");function Ie(t,e){if(e.length===0)return t;if(new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(6,!1)!==A)throw new RangeError("insertKernelTlvs expects a canonical frame");let r=0;for(let a of e){if(a.value.byteLength>255)throw new RangeError(`TLV 0x${a.type.toString(16)} value longer than 255 bytes`);r+=2+a.value.byteLength}let o=A+r;if(o>65535)throw new RangeError("TLV region too large");let s=new Uint8Array(t.byteLength+r);s.set(t.subarray(0,A),0);let c=A;for(let a of e)s[c]=a.type,s[c+1]=a.value.byteLength,s.set(a.value,c+2),c+=2+a.value.byteLength;return s.set(t.subarray(A),c),new DataView(s.buffer).setUint16(6,o,!1),s}i(Ie,"insertKernelTlvs");function ra(t){return Uint8Array.of(t&255)}i(ra,"tlvU8");function Ce(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t>>>0,!1),e}i(Ce,"tlvU32");function oa(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,t,!1),e}i(oa,"tlvU64");function Xe(t,e){return t.find(n=>n.type===e)?.value}i(Xe,"findTlv");function io(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1)}i(io,"readU32");function Bt(t,e){let n=Xe(e,D.ACK_STRIDE);if(!n||n[0]!==Sn)return Wr(t).records.map(c=>({seq:c.seq,status:c.status}));let r=M(t);if(r.payloadLen%Sn!==0||A+r.payloadLen>t.byteLength)throw new RangeError("positioned BULK_ACK records do not fill payloadLen");let o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=[];for(let c=A;c<A+r.payloadLen;c+=Sn)s.push({seq:o.getBigUint64(c,!1),status:o.getUint16(c+8,!1),position:{partition:o.getUint32(c+10,!1),offset:o.getBigUint64(c+14,!1)}});return s}i(Bt,"readKernelBulkAck");function Kt(t){let e=Xe(t,D.MESSAGE_GID);return e&&e.byteLength>0?Mn.decode(e):void 0}i(Kt,"readKernelMessageGid");var bo=3e4,Lo=250;function sa(t){let e=i(n=>n!==null&&typeof n=="object"&&!Array.isArray(n),"isDoc");return e(t)?[t,t.channel,t.data].filter(e):[]}i(sa,"channelAnswerDocs");async function xn(t,e={}){let n=e.waitMs??bo,r=e.pollMs??Lo,o=Date.now()+n;for(;;){let s;try{s=await t()}catch(u){return{refused:"read",detail:`the read of its answer was refused (${u instanceof Error?u.message:String(u)})`}}let c=sa(s);if(c.map(u=>u.engine).find(u=>typeof u=="string")==="convex")return{refused:"convex",detail:"its answer names the engine convex, which has no kernel table"};let a=c.map(u=>u.kernelTableId).find(u=>typeof u=="number"&&Number.isInteger(u)&&u>=0&&u<=4294967295);if(a!==void 0)return{table:a};if(Date.now()+r>o)return{refused:"pending",detail:`its answer named no kernelTableId within ${n} ms (the compile still pending)`};await new Promise(u=>setTimeout(u,r))}}i(xn,"resolveKernelTableId");function ia(t,e){try{for(let n of e){let r=ie(t,n);if(r.layout==="seq-linked")return r}return ie(t)}catch{return}}i(ia,"decodeLinkedError");async function _o(t){let e=await In(t.payload),n={frameType:y.PUBLISH,flags:0,headerLen:A,sessionId:t.sessionId,payloadLen:t.payload.byteLength},r={channelId:t.table,partitionId:t.partition,sequence:t.seq,hlcTimestamp:0n,schemaFingerprint:0,qosLevel:t.qosLevel??1,encryptionMode:0,attributesCount:0,payloadHash:e,detachedSignature:new Uint8Array(64)},o=Ln(n,r),s=await t.sign(kt(o));if(s.byteLength!==64)throw new RangeError(`a PUBLISH signature is 64 bytes, got ${s.byteLength}`);let c=Ln(n,{...r,detachedSignature:s}),a=new Uint8Array(c.byteLength+t.payload.byteLength);return a.set(c,0),a.set(t.payload,c.byteLength),t.tlvs&&t.tlvs.length>0?Ie(a,t.tlvs):a}i(_o,"encodeKernelPublishFrame");var Tn=64;function So(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.byteLength<se||e.getUint16(6,!1)!==A)throw new RangeError("a SUBSCRIBE signing input is read from the canonical form (headerLen 16, a 32-byte body)");let n=A+e.getUint32(12,!1),r=se;for(let o=0,s=t[A+28];o<s;o++){if(r+3>n)throw new RangeError("a SUBSCRIBE filter runs past the body");r+=3+(t[r+1]<<8|t[r+2])}if(r>n)throw new RangeError("a SUBSCRIBE filter runs past the body");return t.slice(8,r)}i(So,"kernelSubscribeSigningInput");async function To(t){let e;if(t.sign){e=Ne({sessionId:t.sessionId,envelope:t.envelope,consumerSignature:new Uint8Array(Tn)});let n=await t.sign(So(e));if(n.byteLength!==Tn)throw new RangeError(`a SUBSCRIBE consumerSignature is 64 bytes, got ${n.byteLength}`);e.set(n,e.byteLength-Tn)}else e=Ne({sessionId:t.sessionId,envelope:t.envelope});return t.tlvs&&t.tlvs.length>0?Ie(e,t.tlvs):e}i(To,"encodeKernelSubscribeFrame");var An=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function X(t){let e="",n=0;for(;n+2<t.length;n+=3){let r=t[n]<<16|t[n+1]<<8|t[n+2];e+=ce[r>>18&63]+ce[r>>12&63]+ce[r>>6&63]+ce[r&63]}if(n<t.length){let r=t[n]<<16|(n+1<t.length?t[n+1]:0)<<8;e+=ce[r>>18&63]+ce[r>>12&63],n+1<t.length&&(e+=ce[r>>6&63])}return e}i(X,"b64u");function Ht(t){let e=t.replace(/=+$/,""),n=[],r=0,o=0;for(let s of e){let c=ce.indexOf(s==="+"?"-":s==="/"?"_":s);if(c<0)throw new RangeError("not base64url");r=r<<6|c,o+=6,o>=8&&(o-=8,n.push(r>>o&255))}return Uint8Array.from(n)}i(Ht,"b64uDecode");function aa(t){let e=t.split(".")[1];if(e)try{let n=JSON.parse(Mn.decode(Ht(e)));return typeof n.npk_unit=="string"?n.npk_unit:void 0}catch{return}}i(aa,"tokenUnitOf");function ca(t){let e=X(t).replace(/-/g,"+").replace(/_/g,"/");return e+"=".repeat((4-e.length%4)%4)}i(ca,"b64std");var ue=new TextEncoder,Mn=new TextDecoder;function De(){let t=globalThis.crypto;if(!t?.subtle)throw new E("KERNEL_DOOR_CONFIG","Web Crypto (globalThis.crypto.subtle) is not available");return t.subtle}i(De,"subtle");function Cn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}i(Cn,"randomBytes");async function In(t){return new Uint8Array(await De().digest("SHA-256",t))}i(In,"sha256");var ua=class Dn{static{i(this,"_KernelDoorKey")}jkt;publicKeyRaw;privateKey;constructor(e,n,r){this.privateKey=e,this.publicKeyRaw=n,this.jkt=r}static async fromSeed(e){if(e.byteLength!==32)throw new RangeError("an Ed25519 seed is 32 bytes");let n=new Uint8Array(An.byteLength+32);n.set(An,0),n.set(e,An.byteLength);let r=await De().importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await De().exportKey("jwk",r);if(typeof o.x!="string")throw new E("KERNEL_DOOR_CONFIG","Ed25519 key export carried no public x");let s=Ht(o.x),c=`{"crv":"Ed25519","kty":"OKP","x":"${X(s)}"}`,a=X(await In(ue.encode(c)));return new Dn(r,s,a)}static async generate(){return Dn.fromSeed(Cn(32))}async sign(e){return new Uint8Array(await De().sign({name:"Ed25519"},this.privateKey,e))}async dpopProof(e,n,r=Date.now()){let o={typ:"dpop+jwt",alg:"EdDSA",jwk:{kty:"OKP",crv:"Ed25519",x:X(this.publicKeyRaw)}},s={jti:X(Cn(16)),htm:"POST",htu:`https://${e}/v1/npp`,iat:Math.floor(r/1e3),ath:X(await In(ue.encode(n)))},c=`${X(ue.encode(JSON.stringify(o)))}.${X(ue.encode(JSON.stringify(s)))}`;return`${c}.${X(await this.sign(ue.encode(c)))}`}},Ao="pass nodeKeys: the JWKS the kernel serves at GET /.well-known/npp-cell-jwks.json on its control door, its https:// URL, or the raw 32-byte Ed25519 key";function da(t){if(t==null)throw new E("KERNEL_DOOR_CONFIG",`no node key source to verify the HELLO_ACK with: ${Ao}`);if(t instanceof Uint8Array){if(t.byteLength!==32)throw new E("KERNEL_DOOR_CONFIG",`a raw node key is 32 bytes (Ed25519), got ${t.byteLength}`);return{raws:[t]}}if(typeof t=="string"){let e;try{e=new URL(t)}catch{throw new E("KERNEL_DOOR_CONFIG",`nodeKeys is not a URL: ${JSON.stringify(t)}`)}if(e.protocol!=="https:")throw new E("KERNEL_DOOR_CONFIG",`a node JWKS URL must be https://, got ${e.protocol}//`);return{url:e.toString()}}return{raws:vo(t)}}i(da,"classifyNodeKeys");function vo(t){let e=t?.keys;if(!Array.isArray(e))throw new E("KERNEL_DOOR_CONFIG",`nodeKeys is not a JWKS document (no keys array): ${Ao}`);let n=[];for(let r of e){if(r?.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.x!="string"||r.use!==void 0&&r.use!=="sig")continue;let o;try{o=Ht(r.x)}catch{continue}o.byteLength===32&&n.push(o)}if(n.length===0)throw new E("KERNEL_DOOR_CONFIG","the node key set holds no Ed25519 signing key (kty OKP, crv Ed25519)");return n}i(vo,"ed25519KeysOf");async function ao(t){let e=[];for(let n of t)try{e.push(await De().importKey("raw",n,{name:"Ed25519"},!1,["verify"]))}catch{}if(e.length===0)throw new E("KERNEL_DOOR_CONFIG","none of the node keys is a usable Ed25519 public key");return e}i(ao,"importVerifyKeys");async function fa(t,e){let n=da(t);if("raws"in n)return ao(n.raws);let r=e??globalThis.fetch;if(typeof r!="function")throw new E("KERNEL_DOOR_CONFIG",`no fetch to read the node JWKS at ${n.url}; pass the JWKS document instead`);let o;try{let s=await r(n.url,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`HTTP ${s.status}`);o=await s.json()}catch(s){throw new E("KERNEL_DOOR_UNAVAILABLE",`could not read the node JWKS at ${n.url}: ${s.message}`)}return ao(vo(o))}i(fa,"loadNodeVerifyKeys");async function la(t,e,n){for(let r of t)try{if(await De().verify({name:"Ed25519"},r,e,n))return!0}catch{}return!1}i(la,"verifiesUnderAny");function pa(){let t=globalThis.WebSocket;if(typeof t!="function")throw new E("KERNEL_DOOR_UNAVAILABLE","no global WebSocket in this runtime; pass the `webSocket` factory option (Node < 22: the `ws` package)");return e=>new t(e)}i(pa,"defaultWebSocketFactory");async function ha(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(typeof t=="string"){try{let n=JSON.parse(t);if(n.type==="npp_frame"&&n.encoding==="base64"&&typeof n.data=="string")return Ht(n.data)}catch{return null}return null}let e=t;return typeof e?.arrayBuffer=="function"?new Uint8Array(await e.arrayBuffer()):null}i(ha,"messageBytes");function No(t){let e=t.find(n=>n.key==="npp_delivery_token")?.value;if(!(typeof e!="string"||!/^[0-9a-fA-F]{32}$/.test(e)))return{hi:BigInt(`0x${e.slice(0,16)}`),lo:BigInt(`0x${e.slice(16)}`)}}i(No,"deliveryTokenOf");function Ea(t){if(t===void 0)return{answered:!1,accepted:!1};let e=Q(t.status)??(t.error?mo[t.status]:void 0);return{answered:!0,accepted:!t.error&&Je.has(t.status),statusCode:t.status,...e!==void 0?{statusName:e}:{},...t.reason?{reason:t.reason}:{}}}i(Ea,"ackResultOf");function ga(t){if(t===void 0||t==="beginning")return 0n;if(t==="end")return oo;let e=typeof t=="bigint"?t:t.offset;if(e<0n||e>=oo-1n)throw new RangeError(`start offset out of range: ${e} (0 \u2264 offset < 2^64 \u2212 2)`);return e}i(ga,"startCursorOf");function vn(t,e){return`${t}/${e}`}i(vn,"partitionKey");function wa(){let t={parkedAt:void 0,moved:Promise.resolve(),wake:i(()=>{},"wake")};return t.moved=new Promise(e=>{t.wake=e}),t}i(wa,"newFlight");function ya(t,e){t.parkedAt=e;let n=t.wake;t.moved=new Promise(r=>{t.wake=r}),n()}i(ya,"park");function ma(t,e){return{resolve:i(n=>{e.parkedAt=void 0,t.resolve(n)},"resolve"),reject:i(n=>{e.parkedAt=void 0,t.reject(n)},"reject")}}i(ma,"unparking");var Ra=/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?):(\d{1,5})$/;function ba(t,e){let n=Ra.exec(e);if(!n)return;let r=Number(n[1]);if(r<1||r>65535)return;let o=new URL(t);return o.host=e,o.toString()}i(ba,"redirectDoor");var Oo=class{static{i(this,"KernelSubscription")}constructor(t,e,n,r,o,s){this.session=t,this.table=e,this.handle=n,this.partition=r,this.creditFrames=o,this.creditBytes=s}queue=[];waiters=[];ended;push(t){let e=this.waiters.shift();e?e.resolve(t):this.queue.push(t)}end(t){if(this.ended===void 0){this.ended=t;for(let e of this.waiters.splice(0))t?e.reject(t):e.resolve(null)}}async next(t=3e4){let e=this.queue.shift();if(e)return this.handOut(e);if(this.ended!==void 0){if(this.ended)throw this.ended;return null}let n=await new Promise((r,o)=>{let s=setTimeout(()=>{let a=this.waiters.indexOf(c);a>=0&&this.waiters.splice(a,1),o(new E("KERNEL_DOOR_TIMEOUT",`no delivery within ${t} ms`))},t),c={resolve:i(a=>{clearTimeout(s),r(a)},"resolve"),reject:i(a=>{clearTimeout(s),o(a)},"reject")};this.waiters.push(c)});return n?this.handOut(n):null}handOut(t){return this.session.sendCredit(this.table,this.handle,1,0),t}ack(t){return this.session.sendAck(this.table,this.handle,t.partition,t.offset,t.deliveryToken)}credit(t,e=0){this.session.sendCredit(this.table,this.handle,t,e)}open(){this.session.sendCredit(this.table,this.handle,this.creditFrames,this.creditBytes)}async*[Symbol.asyncIterator](){for(;;){let t=await this.next(2147483647);if(t===null)return;yield t}}},La=class Un{static{i(this,"_KernelDoorSession")}sessionId;negotiatedCapabilities;door;ws;key;timeoutMs;options;followRedirects;sequenceStore;publishes=new Map;publishPartitions=new Map;awaitingReason=new Map;primaryHints=new Map;links=new Map;routes=new Map;lanes=new Map;owed=[];reasonDueBy;ackDeadline;subscriptions=[];closedWith;goodbyeWaiter;constructor(e){this.ws=e.ws,this.key=e.key,this.door=e.door,this.sessionId=e.sessionId,this.negotiatedCapabilities=e.negotiatedCapabilities,this.timeoutMs=e.timeoutMs,this.options=e.options,this.followRedirects=e.options.followRedirects===!0,this.sequenceStore=e.options.sequenceStore??ze}get engineExt(){return(this.negotiatedCapabilities&Qe)!==0}static async connect(e){let n=Ro({door:e.door,env:e.env});if(n.kind!=="kernel"||n.url===void 0)throw new E("KERNEL_DOOR_UNAVAILABLE",`no kernel door configured: pass the door option (wss://host:port/v1/npp) or set ${$t}`);let r=n.url;if(!e.dpop&&!e.key)throw new E("KERNEL_DOOR_CONFIG","a kernel session needs `key` or `dpop` to sign its HELLO's DPoP proof");let o=await fa(e.nodeKeys,e.fetch),s=e.timeoutMs??15e3,c=e.webSocket??pa(),a=new URL(r).host,u;try{u=c(r)}catch(_){throw new E("KERNEL_DOOR_UNAVAILABLE",`could not open ${r}: ${_.message}`)}u.binaryType="arraybuffer";let d=[],f,l,m,g=Promise.resolve();u.addEventListener("message",_=>{g=g.then(async()=>{let L=await ha(_.data);L&&(f?f.onFrame(L):l?l.resolve(L):d.push(L))})}),u.addEventListener("close",_=>{g=g.then(()=>{let L=new E("KERNEL_DOOR_UNAVAILABLE",`the kernel door closed the connection (code ${_?.code??"?"}${_?.reason?`: ${_.reason}`:""})`);f?f.onClosed(L):(m=L,l?.reject(L))})}),await new Promise((_,L)=>{let v=setTimeout(()=>L(new E("KERNEL_DOOR_TIMEOUT",`${r} did not open within ${s} ms`)),s);u.addEventListener("open",()=>{clearTimeout(v),_()}),u.addEventListener("error",p=>{clearTimeout(v),L(new E("KERNEL_DOOR_UNAVAILABLE",`could not connect to ${r}${p?.error?.message??p?.message?`: ${p?.error?.message??p?.message}`:""}`))})});let w=Cn(32),R=e.dpop,C=e.key,b=ue.encode(JSON.stringify({access_token:e.accessToken,dpop:R?await R.proof(`https://${a}/v1/npp`,e.accessToken):await C.dpopProof(a,e.accessToken),jkt:R?R.jkt:C.jkt,nonce:ca(w),...e.unit!==void 0?{unit:e.unit}:{},...e.sessionTtlSec!==void 0?{sessionTtlSec:e.sessionTtlSec}:{},...e.followRedirects===!0?{redirectOk:!0}:{}})),O=Fr({sessionId:0,nppVersionMajor:$r,nppVersionMinor:Br,capabilityFlags:Qe|Mr.HLC,qosCapabilities:1,authBody:b}),T=e.producerEpoch===void 0?[]:[{type:D.PRODUCER_EPOCH,value:Ce(e.producerEpoch)}];u.send(Ie(O,T));let I=Date.now()+s,H=i(()=>{if(m)return Promise.reject(m);let _=d.shift();return _?Promise.resolve(_):new Promise((L,v)=>{let p=setTimeout(()=>{l=void 0,v(new E("KERNEL_DOOR_TIMEOUT",`no HELLO_ACK within ${s} ms`))},Math.max(1,I-Date.now()));l={resolve:i(P=>{clearTimeout(p),l=void 0,L(P)},"resolve"),reject:i(P=>{clearTimeout(p),l=void 0,v(P)},"reject")}})},"nextEarly");try{for(;;){let _=await H(),{canonical:L}=de(_),v=M(L);if(v.frameType===y.ERROR){let U=Qr(L).frame;throw new E("KERNEL_DOOR_REFUSED",`HELLO refused: ${Ye(U.reasonCode)}`,U.reasonCode)}if(v.frameType===y.GOODBYE)throw new E("KERNEL_DOOR_REFUSED","the kernel said GOODBYE before HELLO_ACK");if(v.frameType!==y.HELLO_ACK)continue;let p=qr(L);if(!p.nonceEcho||!p.serverSignature)throw new E("KERNEL_DOOR_PROTOCOL","HELLO_ACK carries no node signature trailer (nonceEcho + signature)");let P=!1;for(let U of Vr(L))if(await la(o,p.serverSignature,U)){P=!0;break}if(!P)throw new E("KERNEL_DOOR_PROTOCOL","HELLO_ACK node signature does not verify against the node's published keys");if(!_a(p.nonceEcho,w))throw new E("KERNEL_DOOR_PROTOCOL","HELLO_ACK nonceEcho is not this connection's nonce");if(p.sessionId===0)throw new E("KERNEL_DOOR_PROTOCOL","HELLO_ACK sessionId MUST be non-zero");f=new Un({ws:u,key:e.key,door:r,sessionId:p.sessionId,negotiatedCapabilities:p.negotiatedCapabilities,timeoutMs:s,options:{...e,door:r,env:{}}});for(let U of d.splice(0))f.onFrame(U);return f}}catch(_){try{u.close()}catch{}throw _ instanceof E?_:new E("KERNEL_DOOR_PROTOCOL",`bad HELLO answer: ${_.message}`)}}send(e){if(this.closedWith!==void 0)throw this.closedWith??new E("KERNEL_DOOR_UNAVAILABLE","the session is closed");this.ws.send(e)}wait(e,n,r){return new Promise((o,s)=>{let c=setTimeout(()=>{n(),s(new E("KERNEL_DOOR_TIMEOUT",`no ${r} within ${this.timeoutMs} ms`))},this.timeoutMs);e({resolve:i(a=>{clearTimeout(c),o(a)},"resolve"),reject:i(a=>{clearTimeout(c),s(a)},"reject")})})}async publish(e){if(e.seq!==void 0)return this.publishAt({...e,seq:e.seq});if(this.closedWith!==void 0)throw this.closedWith??new E("KERNEL_DOOR_UNAVAILABLE","the session is closed");let{answer:n,sequence:r,verdict:o}=await Ze(this.sequenceStore,this.producerScope(e),c=>this.publishAt({...e,seq:c}).then(a=>({result:a,status:a.statusCode}))),{result:s}=n;return o.kind==="stored"?{...s,accepted:!0}:o.kind==="unsettled"?s:{accepted:!1,statusCode:s.statusCode,statusName:s.statusName,sequence:s.sequence,...s.position?{position:s.position}:{},sequenceConflict:{sequence:r,reason:o.reason}}}producerScope(e){let n=this.options,r=n.producerEpoch!==void 0?`epoch ${n.producerEpoch}`:`session ${this.sessionId}`;return{thumbprint:n.dpop?.jkt??this.key?.jkt??"",channelGid:`kernel:${n.unit??aa(n.accessToken)??""}/${e.table}/${e.partition}@${r}`}}async publishAt(e){if(e.seq<1n)throw new RangeError("seq must be \u2265 1 (seq 0 is the SUBSCRIBE acceptance record)");if(this.closedWith!==void 0)throw this.closedWith??new E("KERNEL_DOOR_UNAVAILABLE","the session is closed");let n=vn(e.table,e.partition),r=this.joinLane(n);try{if(!this.followRedirects)return(await this.publishOnce(e,r)).result;let o=await this.routeFor(n);for(let s=0;;s+=1){let{result:c,primary:a}=await o.publishOnce(e,r);if(c.statusCode!==to||a===void 0||s>=yo)return c;let u=ba(o.door,a.authority);if(u===void 0)return c;o=await this.linkTo(u),o===this?this.routes.delete(n):this.routes.set(n,u)}}finally{this.leaveLane(r)}}joinLane(e){let n=wa(),r=this.lanes.get(e);return r?r.push(n):this.lanes.set(e,[n]),{origin:this,key:e,flight:n}}leaveLane(e){let n=this.lanes.get(e.key),r=n?n.indexOf(e.flight):-1;n&&r>=0&&(n.splice(r,1),n.length===0&&this.lanes.delete(e.key)),e.flight.wake()}async turnAt(e,n){for(;;){let r=this.lanes.get(e.key)??[],o=r.indexOf(e.flight),s=o<0?void 0:r.slice(0,o).find(c=>c.parkedAt!==n);if(s===void 0)return;await s.moved}}async routeFor(e){let n=this.routes.get(e);if(n===void 0)return this;let r=await this.links.get(n)?.catch(()=>{});return r!==void 0&&r.closedWith===void 0?r:(this.routes.delete(e),this.primaryHints.delete(e),this)}async linkTo(e){if(e===this.door)return this;let n=this.links.get(e);if(n!==void 0){let o=await n.catch(()=>{});if(o!==void 0&&o.closedWith===void 0)return o;if(this.links.get(e)!==n)return this.linkTo(e);this.links.delete(e)}let r=Un.connect({...this.options,door:e,env:{}});this.links.set(e,r);try{return await r}catch(o){throw this.links.get(e)===r&&this.links.delete(e),o}}async publishOnce(e,n){if(e.seq<1n)throw new RangeError("seq must be \u2265 1 (seq 0 is the SUBSCRIBE acceptance record)");if(this.publishes.has(e.seq))throw new RangeError(`a PUBLISH with seq ${e.seq} is already waiting for its ack`);let r=[];e.ackClass!==void 0&&r.push({type:D.ACK_CLASS,value:ra(e.ackClass)}),e.key&&r.push({type:D.RECORD_KEY,value:e.key}),e.tenant!==void 0&&r.push({type:D.TENANT_SELECT,value:ue.encode(e.tenant)});let o=this.key;if(!o)throw new E("KERNEL_DOOR_CONFIG","a PUBLISH is signed with the session key: connect with `key` to publish");let s=await _o({sessionId:this.sessionId,table:e.table,partition:e.partition,seq:e.seq,payload:e.payload,sign:i(a=>o.sign(a),"sign"),...this.engineExt?{tlvs:r}:{}});if(await n.origin.turnAt(n,this.door),this.closedWith!==void 0)throw this.closedWith??new E("KERNEL_DOOR_UNAVAILABLE","the session is closed");if(this.publishes.has(e.seq))throw new RangeError(`a PUBLISH with seq ${e.seq} is already waiting for its ack`);let c=this.wait(a=>{this.publishes.set(e.seq,ma(a,n.flight)),this.publishPartitions.set(e.seq,vn(e.table,e.partition))},()=>{this.publishes.delete(e.seq),this.publishPartitions.delete(e.seq),n.flight.parkedAt=void 0},`BULK_ACK for seq ${e.seq}`);return this.send(s),ya(n.flight,this.door),c}async subscribe(e){if(this.owed.some(f=>f.kind==="subscribe"))throw new RangeError("a SUBSCRIBE is already waiting for its acceptance");let n=e.mode==="queue";if(n&&(e.cursorId===void 0||!this.engineExt))throw new E("KERNEL_DOOR_CONFIG",e.cursorId===void 0?"a queue SUBSCRIBE names its durable cursor (cursorId, TLV CURSOR_ID)":"a queue SUBSCRIBE names its cursor in a TLV, which needs a session that negotiated ENGINE_EXT");let r=[];e.partition!==void 0&&r.push({type:D.PARTITION,value:Ce(e.partition)}),e.cursorId!==void 0&&r.push({type:D.CURSOR_ID,value:oa(e.cursorId)}),e.tenant!==void 0&&r.push({type:D.TENANT_SELECT,value:ue.encode(e.tenant)});let o=this.key,s=await To({sessionId:this.sessionId,...o?{sign:i(f=>o.sign(f),"sign")}:{},tlvs:r,envelope:{channelId:e.table,mode:n?1:0,deliveryPreference:n?2:0,qosCapabilities:1,partitionFilter:0,startCursor:e.cursorId!==void 0?0n:ga(e.from),startHlc:0n,filters:[]}});this.send(s);let c,a=await this.wait(f=>{c={kind:"subscribe",waiter:f},this.owed.push(c)},()=>this.forgetOwed(c),"SUBSCRIBE acceptance");if(a.error||!Je.has(a.status)){let f=a.error?Ye(a.status):Q(a.status)??Ye(a.status);throw new E("KERNEL_DOOR_REFUSED",`SUBSCRIBE refused: ${f}`,a.status)}let u=Xe(a.tlvs,D.SUBSCRIPTION_HANDLE),d=new Oo(this,e.table,u?io(u):void 0,e.partition,e.credit??64,e.creditBytes??4*1024*1024);return this.subscriptions.push(d),this.closedWith!==void 0?d.end(this.closedWith):d.open(),d}sendCredit(e,n,r,o){if(this.closedWith!==void 0)return;let s=Yr(this.sessionId,{channelId:e,creditDelta:r,projectedLagMs:0,bandwidthBudgetBps:0}),c=[];o>0&&c.push({type:D.BYTE_CREDIT,value:Ce(o)}),n!==void 0&&c.push({type:D.SUBSCRIPTION_HANDLE,value:Ce(n)}),this.send(this.engineExt?Ie(s,c):s)}sendAck(e,n,r,o,s){let c=Jr(this.sessionId,e,[{seq:o,disposition:0,...s?{deliveryToken:s}:{}}]),a=[{type:D.PARTITION,value:Ce(r)}];return n!==void 0&&a.push({type:D.SUBSCRIPTION_HANDLE,value:Ce(n)}),this.send(this.engineExt?Ie(c,a):c),new Promise(u=>{this.owed.push({kind:"ack",settle:i(d=>u(Ea(d)),"settle"),at:Date.now()}),this.armAckDeadline()})}answerOwed(e){let n;!e.error&&!Je.has(e.status)?n="subscribe":!e.error&&this.engineExt&&(n=Xe(e.tlvs,D.SUBSCRIPTION_HANDLE)?"subscribe":"ack");let r=n===void 0?this.owed.length>0?0:-1:this.owed.findIndex(s=>s.kind===n);if(r<0)return;let[o]=this.owed.splice(r,1);if(o.kind==="ack"){o.settle(e);return}for(let s of this.owed.splice(0,r))s.kind==="ack"&&s.settle(void 0);o.waiter.resolve(e)}controlError(e,n){let r=this.reasonDueBy;this.reasonDueBy=void 0,!(r!==void 0&&Date.now()<=r)&&this.answerOwed({status:e,tlvs:[],error:!0,reason:n})}forgetOwed(e){let n=e===void 0?-1:this.owed.indexOf(e);n>=0&&this.owed.splice(n,1)}armAckDeadline(){if(this.ackDeadline!==void 0)return;let e=this.owed.find(r=>r.kind==="ack");if(e===void 0)return;let n=Math.max(Math.min(ea,this.timeoutMs),e.at+this.timeoutMs-Date.now());this.ackDeadline=setTimeout(()=>{this.ackDeadline=void 0;let r=Date.now(),o=[],s=[],c=!0;for(let a of this.owed){if(a.kind==="ack"&&c){if(r-a.at>=this.timeoutMs){o.push(a);continue}c=!1}s.push(a)}if(o.length>0){this.owed.length=0;for(let a of s)this.owed.push(a)}for(let a of o)a.settle(void 0);this.armAckDeadline()},n)}async close(e=5e3){if(this.closedWith!==void 0)return;let n=[...this.links.values()];this.links.clear(),await Promise.all(n.map(o=>o.then(s=>s.close(e)).catch(()=>{})));let r=new Promise(o=>{let s=setTimeout(o,e);this.goodbyeWaiter=()=>{clearTimeout(s),o()}});try{this.ws.send(Zr(this.sessionId,{reasonCode:0}))}catch{}await r,this.onClosed(null);try{this.ws.close()}catch{}}onClosed(e){if(this.closedWith!==void 0)return;this.closedWith=e;let n=e??new E("KERNEL_DOOR_UNAVAILABLE","the session is closed");for(let r of this.publishes.values())r.reject(n);this.publishes.clear(),this.publishPartitions.clear();for(let r of this.awaitingReason.values())clearTimeout(r.timer),r.waiter.resolve(r.answer);this.awaitingReason.clear();for(let r of this.links.values())r.then(o=>o.close()).catch(()=>{});this.links.clear(),this.routes.clear();for(let r of this.owed.splice(0))r.kind==="subscribe"?r.waiter.reject(n):r.settle(void 0);this.ackDeadline!==void 0&&clearTimeout(this.ackDeadline),this.ackDeadline=void 0,this.reasonDueBy=void 0;for(let r of this.subscriptions)r.end(e);this.goodbyeWaiter?.()}onFrame(e){let n,r;try{({canonical:n,tlvs:r}=de(e))}catch{return}let o=M(n);switch(o.frameType){case y.PING:this.ws.send(eo(this.sessionId,n.slice(A,A+o.payloadLen)));return;case y.BULK_ACK:{let s=Bt(n,r),c=s.length===1?Kt(r):void 0;for(let a of s){if(a.seq===0n){this.reasonDueBy=a.status===no?Date.now()+ro:void 0,this.answerOwed({status:a.status,tlvs:r,error:!1});continue}let u=this.publishes.get(a.seq);if(!u)continue;this.publishes.delete(a.seq);let d=this.publishPartitions.get(a.seq);this.publishPartitions.delete(a.seq);let f=a.status===to&&d!==void 0?this.primaryHints.get(d):void 0,l={result:{accepted:Je.has(a.status),statusCode:a.status,statusName:Q(a.status),sequence:a.seq,...a.position?{position:a.position}:{},...c!==void 0&&Je.has(a.status)?{messageGid:c}:{}},...f?{primary:f}:{}};if(a.status===no){let m=a.seq,g=setTimeout(()=>{let w=this.awaitingReason.get(m);w&&(this.awaitingReason.delete(m),w.waiter.resolve(w.answer))},ro);this.awaitingReason.set(m,{waiter:u,answer:l,timer:g});continue}u.resolve(l)}return}case y.DELIVER:this.route(this.readDeliver(n),void 0);return;case y.DELIVER_BATCH:{let s=Xe(r,D.SUBSCRIPTION_HANDLE),c=s?io(s):void 0,a=new DataView(n.buffer,n.byteOffset,n.byteLength),u=a.getUint16(A,!1),d=A+2;for(let f=0;f<u;f+=1){let l=a.getUint32(d,!1);d+=4,this.route(this.readDeliver(de(n.slice(d,d+l)).canonical),c),d+=l}return}case y.ERROR:{let s=this.owed.length>0||this.reasonDueBy!==void 0,c=[...this.awaitingReason.keys(),...s?[0n]:[]],a=ia(n,c);if(!a||a.layout!=="seq-linked"||a.seq===void 0)return;if(a.seq===0n){this.controlError(a.code,a.reason);return}let u=this.awaitingReason.get(a.seq);if(u){this.awaitingReason.delete(a.seq),clearTimeout(u.timer);let d=a.reason;po(d)?u.waiter.reject(new go(u.answer.result.statusCode,d)):Eo(d)?u.waiter.reject(new wo(u.answer.result.statusCode,d)):u.waiter.resolve(u.answer)}return}case y.GOODBYE:this.onClosed(null);return;case y.SYS_EVENT:this.onSysEvent(n);return;default:return}}onSysEvent(e){if(!this.followRedirects)return;let n;try{let r=Xr(e).frame;if(r.eventCode!==ta)return;n=JSON.parse(Mn.decode(r.payload))}catch{return}typeof n?.table!="number"||typeof n.partition!="number"||typeof n.authority!="string"||this.primaryHints.set(vn(n.table,n.partition),{authority:n.authority})}readDeliver(e){let n=Hi(e),r=No(n.attributes);return{table:n.channelId,partition:n.partitionId,offset:n.sequence,hlc:n.hlcTimestamp,position:{partition:n.partitionId,offset:n.sequence},attributes:n.attributes,payload:n.payload,...r?{deliveryToken:r}:{}}}route(e,n){((n!==void 0?this.subscriptions.find(o=>o.handle===n):void 0)??this.subscriptions.find(o=>o.table===e.table&&(o.partition===void 0||o.partition===e.partition))??this.subscriptions.find(o=>o.table===e.table))?.push(e)}};function _a(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r+=1)n|=t[r]^e[r];return n===0}i(_a,"bytesEqual");var Sa=y.PUBLISH,Yl=y.BULK_ACK,Ta=48;function $n(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}i($n,"copyToArrayBuffer");async function Co(t){let e=globalThis.crypto.subtle,n=new TextEncoder().encode(JSON.stringify(t.payload)),r=await e.digest("SHA-256",$n(n)),o=new Uint8Array(r);if(o.byteLength!==Ae)throw new Error(`payloadHash must be ${Ae} bytes, got ${o.byteLength}`);let s=new Uint8Array(Ge);s.set(Y({frameType:Sa,flags:0,headerLen:h,sessionId:t.sessionId,payloadLen:n.byteLength}),0);let c=new DataView(s.buffer,s.byteOffset,s.byteLength);c.setUint32(16,t.channelId??1,!1),c.setUint32(20,t.partitionId??0,!1),c.setBigUint64(24,t.sequence,!1),c.setBigUint64(32,0n,!1),c.setUint32(40,0,!1),s[44]=t.qosLevel??1,s[45]=0,c.setUint16(46,0,!1),s.set(o,48);let a=kt(s),u=await e.sign("Ed25519",t.ed25519PrivateKey,$n(a)),d=new Uint8Array(u);if(d.byteLength!==K)throw new Error(`ed25519 signature must be ${K} bytes, got ${d.byteLength}`);s.set(d,80);let f=new Uint8Array(Ge+n.byteLength);return f.set(s,0),f.set(n,Ge),f}i(Co,"buildSignedPublishFrame");async function Io(t){let e=Ne({sessionId:t.sessionId,envelope:{channelId:1,mode:t.mode,deliveryPreference:t.deliveryPreference,qosCapabilities:0,partitionFilter:0,startCursor:t.startCursor??0n,startHlc:t.startHlc??0n,filters:[]},consumerSignature:new Uint8Array(K)}),n=await globalThis.crypto.subtle.sign("Ed25519",t.ed25519PrivateKey,$n(_n(e))),r=new Uint8Array(n);if(r.byteLength!==K)throw new Error(`ed25519 sig must be ${K} bytes`);return e.set(r,Ta),e}i(Io,"buildSignedSubscribeFrame");function Do(t){if(t.byteLength<h+10)throw new Error(`BULK_ACK too short: ${t.byteLength}`);let{canonical:e,tlvs:n}=de(t),r=Bt(e,n),o=r[0];if(!o)throw new RangeError("BULK_ACK carries no record");let s=r.length===1?Kt(n):void 0;return{sessionId:M(e).sessionId,seq:o.seq,status:o.status,...o.position?{position:o.position}:{},...s!==void 0?{messageGid:s}:{}}}i(Do,"decodeBulkAck");function F(t){return typeof t=="string"&&t.length>0?t:void 0}i(F,"str");function Bn(t){let e=t.split(".");if(e.length<2)return{};try{let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4===0?"":"=".repeat(4-n.length%4),o=typeof Buffer<"u"?Buffer.from(n+r,"base64").toString("utf8"):atob(n+r);return JSON.parse(o)}catch{return{}}}i(Bn,"decodeJwtClaims");function Aa(t){return F(t["npayload/orgId"])??F(t.orgId)??F(t.org)??F(t.org_id)??F(t.sub)}i(Aa,"orgOfClaims");async function Uo(t){if(t!==void 0)return Aa(Bn(typeof t=="function"?await t():t))}i(Uo,"orgOfCredential");var va=/^[a-z0-9][a-z0-9._-]{0,127}$/;function Na(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}i(Na,"fnv1aHex");function Oa(t){return va.test(t)?t:`${t.toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,110)||"x"}-h${Na(t)}`}i(Oa,"kernelSafeName");function ko(t,e){return Oa(`${t}.${e}`)}i(ko,"kernelUnitFor");function Po(t){let e=i(n=>n!==null&&typeof n=="object"&&!Array.isArray(n),"isDoc");return e(t)?[t,t.channel,t.data].filter(e):[]}i(Po,"answerDocs");function tp(t){let e=Po(t);return e.some(n=>n.engine==="convex")?!1:e.some(n=>n.engine==="kernel"||typeof n.kernelTable=="string"&&n.kernelTable!==""||typeof n.kernelTableId=="number"&&Number.isInteger(n.kernelTableId))}i(tp,"channelAnswerNamesKernelTable");function xo(t){for(let e of Po(t)){let n=F(e.appId),r=F(e.envId);if(n!==void 0&&r!==void 0)return ko(n,r)}}i(xo,"channelAnswerUnit");function np(t){let e=Bn(t),n=F(e["npayload/appId"])??F(e.app),r=F(e["npayload/envId"]);return n!==void 0&&r!==void 0?ko(n,r):void 0}i(np,"tokenUnit");var Ca={1:"REJECTED_VERSION",2:"REJECTED_QOS",[Oe.FRAME_MALFORMED]:"FRAME_MALFORMED",[Oe.PROTOCOL_VIOLATION]:"PROTOCOL_VIOLATION",[Oe.UPSTREAM_REFUSED]:"UPSTREAM_REFUSED",501:"UNSUPPORTED",502:"SESSION_EXPIRED"};function Ft(t){return Q(t)??(t===Hr.REJECTED_HW_ATTESTATION?"REJECTED_HW_ATTESTATION":void 0)}i(Ft,"nppStatusName");function Vt(t){return Ca[t]??Ft(t)}i(Vt,"nppErrorName");var Ia=new Set(["REJECTED_AUTH","SESSION_EXPIRED","REJECTED_SIGNATURE","REJECTED_GRANT"]),Da=new Set(["DEFERRED_RETRY","DEFERRED_UNDER_REPLICATED","REJECTED_QUOTA"]),Ua=new Set(["FRAME_MALFORMED","PROTOCOL_VIOLATION","UNSUPPORTED","REJECTED_VERSION","REJECTED_QOS"]);function ap(t){return t===void 0?"protocol":Ia.has(t)?"auth":Da.has(t)?"deferred":Ua.has(t)?"protocol":"admission"}i(ap,"nppRefusalClass");var ka="https://api.npayload.com",Pa="https://auth.npayload.com",$o="https://npp.npayload.com",Mo="npayload.com",xa=new Map([[new URL(ka).hostname,"API"],[new URL(Pa).hostname,"auth host"],[new URL($o).hostname,"edge"]]);function Ma(t){return t===Mo||t.endsWith(`.${Mo}`)}i(Ma,"isProductionHost");function $a(t){let e;try{e=new URL(t).hostname}catch{return}try{e=decodeURIComponent(e)}catch{}return e.toLowerCase().replace(/\.+$/,"")}i($a,"hostOf");function Bo(t){let e=t?.trim();return e||void 0}i(Bo,"named");function Kn(t){let e=Bo(t);if(e===void 0)return;let n=$a(e);if(!(n===void 0||!Ma(n)))return xa.get(n)??"host"}i(Kn,"productionRole");function Ko(t){let e=[];for(let[r,o]of t){let s=Bo(o);s!==void 0&&e.push({source:r,url:s})}let n=e.find(r=>Kn(r.url)===void 0);return n===void 0?{named:e}:{named:e,other:n}}i(Ko,"estateOf");var Ba=["NPAYLOAD_API_URL","NPAYLOAD_AUTH_URL","NPAYLOAD_EDGE_URL","NPAYLOAD_PRIMUS_API_URL","NPAYLOAD_ACCOUNT_API_URL","NPAYLOAD_ADMIN_API_URL","KERNEL_DOOR_URL"];function Ho(t,e=n=>n){return Ba.map(n=>[e(n),t[n]])}i(Ho,"environmentSources");function Fo(t){try{let e=new URL(t).origin;return e&&e!=="null"?e:t}catch{return t}}i(Fo,"shown");function Vo(t,e){if(t.other===void 0)return;let n=Kn(e);if(n!==void 0)return`this run names another estate (${t.other.source} ${t.other.url}), so it sends no request to npayload's production ${n} (${Fo(e)}): npayload's production hosts serve its production estate alone`}i(Vo,"dialRefusal");function lp(t,e){if(t.other===void 0)return;let n=Kn(e);if(n!==void 0)return`this run names another estate (${t.other.source} ${t.other.url}), so it opens no page on npayload's production ${n} (${Fo(e)}): npayload's production hosts serve its production estate alone`}i(lp,"pageRefusal");function pp(t){if(t.other!==void 0)return`this run names another estate (${t.other.source} ${t.other.url}) and no edge of it: npayload's production edge ${$o} is the default of its production estate alone`}i(pp,"noEdgeRefusal");function hp(t){let e={},n=t.replace(/\r\n?/g,`
|
|
3
|
+
`),r=/^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\n]+)?\s*(?:#.*)?$/gm;for(let o=r.exec(n);o!==null;o=r.exec(n)){let s=(o[2]??"").trim(),c=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),c==='"'&&(s=s.replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r")),e[o[1]]=s}return e}i(hp,"readDotenvText");var Ka=new Set([301,302,303,307,308]),qo=20,Ha=["authorization","proxy-authorization","cookie","dpop"],Fa=["content-type","content-length","content-encoding","content-language","content-location"];function Wo(t,e){if(t===void 0)return;let n=i(r=>e.includes(r.toLowerCase()),"dropped");if(t instanceof Headers){let r=new Headers(t);for(let o of e)r.delete(o);return r}return Array.isArray(t)?t.filter(([r])=>!n(r)):Object.fromEntries(Object.entries(t).filter(([r])=>!n(r)))}i(Wo,"withoutHeaders");function Va(t){return typeof t=="string"?t:t instanceof URL?t.href:t.url}i(Va,"urlOf");function qt(t){try{let e=new URL(t).origin;return e&&e!=="null"?e:t}catch{return t}}i(qt,"originOf");async function Hn(t){try{await t.body?.cancel()}catch{}}i(Hn,"discard");function Go(t,e,n){return async(r,o)=>{let s=Va(r),c=t(s);if(c!==void 0)throw e(c,s);let a=n??globalThis.fetch,u={...o??{},redirect:"manual"},d=s;for(let f=0;;f+=1){let l=await a(f===0?r:d,u),m=Ka.has(l.status)?l.headers.get("location"):null;if(m===null)return l;let g=new URL(m,d).href,w=t(g);if(w!==void 0)throw await Hn(l),e(`the redirect from ${qt(d)} to ${qt(g)} is not followed: ${w}`,g);if(f===qo)throw await Hn(l),new TypeError(`fetch failed: more than ${qo} redirects from ${s}`);let R=(u.method??"GET").toUpperCase(),C=l.status===303&&R!=="HEAD"||(l.status===301||l.status===302)&&R==="POST",b=u.headers;C&&(b=Wo(b,Fa)),qt(g)!==qt(d)&&(b=Wo(b,Ha)),u={...u,...C?{method:"GET",body:null}:{},...b!==void 0?{headers:b}:{}},await Hn(l),d=g}}}i(Go,"dialFetch");var jo=Symbol.for("npayload.error.nppTransport"),ye=class t extends Error{static{i(this,"NppTransportError")}code;status;upstreamCode;details;constructor(e,n,r){super(e),this.name="NppTransportError",this.code=n,this.details=r,this.status=r.status,this.upstreamCode=r.upstreamCode,Object.defineProperty(this,jo,{value:!0})}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[jo]===!0}},Jo=Symbol.for("npayload.error.transportUnavailable"),ge=class t extends ye{static{i(this,"TransportUnavailableError")}constructor(e,n="npp",r={}){super(e,"TRANSPORT_UNAVAILABLE",{failedTransport:n,...r}),this.name="TransportUnavailableError",Object.defineProperty(this,Jo,{value:!0})}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[Jo]===!0}},Fn=class extends ye{static{i(this,"TransportRefusedError")}constructor(e,n){super(e,"TRANSPORT_REFUSED",{failedTransport:"npp",...n}),this.name="TransportRefusedError"}},we=class extends ye{static{i(this,"NppKernelDoorError")}constructor(e,n,r={}){super(`${e}: ${n}`,e,{failedTransport:"npp",...r}),this.name="NppKernelDoorError"}},Vn=class extends ye{static{i(this,"NppRefusedError")}refusal;constructor(e,n,r){super(e,"NPP_REFUSED",{failedTransport:"npp",...r,upstreamCode:n.name??Wn(n.code),...n.reason?{upstreamMessage:n.reason}:{}}),this.name="NppRefusedError",this.refusal=n}},qn=class extends ye{static{i(this,"NppProtocolError")}frameType;constructor(e,n,r){super(e,"NPP_PROTOCOL",{failedTransport:"npp",...r}),this.name="NppProtocolError",this.frameType=n}},Zo=new Set([429,500,502,503,504]),qa=`0x${Qe.toString(16).padStart(4,"0")}`,Wa=2147483647;function Ga(t){let e=t.producerEpoch;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>Wa)throw new we("KERNEL_CONFIG",`producerEpoch must be an integer from 0 to 0x7FFF_FFFF (the node's implicit epochs start at 0x8000_0000), got ${String(e)}; nothing was sent.`);if(typeof t.readChannel!="function")throw new we("KERNEL_CONFIG","the kernel door needs `readChannel`, the client's read of a channel's answer; nothing was sent.");let n=t.credential;if(n!==void 0&&(typeof n.accessToken!="function"||typeof n.proof!="function"))throw new we("KERNEL_CONFIG","the kernel door's `credential` needs `accessToken` and `proof`; nothing was sent.")}i(Ga,"assertKernelDoorOptions");var ja=6e4,Ja=50,Ya=5e3,Xa="NPAYLOAD_TEST_RESTART_WINDOW_MS";function Qa(){let t=globalThis.process?.env;if(!t||t.VITEST!=="true")return;let e=t[Xa];if(e===void 0||e==="")return;let n=Number(e);return Number.isFinite(n)&&n>=0?n:void 0}i(Qa,"harnessRestartWindowMs");function za(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:Qa()??ja}i(za,"restartWindowFor");function Za(t){let e=t.get("Retry-After");if(e===null||e.trim()==="")return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}i(Za,"retryAfterMs");function Yo(t,e,n,r){if(t>=e)return;let o=n-Date.now();if(o<=0||r!==void 0&&r>o)return;let s=Math.min(Ya,Ja*2**Math.min(t-1,16))*(.8+Math.random()*.4);return Math.min(Math.max(r??0,Math.round(s)),o)}i(Yo,"nextRepostWaitMs");function Np(t){let e=Wn(t.statusCode),n=t.statusName??Ft(t.statusCode)??"UNREGISTERED_STATUS";if(t.sequenceConflict)return`NPP publish not stored: the broker answered ${n} (BULK_ACK ${e}, HTTP ${t.httpStatus}) for producer sequence ${t.sequenceConflict.sequence} \u2014 ${t.sequenceConflict.reason}`;let r=`NPP publish rejected by the edge: ${n} (BULK_ACK ${e}, HTTP ${t.httpStatus})`;if(t.error){let o=`0x${t.error.code.toString(16).padStart(4,"0")}`,s=t.error.name??o;r+=` \u2014 ${s}${t.error.name?` (${o})`:""}${t.error.reason?`: ${t.error.reason}`:""}`}return t.upstream&&(t.upstream.component||t.upstream.status!==void 0)&&(r+=` [upstream ${t.upstream.component??"unknown"}${t.upstream.status!==void 0?` ${t.upstream.status}`:""}]`),r}i(Np,"describeNppRejection");function ec(t,e){for(let n of t.slice(1)){if(n.byteLength<h||n[4]!==y.ERROR)continue;let r=ie(n,e);return{code:r.code,name:Vt(r.code),reason:r.reason}}}i(ec,"linkedErrorSideband");function tc(t){let e=t.get("X-NPayload-Upstream-Component")??void 0,n=t.get("X-NPayload-Upstream-Status"),r=n!==null&&/^\d+$/.test(n.trim())?Number(n.trim()):void 0;if(!(e===void 0&&r===void 0))return{...e!==void 0?{component:e}:{},...r!==void 0?{status:r}:{}}}i(tc,"upstreamFromHeaders");var nc=8*1024;function rc(t){if(t.byteLength<h)return!1;for(let e=0;e<oe.length;e+=1)if(t[e]!==oe[e])return!1;return!0}i(rc,"isNppFrame");function oc(t){let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(0,nc)))}catch{return{}}if(!e||typeof e!="object")return{};let n=e,r=n.error&&typeof n.error=="object"?n.error:void 0,o=te(e)??r?.code??n.code??(typeof n.error=="string"?n.error:void 0),s=r?.message??n.message;return{...typeof o=="string"&&o?{upstreamCode:o}:{},...typeof s=="string"&&s?{upstreamMessage:s}:{}}}i(oc,"readUpstream");function sc(t,e,n,r){let o=t.headers.get("content-type")??void 0,{upstreamCode:s,upstreamMessage:c}=oc(e),a={status:t.status,url:n,...o?{contentType:o}:{},...s?{upstreamCode:s}:{},...c?{upstreamMessage:c}:{}},u=`answered HTTP ${t.status}`+(o?` (${o})`:"")+(s?` with code ${s}`:"")+(c?`: ${c}`:"")+", which is not an NPP frame";return Zo.has(t.status)?new ge(`npp: the frame door ${n} ${u}, on every one of ${r} attempt(s) across the restart window; the NPP transport is unavailable and the operation was not downgraded to HTTP/JSON.`,"npp",a):new Fn(`npp: the frame door ${n} ${u}; the operation was refused, not retried, and not downgraded to HTTP/JSON.`,a)}i(sc,"nonFrameAnswer");function Wn(t){return`0x${t.toString(16).padStart(4,"0")}`}i(Wn,"hex16");function ic(t){for(let[e,n]of Object.entries(y))if(n===t)return e;return`0x${t.toString(16).padStart(2,"0")}`}i(ic,"frameTypeWord");function ac(t,e){return`${t.name??"UNREGISTERED_CODE"} (ERROR ${Wn(t.code)}, HTTP ${e})${t.reason?`: ${t.reason}`:""}`}i(ac,"describeNppRefusal");function cc(t,e){try{let{canonical:n}=de(t),r=e!==void 0&&e!==0n?[e,0n]:[0n];for(let s of r){let c=ie(n,s);if(c.layout==="seq-linked")return{code:c.code,name:Vt(c.code),reason:c.reason}}let o=ie(n);return{code:o.code,name:Vt(o.code),reason:o.reason}}catch{return}}i(cc,"readFrameDoorError");function uc(t,e,n,r,o){let s=t.headers.get("content-type")??void 0,c={status:t.status,url:n,...s?{contentType:s}:{}},a=r>1?` on every one of ${r} attempts across the restart window`:"",u=e[4];if(u===y.ERROR){let f=cc(e,o);if(f)return new Vn(`npp: the frame door ${n} refused the frame${a}: ${ac(f,t.status)}`,f,c)}let d=u===y.ERROR?"an ERROR frame too short or too malformed to carry its code":`a ${ic(u)} frame (type 0x${u.toString(16).padStart(2,"0")})`;return new qn(`npp: the frame door ${n} answered HTTP ${t.status} with ${d}${a}, where the answer to a frame is a BULK_ACK or an ERROR; the answer breaks the NPP protocol, so the operation failed and was not downgraded to HTTP/JSON.`,u,c)}i(uc,"frameDoorRefusal");var es=Symbol.for("npayload.transport.npp"),ts=Symbol.for("npayload.transport.npp.edge"),ns=Symbol.for("npayload.transport.npp.frameGuard");function Op(t){return typeof t=="object"&&t!==null&&t[es]===!0}i(Op,"isNppTransport");function dc(t){return t[ts]}i(dc,"nppTransportEdge");function Cp(t,e){Object.defineProperty(t,ns,{value:e,configurable:!0})}i(Cp,"guardFrames");function Xo(t,e){let n=t[ns];if(n!==void 0)return n(e);let r=typeof process<"u"?process.env:{},o=Ko([["the transport's edgeUrl",dc(t)],...Ho(r)]),s=Vo(o,e);return s===void 0?void 0:`${s}. Build the transport with the edge of that estate, or name no other estate in the environment.`}i(Xo,"frameRefusal");var Qo=class{static{i(this,"NppTransport")}kind="npp";cfg;fetchImpl;sessionId;credentialOrg;sequenceStore;kernelTableIds=new Map;kernelAnswers=new Map;kernelUnits=new Map;constructor(e,n){if(!e||typeof e.edgeUrl!="string"||e.edgeUrl.length===0)throw new Error("NppTransport requires edgeUrl");e.kernel&&Ga(e.kernel),this.cfg=e,Object.defineProperty(this,es,{value:!0}),Object.defineProperty(this,ts,{value:e.edgeUrl}),this.sequenceStore=e.sequenceStore??ze,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.sessionId=n!==void 0?n>>>0:globalThis.crypto.getRandomValues(new Uint32Array(1))[0]>>>0}async subscribe(e,n){let r=await Io({sessionId:this.sessionId,ed25519PrivateKey:this.cfg.ed25519PrivateKey,mode:n.mode??0,deliveryPreference:n.deliveryPreference??0,...n.startCursor!==void 0?{startCursor:n.startCursor}:{}}),o=await this.postFrame(r,{"X-NPP-Channel-Gid":e,"X-NPP-Consumer-Id":n.consumerId});return{accepted:o.accepted,statusCode:o.statusCode,transport:"npp"}}async postFrame(e,n,r={},o){let s=`${this.cfg.edgeUrl.replace(/\/+$/,"")}/v1/npp/frame`,c=Xo(this,s);if(c!==void 0)throw new ge(`npp: ${c}`,"npp",{url:s});this.credentialOrg??=await Uo(this.cfg.accessToken);let a=this.credentialOrg,u={"Content-Type":"application/octet-stream",...a?{"X-NPP-Org-Id":a}:{},"X-NPP-App-Id":this.cfg.appId,"X-NPP-Jkt":this.cfg.jwkThumbprint,"X-NPP-Client-Id":this.cfg.clientId,...n},d=r.maxRetries!==void 0?Math.max(1,r.maxRetries):Number.POSITIVE_INFINITY,f=Date.now()+za(r.restartWindowMs??this.cfg.restartWindowMs),l=this.cfg.kernel?.credential,m=Go(g=>Xo(this,g),(g,w)=>new ge(`npp: ${g}`,"npp",{url:w}),this.fetchImpl);for(let g=1;;g+=1){let w=u;if(l){let p=await l.accessToken();w={...u,Authorization:`DPoP ${p}`,DPoP:await l.proof(s,p)}}let R,C;try{R=await m(s,{method:"POST",headers:w,body:e}),C=new Uint8Array(await R.arrayBuffer())}catch(p){if(p instanceof ge)throw p;let P=Yo(g,d,f,void 0);if(P!==void 0){await zo(P);continue}let U=p instanceof Error?p.message:String(p),et=new ge(`npp: the frame door ${s} gave no answer (${U}) on every one of ${g} attempt(s) across the restart window; the NPP transport is unavailable and the operation was not downgraded to HTTP/JSON.`,"npp",{url:s});throw et.cause=p,et}let O=rc(C)?xt(C):[],T=O[0],I=T!==void 0&&T[4]===y.BULK_ACK?Do(T):void 0;if(Zo.has(R.status)||I?.status===ve.DEFERRED_RETRY){let p=Yo(g,d,f,Za(R.headers));if(p!==void 0){await zo(p);continue}}if(T===void 0)throw sc(R,C,s,g);if(!I)throw uc(R,T,s,g,o);let _=I.messageGid??R.headers.get("X-NPP-Message-Gid")??void 0,L=ec(O,I.seq),v=tc(R.headers);return{accepted:I.status===ve.ACCEPTED||I.status===ve.ACCEPTED_DUPLICATE,statusCode:I.status,statusName:Ft(I.status),httpStatus:R.status,sequence:I.seq.toString(),..._?{gid:_}:{},...I.position?{position:I.position}:{},...L?{error:L}:{},...v?{upstream:v}:{},attempts:g}}}async publish(e,n,r){let o=this.cfg.kernel,s=o?await this.kernelTableIdOf(e,o):void 0,c=o?.credential?await this.kernelUnitOf(e,o):void 0,a={"X-NPP-Channel-Gid":e,...r?.routingKey?{"X-NPP-Routing-Key":r.routingKey}:{},...o?{"X-NPP-Capabilities":qa,"X-NPP-Producer-Epoch":String(o.producerEpoch)}:{},...c!==void 0?{"X-NPP-Unit":c}:{}},{answer:u,sequence:d,verdict:f}=await Ze(this.sequenceStore,{thumbprint:this.cfg.jwkThumbprint,channelGid:e},async m=>{let g=await Co({sessionId:this.sessionId,sequence:m,payload:n,ed25519PrivateKey:this.cfg.ed25519PrivateKey,...r?.qosLevel!==void 0?{qosLevel:r.qosLevel}:{},...s!==void 0?{channelId:s}:{}}),w=await this.postFrame(g,a,{...r?.maxRetries!==void 0?{maxRetries:r.maxRetries}:{},...r?.restartWindowMs!==void 0?{restartWindowMs:r.restartWindowMs}:{}},m);return{...w,status:w.statusCode,retried:w.attempts>1}}),l=f.kind==="stored";return{accepted:l,statusCode:u.statusCode,statusName:u.statusName,httpStatus:u.httpStatus,sequence:u.sequence,transport:"npp",...u.gid&&l?{gid:u.gid}:{},...u.position?{position:u.position}:{},...u.error?{error:u.error}:{},...u.upstream?{upstream:u.upstream}:{},...f.kind==="conflict"||f.kind==="rewound"?{sequenceConflict:{sequence:d.toString(),reason:f.reason}}:{}}}async kernelTableIdOf(e,n){let r=this.kernelTableIds.get(e);if(r!==void 0)return r;let o=await xn(async()=>{let s=await n.readChannel(e);return this.kernelAnswers.set(e,s),s},{...n.tableIdWaitMs!==void 0?{waitMs:n.tableIdWaitMs}:{},...n.tableIdPollMs!==void 0?{pollMs:n.tableIdPollMs}:{}});if("refused"in o)throw new we("KERNEL_TABLE_ID_UNRESOLVED",`channel ${e}: ${o.detail}. A PUBLISH to the kernel's door carries the kernelTableId its channel's answer names; no frame was sent.`,{channel:e});return this.kernelTableIds.set(e,o.table),o.table}async kernelUnitOf(e,n){let r=this.kernelUnits.get(e);if(r!==void 0)return r;let o=(n.unit!==void 0&&n.unit!==""?n.unit:void 0)??xo(this.kernelAnswers.get(e))??await n.credential?.unit?.();if(o===void 0||o==="")throw new we("KERNEL_UNIT_UNRESOLVED",`channel ${e}: no unit was given, its answer names no appId and envId, and the credential names no app and environment, so the unit its frames name cannot be read; no frame was sent.`,{channel:e});return this.kernelUnits.set(e,o),o}};function zo(t){return new Promise(e=>setTimeout(e,t))}i(zo,"sleep");export{wc as a,Qn as b,S as c,z as d,me as e,ke as f,Z as g,st as h,at as i,fe as j,le as k,ct as l,ft as m,lt as n,ee as o,V as p,zn as q,Zn as r,er as s,ut as t,Oc as u,ei as v,Cr as w,y as x,ve as y,kn as z,Pn as A,ze as B,$t as C,fo as D,Nn as E,po as F,E as G,Ro as H,ua as I,Oo as J,La as K,F as L,Bn as M,Aa as N,tp as O,np as P,Ft as Q,ap as R,ka as S,$o as T,Bo as U,Kn as V,Ko as W,Ho as X,Vo as Y,lp as Z,pp as _,hp as $,Go as aa,ye as ba,ge as ca,Fn as da,we as ea,Vn as fa,qn as ga,Np as ha,Op as ia,dc as ja,Cp as ka,Qo as la};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-LVVHOJLW.mjs";import"./chunk-QGH4LHSH.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as CliError,h as failWith,c as failureReceiptLines,e as failureText,f as isNetworkFailure,b as renderError,g as unreachableText,d as withFailureReceipt};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as g}from"./chunk-4NWQCPI4.mjs";import{c as p,f}from"./chunk-2XQXDEXA.mjs";import{h as d}from"./chunk-UJP3Q23X.mjs";import{a as c}from"./chunk-LJNU5QHZ.mjs";import a from"chalk";function u(){let e=new Set;for(let t of[p,g,f])for(let o of Object.values(t))for(let n of Object.values(o.ops))for(let s of n.scopes??[])e.add(s);return e.add("account:read"),e.add("account:write"),[...e].sort()}c(u,"reconcileOpScopes");function m(e){return[...new Set([...e,...u()])].sort()}c(m,"computePushGrant");async function O(e,t,o){if(!t){o(a.dim(` (credential scopes not synced \u2014 no app id on this run)
|
|
2
|
+
`));return}try{let{restoreSession:n}=await import("./chunk-I3UZ2FRE.mjs"),s=await n();if(!s){o(a.dim(" (credential scopes not synced \u2014 run `npayload login` once to let push manage them)\n"));return}let r=m(e),l=(await s.provisionOac(null,t,!1,r)).allowedScopes?.length??r.length;o(a.dim(` credential scopes \u2014 synced to the config (${l} per-object scope(s))
|
|
3
|
+
`))}catch(n){d(n);let s=n instanceof Error?n.message:String(n);o(a.yellow(` (credential scopes not synced: ${s} \u2014 config is applied; re-run \`npayload push\` after \`npayload login\`)
|
|
4
|
+
`))}}c(O,"syncCredentialScopes");async function R(e,t,o=()=>{}){let n=[...new Set(e)].sort(),{restoreSession:s}=await import("./chunk-I3UZ2FRE.mjs"),r=await s();if(!r)throw new Error("declared [access_scopes] sync needs the human management session \u2014 run `npayload login` (a machine credential can never widen its own grant).");let i=await r.provisionOac(null,t,!1,n),l=i.allowedScopes?.length??n.length;return o(a.dim(` credential scopes \u2014 grant set-equal to the manifest (${l} scope(s))
|
|
5
|
+
`)),{allowedScopes:i.allowedScopes??n}}c(R,"syncExactGrant");export{u as a,m as b,O as c,R as d};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as s,c as a}from"./chunk-OA73YMB6.mjs";import{a as c}from"./chunk-LJNU5QHZ.mjs";import{existsSync as u,readFileSync as f}from"fs";import{join as d}from"path";var i=class extends Error{static{c(this,"AuthError")}constructor(t){super(t),this.name="AuthError"}},l="Not authenticated. Run `npayload login` (interactive, stores in the OS keychain), or for CI / headless set NPAYLOAD_CLIENT_ID + NPAYLOAD_CLIENT_SECRET (or NPAYLOAD_TOKEN for a short-lived token). Run `npayload doctor` to check this host.";function h(){let n=process.cwd(),t=n;for(let o=0;o<5;o++){let r=d(t,".npayload.json");if(u(r))try{let p=JSON.parse(f(r,"utf8"));return t!==n&&process.stderr.write(`npayload: using app credentials from a parent directory (${r}). Run from the project root, or set NPAYLOAD_CLIENT_ID/NPAYLOAD_TOKEN, if this is not the app you intend.
|
|
2
|
+
`),p}catch{return null}let e=d(t,"..");if(e===t)break;t=e}return null}c(h,"findProjectCredentials");async function v(){let n=process.env.NPAYLOAD_TOKEN?.trim()||void 0,t=process.env.NPAYLOAD_CLIENT_ID?.trim()||void 0,o=(process.env.NPAYLOAD_CLIENT_SECRET??process.env.NPAYLOAD_HMAC_SECRET)?.trim()||void 0;if(n)return{clientId:t??"",hmacSecret:o??"",accessToken:n,source:"env_token"};if(t&&o)return{clientId:t,hmacSecret:o,source:"env"};let r=h();if(r?.clientId&&r?.hmacSecret)return{clientId:r.clientId,hmacSecret:r.hmacSecret,source:"project",...r.dpopPrivateJwk!==void 0?{dpopPrivateJwk:r.dpopPrivateJwk}:{}};try{let e=await a();if(e?.clientId&&e?.hmacSecret)return{clientId:e.clientId,hmacSecret:e.hmacSecret,source:"keychain",...e.dpopPrivateJwk!==void 0?{dpopPrivateJwk:e.dpopPrivateJwk}:{}}}catch(e){throw e instanceof s?new i(`${e.message}
|
|
3
|
+
|
|
4
|
+
${l}`):e}throw new i(l)}c(v,"resolveCredentials");async function N(){try{return await v()}catch{return null}}c(N,"tryResolveCredentials");export{i as a,h as b,v as c,N as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as h,V as g,W as m,Y as U,Z as k,_ as b,aa as E,ca as u,ka as T,w as R}from"./chunk-QGH4LHSH.mjs";import{a as r}from"./chunk-LJNU5QHZ.mjs";var A=class e{constructor(n,t){this.estate=n;this.cureFor=t}static{r(this,"DialGuard")}get production(){return this.estate.other===void 0}refusal(n){let t=U(this.estate,n);return t===void 0?void 0:`${t}. ${this.cureFor(g(n))}`}noEdge(){let n=b(this.estate);return n===void 0?void 0:`${n}. ${this.cureFor("edge")}`}checkPages(...n){for(let t of n){let a=k(this.estate,t);if(a!==void 0)throw new u(y(`${a}. ${this.cureFor(g(t))}`))}}check(...n){for(let t of n){let a=this.refusal(t);if(a!==void 0)throw new u(y(a))}}with(n){return new e(m([...this.estate.named.map(t=>[t.source,t.url]),...n]),this.cureFor)}};function C(e,n){return E(t=>e.refusal(t),t=>new u(y(t)),n)}r(C,"guardedFetch");var D=Symbol("npayload.dial.refusal");function K(e){let n=new Error(e.message);return n.name="AbortError",n[D]=e,n}r(K,"carried");function $(e){return e instanceof Error?e[D]:void 0}r($,"refusalCarriedBy");function y(e){return e.charAt(0).toUpperCase()+e.slice(1)}r(y,"capitalised");var f=new WeakMap;function j(e){return f.get(e)?.guard}r(j,"guardOf");function H(e){return f.get(e)?.tokenUrl}r(H,"tokenUrlOf");function L(e){return f.get(e)?.apiUrl}r(L,"apiUrlOf");function v(e){return`${(e.authUrl??e.baseUrl??h).replace(/\/+$/,"")}/oauth/token`}r(v,"tokenEndpointOf");function F(e,n){let t=n.path;for(let[a,d]of Object.entries(n.pathParams??{}))t=t.replace(`{${a}}`,encodeURIComponent(d));return e.replace(/\/+$/,"")+t}r(F,"requestUrl");function S(e,n){let t=C(n),a,d={fetch:r(async o=>{try{return await t(o.url,{method:o.method,headers:o.headers,body:o.body??null,...o.signal!==void 0?{signal:o.signal}:{},...a!==void 0?{dispatcher:a}:{}})}catch(i){throw i instanceof u?K(i):I(i)}},"fetch")},s=new R({config:{...e,httpClient:d}});a=s.dispatcher;let p=v(e),w=e.baseUrl??h;f.set(s,{guard:n,tokenUrl:p,apiUrl:w});let c=s.auth;if(c!==void 0&&typeof c.getAccessToken=="function"){let o=c;typeof o.fetchImpl=="function"&&(o.fetchImpl=C(n,o.fetchImpl));let i=c.getAccessToken.bind(c);c.getAccessToken=async l=>(n.check(p),i(l))}if(typeof s.send=="function"){let o=s.send.bind(s);s.send=(async i=>{n.check(p,F(w,i));try{return await o(i)}catch(l){throw $(l)??l}})}return s}r(S,"dialKernel");function I(e){if(!(e instanceof TypeError))return e;let n=e.cause,t=n instanceof Error?n.message:typeof n=="string"?n:void 0;return t===void 0||t===""||e.message.includes(t)?e:new TypeError(`${e.message}: ${t}`,{cause:n})}r(I,"withDialReason");function _(e){if(e instanceof u)throw e}r(_,"rethrowRefusal");function N(e,n){T(e,t=>n.refusal(t))}r(N,"guardTransport");export{A as a,C as b,j as c,H as d,L as e,v as f,S as g,_ as h,N as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./chunk-IK32U5FV.mjs";import{a as l}from"./chunk-LJNU5QHZ.mjs";function t(e){return[...new Set(e)].sort()}l(t,"normalizeScopes");function f(e,r){let o=t(e),n=t(r);return o.length===n.length&&o.every((i,c)=>i===n[c])}l(f,"scopesEqual");function d(e,r,o){let n=new Set(e),i=new Set(r),c=new Set(o);return{base:t(e),manifest:t(r),remote:t(o),localAdded:t(r.filter(s=>!n.has(s))),localRemoved:t(e.filter(s=>!i.has(s))),remoteAdded:t(o.filter(s=>!n.has(s))),remoteRemoved:t(e.filter(s=>!c.has(s)))}}l(d,"diffAgainstBase");function p(e){let r=t(e.declared),o=e.resolution??"none",n=a(r,e.floor);if(n.length>0)return{kind:"floor-gap",gap:n};let i=t(e.remote.scopes),c=t(e.pullBase??e.remote.scopes);return e.remote.configDrift&&!f(r,i)?o==="accept-remote"?{kind:"accept-remote",grant:i,manifest:i}:o==="overwrite-remote"?{kind:"sync",grant:r}:{kind:"conflict",diff:d(c,r,i)}:{kind:"sync",grant:r}}l(p,"reconcileScopes");export{p as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as a,e as b,f as c,g as d}from"./chunk-PYLSDRRO.mjs";import"./chunk-MDW42OG6.mjs";import"./chunk-UNDT7J2V.mjs";import"./chunk-IK32U5FV.mjs";import"./chunk-SRQQNHSX.mjs";import"./chunk-MW4TLR2T.mjs";import"./chunk-JUXYOKI2.mjs";import"./chunk-TQFAYJEP.mjs";import"./chunk-4NWQCPI4.mjs";import"./chunk-FAO3QJC5.mjs";import"./chunk-455C67EN.mjs";import"./chunk-CJDCY2NH.mjs";import"./chunk-2XQXDEXA.mjs";import"./chunk-XLK55DEY.mjs";import"./chunk-LVVHOJLW.mjs";import"./chunk-I7YPDC7V.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-P5GCOROB.mjs";import"./chunk-UJP3Q23X.mjs";import"./chunk-QGH4LHSH.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{c as pullScopesIntoManifest,d as registerScopes,b as runScopesDiff,a as runScopesFix};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as d}from"./chunk-GGXNXM73.mjs";import{a as i}from"./chunk-LJNU5QHZ.mjs";import{existsSync as h,readFileSync as R}from"fs";import{dirname as y,isAbsolute as k,join as g,resolve as m}from"path";function p(e){return e.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}i(p,"sanitize");function S(e){return e.trim().toLowerCase()==="authorization"?"AUTH":p(e)}i(S,"headerSuffix");function x(e,o){return`{{ secrets.${[e.app?p(e.app):"",p(e.channel),S(o)].filter(t=>t.length>0).join("_")} }}`}i(x,"secretRefFor");var w=/^\s*\{\{\s*secrets\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}\s*$/;function l(e){return typeof e=="string"&&w.test(e)}i(l,"isSecretRef");function j(e){if(typeof e!="string")return null;let o=w.exec(e);return o?o[1]:null}i(j,"parseSecretRef");function v(e,o){let r={};for(let[t,s]of Object.entries(e))d(t)&&!l(s)?r[t]=x(o,t):r[t]=s;return r}i(v,"redactSecretHeaders");var A=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)(?:\s*=|:\s)(.*)$/;function E(e){let o={};for(let r of e.split(/\r?\n/)){let t=r.trim();if(!t||t.startsWith("#"))continue;let s=A.exec(t);s&&(o[s[1]]=s[2].trim().replace(/^(["'])(.*)\1$/,"$2"))}return o}i(E,"parseDotenv");function O(e,o=process.env){let r=k(e)?e:m(process.cwd(),e),t=y(r),s=[g(t,".env"),g(t,"npayload",".env")],c={};for(let n of[...s].reverse())if(h(n))try{Object.assign(c,E(R(n,"utf8")))}catch{}for(let[n,a]of Object.entries(o))a!==void 0&&a!==""&&(c[n]=a);return{env:c,searched:s}}i(O,"loadSecretEnv");function C(e,o=process.env,r=[]){let t=[],s=i(n=>{if(typeof n=="string"){let a=j(n);if(a===null)return n;let f=o[a];return f===void 0||f===""?(t.push(a),n):f}if(Array.isArray(n))return n.map(s);if(n&&typeof n=="object"){let a={};for(let[f,u]of Object.entries(n))a[f]=s(u);return a}return n},"walk"),c=s(e);if(t.length>0)throw new Error(`unresolved secret reference(s): ${[...new Set(t)].sort().join(", ")} \u2014 set them in your environment (process env, project .env, npayload/.env) before pushing`+(r.length>0?`; files searched: ${r.join(", ")}`:""));return c}i(C,"resolveSecretRefs");function $(e){let o=[],r=i((t,s)=>{if(Array.isArray(t)){t.forEach((c,n)=>r(c,`${s}/${n}`));return}if(!(!t||typeof t!="object"))for(let[c,n]of Object.entries(t)){let a=`${s}/${c}`;if(c==="headers"&&n&&typeof n=="object"&&!Array.isArray(n))for(let[f,u]of Object.entries(n))d(f)&&typeof u=="string"&&!l(u)&&o.push({path:`${a}/${f}`,header:f});r(n,a)}},"walk");return r(e,""),o}i($,"findRawSecretHeaders");function z(e){let o=$(e);if(o.length!==0)throw new Error("raw secret header value(s) in config \u2014 replace each with a {{ secrets.NAME }} reference (npayload pull writes them; npayload validate lists them): "+o.map(r=>`${r.header} at ${r.path}`).join("; "))}i(z,"assertNoRawSecretHeaders");var b="[redacted \u2014 secret header]";function N(e){let o=i((r,t)=>{if(Array.isArray(r))return r.map(s=>o(s,!1));if(r&&typeof r=="object"){let s={};for(let[c,n]of Object.entries(r))t&&d(c)&&typeof n=="string"&&!l(n)?s[c]=b:s[c]=o(n,c==="headers");return s}return r},"walk");return o(e,!1)}i(N,"maskSecretHeaderValues");export{x as a,l as b,j as c,v as d,E as e,O as f,C as g,$ as h,z as i,b as j,N as k};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One selectable value. `value` is what goes on the wire; `name` is what the
|
|
6
|
+
* user sees. A skip entry carries `value: ""`: the flag is left unset.
|
|
7
|
+
*/
|
|
8
|
+
interface PromptChoice {
|
|
9
|
+
name: string;
|
|
10
|
+
value: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Interactive input provider for `--interactive`. Injected rather than imported
|
|
14
|
+
* so this module stays dependency-free (and unit-testable without a TTY).
|
|
15
|
+
*
|
|
16
|
+
* Every method returns a string; `""` means "left unset" — the interpreter omits
|
|
17
|
+
* that flag entirely rather than sending an empty value.
|
|
18
|
+
*/
|
|
19
|
+
interface InteractivePrompter {
|
|
20
|
+
text(message: string, opts: {
|
|
21
|
+
optional: boolean;
|
|
22
|
+
}): Promise<string>;
|
|
23
|
+
/** Masked input — used for any flag whose name looks like a credential. */
|
|
24
|
+
secret(message: string, opts: {
|
|
25
|
+
optional: boolean;
|
|
26
|
+
}): Promise<string>;
|
|
27
|
+
select(message: string, choices: PromptChoice[]): Promise<string>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The `np` command line (also `npayload`).
|
|
32
|
+
*
|
|
33
|
+
* The CLI is a projection of the same contract as the SDK: every command is registered from the generated command
|
|
34
|
+
* table and sent through the kernel (OAuth client credentials and DPoP).
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
interface BuildProgramOptions {
|
|
38
|
+
/** Override result output (defaults to stdout JSON). */
|
|
39
|
+
print?: (value: unknown) => void;
|
|
40
|
+
/** Override error output (defaults to stderr). */
|
|
41
|
+
printError?: (message: string) => void;
|
|
42
|
+
/**
|
|
43
|
+
* Override the destructive-op confirmation prompt (defaults to a TTY readline prompt, or `--yes`). Returning false
|
|
44
|
+
* aborts the op before any request is sent.
|
|
45
|
+
*/
|
|
46
|
+
confirm?: (question: string) => Promise<boolean>;
|
|
47
|
+
/** Override the `--interactive` prompt provider (defaults to the @inquirer/prompts stack). */
|
|
48
|
+
prompt?: InteractivePrompter;
|
|
49
|
+
/** Override the `np secret set` value source (defaults to stdin when piped, or a masked TTY prompt). */
|
|
50
|
+
readSecret?: (name: string) => Promise<string>;
|
|
51
|
+
}
|
|
52
|
+
declare function buildProgram(opts?: BuildProgramOptions): Promise<Command>;
|
|
53
|
+
|
|
54
|
+
export { type BuildProgramOptions, buildProgram };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One selectable value. `value` is what goes on the wire; `name` is what the
|
|
6
|
+
* user sees. A skip entry carries `value: ""`: the flag is left unset.
|
|
7
|
+
*/
|
|
8
|
+
interface PromptChoice {
|
|
9
|
+
name: string;
|
|
10
|
+
value: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Interactive input provider for `--interactive`. Injected rather than imported
|
|
14
|
+
* so this module stays dependency-free (and unit-testable without a TTY).
|
|
15
|
+
*
|
|
16
|
+
* Every method returns a string; `""` means "left unset" — the interpreter omits
|
|
17
|
+
* that flag entirely rather than sending an empty value.
|
|
18
|
+
*/
|
|
19
|
+
interface InteractivePrompter {
|
|
20
|
+
text(message: string, opts: {
|
|
21
|
+
optional: boolean;
|
|
22
|
+
}): Promise<string>;
|
|
23
|
+
/** Masked input — used for any flag whose name looks like a credential. */
|
|
24
|
+
secret(message: string, opts: {
|
|
25
|
+
optional: boolean;
|
|
26
|
+
}): Promise<string>;
|
|
27
|
+
select(message: string, choices: PromptChoice[]): Promise<string>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The `np` command line (also `npayload`).
|
|
32
|
+
*
|
|
33
|
+
* The CLI is a projection of the same contract as the SDK: every command is registered from the generated command
|
|
34
|
+
* table and sent through the kernel (OAuth client credentials and DPoP).
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
interface BuildProgramOptions {
|
|
38
|
+
/** Override result output (defaults to stdout JSON). */
|
|
39
|
+
print?: (value: unknown) => void;
|
|
40
|
+
/** Override error output (defaults to stderr). */
|
|
41
|
+
printError?: (message: string) => void;
|
|
42
|
+
/**
|
|
43
|
+
* Override the destructive-op confirmation prompt (defaults to a TTY readline prompt, or `--yes`). Returning false
|
|
44
|
+
* aborts the op before any request is sent.
|
|
45
|
+
*/
|
|
46
|
+
confirm?: (question: string) => Promise<boolean>;
|
|
47
|
+
/** Override the `--interactive` prompt provider (defaults to the @inquirer/prompts stack). */
|
|
48
|
+
prompt?: InteractivePrompter;
|
|
49
|
+
/** Override the `np secret set` value source (defaults to stdin when piped, or a masked TTY prompt). */
|
|
50
|
+
readSecret?: (name: string) => Promise<string>;
|
|
51
|
+
}
|
|
52
|
+
declare function buildProgram(opts?: BuildProgramOptions): Promise<Command>;
|
|
53
|
+
|
|
54
|
+
export { type BuildProgramOptions, buildProgram };
|