@npayload/sdk 5.0.4 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +4 -0
  2. package/dist/chunk-2G46BKEC.mjs +1 -0
  3. package/dist/{chunk-KUJJYP3K.mjs → chunk-2WG7FETK.mjs} +1 -1
  4. package/dist/chunk-5R5L7GTT.mjs +17 -0
  5. package/dist/{chunk-2N25V56J.mjs → chunk-6R2QLUWE.mjs} +2 -2
  6. package/dist/chunk-7IFTQ52O.mjs +1 -0
  7. package/dist/chunk-7QTR5IWG.mjs +1 -0
  8. package/dist/chunk-AECDYMA2.mjs +1 -0
  9. package/dist/{chunk-455C67EN.mjs → chunk-AGDMCMF3.mjs} +1 -1
  10. package/dist/chunk-C5EDDEPR.mjs +1 -0
  11. package/dist/{chunk-2PCG57PX.mjs → chunk-CDA75PLA.mjs} +1 -1
  12. package/dist/{chunk-6ZOPXG44.mjs → chunk-CFM43QNN.mjs} +4 -4
  13. package/dist/{chunk-6RMN6EHY.mjs → chunk-GG7UQYUV.mjs} +1 -1
  14. package/dist/{chunk-FAO3QJC5.mjs → chunk-HX6PH7C3.mjs} +1 -1
  15. package/dist/{chunk-RIBBVOCC.mjs → chunk-IH2OLS7G.mjs} +1 -1
  16. package/dist/{chunk-FNAZW7X3.mjs → chunk-K3YY77PG.mjs} +1 -1
  17. package/dist/chunk-KQCX2PCW.mjs +1 -0
  18. package/dist/chunk-LCUELOEE.mjs +2 -0
  19. package/dist/{chunk-2XQXDEXA.mjs → chunk-M7WGBUJ2.mjs} +1 -1
  20. package/dist/{chunk-UMQ2SWSM.mjs → chunk-N6NIJISZ.mjs} +1 -1
  21. package/dist/chunk-ONTNXGOM.mjs +1 -0
  22. package/dist/{chunk-HTQLUO4J.mjs → chunk-ORT5FUFW.mjs} +1 -1
  23. package/dist/chunk-R6DPWMZM.mjs +1 -0
  24. package/dist/{chunk-MPYL6HQR.mjs → chunk-STS7CL74.mjs} +1 -1
  25. package/dist/{chunk-A7HA64P6.mjs → chunk-TUWFD3AZ.mjs} +1 -1
  26. package/dist/chunk-UDLS46F5.mjs +1 -0
  27. package/dist/chunk-VZT7RCAC.mjs +4 -0
  28. package/dist/{chunk-76OM2ZBO.mjs → chunk-WOMYXKGW.mjs} +3 -3
  29. package/dist/{chunk-6NCRQ746.mjs → chunk-X3CZMXOZ.mjs} +1 -1
  30. package/dist/{chunk-BMMAZIUY.mjs → chunk-YFFHEYYK.mjs} +1 -1
  31. package/dist/chunk-YHUBO6K4.mjs +1 -0
  32. package/dist/{chunk-4HVQZC7R.mjs → chunk-YLV3KSNV.mjs} +1 -1
  33. package/dist/{chunk-2OCUKD3K.mjs → chunk-ZDOLKWQD.mjs} +1 -1
  34. package/dist/cli/index.js +254 -277
  35. package/dist/cli/index.mjs +183 -206
  36. package/dist/index.d.mts +4795 -1890
  37. package/dist/index.d.ts +4795 -1890
  38. package/dist/index.js +2 -2
  39. package/dist/index.mjs +2 -2
  40. package/package.json +1 -1
  41. package/dist/chunk-22PYMXSS.mjs +0 -1
  42. package/dist/chunk-52ZB3ZAG.mjs +0 -1
  43. package/dist/chunk-5YK2JKKH.mjs +0 -17
  44. package/dist/chunk-APBVAT7F.mjs +0 -1
  45. package/dist/chunk-EL7XOWA4.mjs +0 -1
  46. package/dist/chunk-GKDZ7663.mjs +0 -1
  47. package/dist/chunk-II74EBLQ.mjs +0 -1
  48. package/dist/chunk-JBAV2AQK.mjs +0 -1
  49. package/dist/chunk-LT2DQLXJ.mjs +0 -1
  50. package/dist/chunk-QUJ2IZXU.mjs +0 -1
  51. package/dist/chunk-WE3NRBO6.mjs +0 -1
  52. package/dist/chunk-YHY7Y4HD.mjs +0 -4
  53. package/dist/chunk-YQVQTVHK.mjs +0 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npayload/sdk",
3
- "version": "5.0.4",
3
+ "version": "5.1.0",
4
4
  "description": "The SDK and CLI for npayload, one platform that makes your systems autonomous: events, pipes, AI agents, partner connections and feeds.",
5
5
  "type": "commonjs",
6
6
  "main": "dist/index.js",
@@ -1 +0,0 @@
1
- import{d as a,e as b,f as c,g as d}from"./chunk-2N25V56J.mjs";import"./chunk-MDW42OG6.mjs";import"./chunk-6RMN6EHY.mjs";import"./chunk-RIBBVOCC.mjs";import"./chunk-76OM2ZBO.mjs";import"./chunk-2OCUKD3K.mjs";import"./chunk-6ZOPXG44.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-UMQ2SWSM.mjs";import"./chunk-YQVQTVHK.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-BMMAZIUY.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{c as pullScopesIntoManifest,d as registerScopes,b as runScopesDiff,a as runScopesFix};
@@ -1 +0,0 @@
1
- import{l as a,m as b}from"./chunk-5YK2JKKH.mjs";import"./chunk-6ZOPXG44.mjs";import"./chunk-TQFAYJEP.mjs";import"./chunk-4NWQCPI4.mjs";import"./chunk-CJDCY2NH.mjs";import"./chunk-2XQXDEXA.mjs";import"./chunk-XLK55DEY.mjs";import"./chunk-UMQ2SWSM.mjs";import"./chunk-YQVQTVHK.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-BMMAZIUY.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as buildReport,b as registerDoctor};
@@ -1,17 +0,0 @@
1
- import{Z as Y}from"./chunk-6ZOPXG44.mjs";import{b as U}from"./chunk-TQFAYJEP.mjs";import{f as T,i as v}from"./chunk-UMQ2SWSM.mjs";import{a as S,e as I}from"./chunk-YQVQTVHK.mjs";import{b as M,c as F}from"./chunk-OA73YMB6.mjs";import{b as D}from"./chunk-WE3NRBO6.mjs";import{da as E}from"./chunk-YHY7Y4HD.mjs";import{a as s}from"./chunk-LJNU5QHZ.mjs";import{existsSync as W,readFileSync as ae}from"fs";import{join as B}from"path";import p from"chalk";import u from"chalk";import ee from"ora";var b=class{static{s(this,"Spinner")}instance;constructor(t){this.instance=ee({text:t,isSilent:!process.stderr.isTTY})}start(t){return t&&(this.instance.text=t),this.instance.start(),this}succeed(t){this.instance.succeed(t)}fail(t){this.instance.fail(t)}warn(t){this.instance.warn(t)}info(t){this.instance.info(t)}stop(){this.instance.stop()}set text(t){this.instance.text=t}};function le(e){return new b(e).start()}s(le,"spin");var te=new Set(["human","table","json","yaml","ndjson"]);function q(e){if(e===void 0)return"human";let t=e.toLowerCase();if(!te.has(t))throw new Error(`Unknown --output "${e}". Use one of: human, table, json, yaml, ndjson.`);return t}s(q,"resolveOutputFormat");function y(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(y,"isScalar");function j(e){return e===null?"":String(e)}s(j,"scalarToString");function O(e){if(e==null)return"null";if(typeof e=="number"||typeof e=="boolean")return String(e);let t=String(e);return t===""||/[:#\-?,[\]{}&*!|>'"%@`]/.test(t)||/^\s|\s$/.test(t)||/^(true|false|null|~|\d)/i.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}s(O,"yamlScalar");function k(e,t=0){let n=" ".repeat(t);if(y(e)||e===void 0)return`${n}${O(e)}`;if(Array.isArray(e))return e.length===0?`${n}[]`:e.map(r=>{if(y(r)||r===void 0)return`${n}- ${O(r)}`;let i=k(r,t+1).replace(/^ {2}/,"");return`${n}- ${i.replace(/^\s+/,"")}
2
- ${k(r,t+1).split(`
3
- `).slice(1).join(`
4
- `)}`.trimEnd()}).join(`
5
- `);let a=Object.entries(e);return a.length===0?`${n}{}`:a.map(([r,i])=>y(i)||i===void 0?`${n}${r}: ${O(i)}`:Array.isArray(i)&&i.length===0?`${n}${r}: []`:!Array.isArray(i)&&Object.keys(i).length===0?`${n}${r}: {}`:`${n}${r}:
6
- ${k(i,t+1)}`).join(`
7
- `)}s(k,"toYaml");function ne(e){if(e.length===0)return"(no rows)";let t=[];for(let o of e)for(let l of Object.keys(o))t.includes(l)||t.push(l);let n=s(o=>o==null?"":y(o)?j(o):JSON.stringify(o),"cell"),a=t.map(o=>Math.max(o.length,...e.map(l=>n(l[o]).length))),r=s(o=>o.map((l,f)=>l.padEnd(a[f])).join(" ").trimEnd(),"fmtRow"),i=r(t),c=a.map(o=>"-".repeat(o)).join(" "),h=e.map(o=>r(t.map(l=>n(o[l]))));return[i,c,...h].join(`
8
- `)}s(ne,"toTable");function z(e,t){switch(t){case"json":return JSON.stringify(e,null,2);case"ndjson":return(Array.isArray(e)?e:[e]).map(n=>JSON.stringify(n)).join(`
9
- `);case"yaml":return k(e);case"table":{let n=Array.isArray(e)?e:[e];return n.every(r=>r!==null&&typeof r=="object"&&!Array.isArray(r))?ne(n):k(e)}case"human":default:return w(e)}}s(z,"renderResult");function w(e,t=0){let n=" ".repeat(t);if(y(e)||e===void 0)return`${n}${e===void 0?"":j(e)}`;if(Array.isArray(e))return e.length===0?`${n}${u.dim("(none)")}`:e.map((i,c)=>`${n}${u.dim(`[${c}]`)}
10
- ${w(i,t+1)}`).join(`
11
- `);let a=Object.entries(e);if(a.length===0)return`${n}${u.dim("(empty)")}`;let r=Math.max(...a.map(([i])=>i.length));return a.map(([i,c])=>{let h=u.cyan(i.padEnd(r));return y(c)||c===void 0?`${n}${h} ${c===void 0?"":j(c)}`:`${n}${h}
12
- ${w(c,t+1)}`}).join(`
13
- `)}s(w,"renderHuman");var H=class{constructor(t){this.format=t;this.tty=t==="human"&&!!process.stderr.isTTY}static{s(this,"StepLog")}tty;spinner=null;lines=[];start(t){this.tty&&(this.spinner=new b(`\u25C9 ${t}`).start())}finish(t){if(this.lines.push(t),!this.tty)return;let n=t.message?u.dim(` (${t.message})`):"",a=`${t.label}${n}`;this.spinner?(t.status==="succeeded"?this.spinner.succeed(`\u2713 ${a}`):t.status==="failed"?this.spinner.fail(`\u2716 ${a}`):t.status==="skipped"?this.spinner.warn(`\u293F ${a}`):this.spinner.info(a),this.spinner=null):process.stderr.write(`${re(t.status)} ${a}
14
- `)}all(){return this.lines}hasFailure(){return this.lines.some(t=>t.status==="failed")}};function re(e){switch(e){case"succeeded":return u.green("\u2713");case"failed":return u.red("\u2716");case"skipped":return u.yellow("\u293F");default:return u.cyan("\u25C9")}}s(re,"glyph");var ge="__set_by_npayload_login__",be="__set_by_npayload_login__",ke="__set_by_npayload_login__";function N(e){if(e==null)return!0;let t=e.trim();return t.length===0?!0:t.startsWith("__set_by_npayload_login__")}s(N,"isPlaceholderCredential");var K="f4d5410c733e4c4a28858907bb7addc6d1fd34280961bdfb74cf0ac7a0a8419b",Ae={$schema:"http://json-schema.org/draft-07/schema#",title:"EventsConfig",type:"object",additionalProperties:!1,properties:{channels:{type:"object",maxProperties:500,propertyNames:{pattern:"^[a-z0-9][a-z0-9._-]{0,126}$"},additionalProperties:{type:"object",additionalProperties:!1,properties:{name:{type:"string",maxLength:4096},idempotencyKey:{type:"string",maxLength:4096},description:{type:"string",maxLength:4096},type:{type:"string",enum:["topic","queue","stream"]},schema:{type:"object",properties:{type:{type:"string",enum:["json","avro","protobuf"]},definition:{type:"string",maxLength:4096},strict:{type:"boolean"}},required:["type"],additionalProperties:!1},settings:{type:"object",properties:{retentionMs:{type:"number"},maxMessageSize:{type:"number"},maxSubscriptions:{type:"number"},idempotencyWindowMs:{type:"number"}},additionalProperties:!1},metadata:{type:"object",additionalProperties:{oneOf:[{type:"string",maxLength:4096},{type:"number"},{type:"boolean"},{type:"null"}]},propertyNames:{maxLength:256,not:{enum:["__proto__","constructor","prototype"]}}},retentionMode:{type:"string",enum:["standard","compacted","compacted_with_log"]},compactionConfig:{type:"object",properties:{minAge:{type:"number"},deletePolicy:{type:"string",enum:["compact","delete","compact_and_delete"]}},additionalProperties:!1},nppMinQos:{type:"number"},rateLimit:{type:"object",properties:{ratePerSec:{type:"number"},burst:{type:"number"}},required:["ratePerSec","burst"],additionalProperties:!1},complianceClass:{type:"string",enum:["NONE","SOC2","GDPR","HIPAA","PCI","FEDRAMP_MOD","FEDRAMP_HIGH","IL5","ITAR"]},privacy:{type:"object",properties:{mode:{type:"string",enum:["standard","e2e","hybrid"]},encryptionProvider:{type:"string",enum:["none","publisher","platform"]}},required:["mode","encryptionProvider"],additionalProperties:!1},privacyMode:{type:"string",enum:["standard","hybrid","e2e"]},pii:{type:"string",enum:["strip","allow","block"]}},required:["name"]}},consumerGroups:{type:"object",maxProperties:500,propertyNames:{pattern:"^[a-z0-9][a-z0-9._-]{0,126}$"},additionalProperties:{type:"object",additionalProperties:!1,properties:{channelGid:{type:"string",maxLength:4096},strategy:{type:"string",enum:["competing","sticky","broadcast"]},maxConcurrency:{type:"number"}},required:["strategy"]}},eventTypes:{type:"object",maxProperties:500,propertyNames:{pattern:"^[a-z0-9][a-z0-9._-]{0,126}$"},additionalProperties:{type:"object",additionalProperties:!1,properties:{displayName:{type:"string",maxLength:4096},description:{type:"string",maxLength:4096},domain:{type:"string",maxLength:4096},entity:{type:"string",maxLength:4096},action:{type:"string",maxLength:4096},ownership:{type:"object",properties:{team:{type:"string",maxLength:4096},contact:{type:"string",maxLength:4096},slackChannel:{type:"string",maxLength:4096}},required:["team","contact"],additionalProperties:!1},channels:{type:"array",items:{type:"string",maxLength:4096}},tags:{type:"array",items:{type:"string",maxLength:4096}},schema:{type:"object",properties:{format:{type:"string",enum:["json_schema","avro","protobuf"]},definition:{type:"string",maxLength:4096}},required:["format","definition"],additionalProperties:!1}},required:["displayName","description","ownership"]}},exchanges:{type:"object",maxProperties:500,propertyNames:{pattern:"^[a-z0-9][a-z0-9._-]{0,126}$"},additionalProperties:{type:"object",additionalProperties:!1,properties:{type:{type:"string",enum:["direct","fanout","topic","headers"]},config:{type:"object",properties:{headersMatchMode:{}},additionalProperties:!1}}}},subscriptions:{type:"object",maxProperties:500,propertyNames:{pattern:"^[a-z0-9][a-z0-9._-]{0,126}$"},additionalProperties:{type:"object",additionalProperties:!1,properties:{channelGid:{type:"string",maxLength:4096},subscribesTo:{type:"string",enum:["messages","failures"]},idempotencyKey:{type:"string",maxLength:4096},consumerAppId:{type:"string",maxLength:4096},description:{type:"string",maxLength:4096},type:{type:"string",enum:["webhook","queue","adapter"]},filter:{type:"object",properties:{where:{type:"object",additionalProperties:{oneOf:[{type:"string",maxLength:4096},{type:"number"},{type:"boolean"}]},propertyNames:{maxLength:256,not:{enum:["__proto__","constructor","prototype"]}}},routingKey:{type:"string",maxLength:4096},subject:{type:"string",maxLength:4096}},additionalProperties:!1},subjectFilter:{type:"string",maxLength:4096},endpoint:{type:"object",properties:{url:{type:"string",format:"npayload-safe-url",maxLength:4096},method:{type:"string",enum:["POST","PUT"]},headers:{type:"object",additionalProperties:{type:"string",pattern:"^[^\\r\\n]*$",maxLength:4096},propertyNames:{pattern:"^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$"}},queueName:{type:"string",maxLength:4096}},additionalProperties:!1},delivery:{type:"object",properties:{timeoutMs:{type:"number"},retryPolicy:{type:"object",properties:{maxAttempts:{type:"number"},backoffStrategy:{type:"string",enum:["exponential","linear","constant"]},initialDelayMs:{type:"number"},maxDelayMs:{type:"number"},backoffMultiplier:{type:"number"}},additionalProperties:!1},batchSize:{type:"number"},batchWindowMs:{type:"number"}},additionalProperties:!1},dlq:{type:"object",properties:{enabled:{type:"boolean"},maxAge:{type:"number"}},required:["enabled"],additionalProperties:!1},deliveryConfig:{type:"object",properties:{maxPerMinute:{type:"number"}},additionalProperties:!1},metadata:{type:"object",additionalProperties:{oneOf:[{type:"string",maxLength:4096},{type:"number"},{type:"boolean"},{type:"null"}]},propertyNames:{maxLength:256,not:{enum:["__proto__","constructor","prototype"]}}},transformPipeId:{type:"string",maxLength:4096},transformTimeout:{type:"number"},transformOnFailure:{type:"string",enum:["deliver_raw","drop_to_dlq"]}},required:["endpoint"]}}}};async function G(e,t){try{let n=new URL("/health",e);return await D(I())(n,{signal:AbortSignal.timeout(2500)}),"reachable"}catch(n){return n instanceof E?(t.push(n),"refused"):"unreachable"}}s(G,"reachable");function se(){let e=process.env.npm_config_user_agent??"";return e.startsWith("bun")?"bun":e.startsWith("pnpm")?"pnpm":e.startsWith("yarn")?"yarn":e.startsWith("npm")?"npm":process.env.BUN_INSTALL?"bun":"unknown"}s(se,"detectPackageManager");function oe(){switch(process.platform){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";case"linux":return"Linux Secret Service (libsecret)";default:return`${process.platform} (unsupported)`}}s(oe,"keychainBackend");async function ie(){let e=await M(),t=!1;if(e)try{let m=await F();t=!!(m?.clientId&&m?.hmacSecret)}catch{t=!1}let n=!!process.env.NPAYLOAD_TOKEN,a=!!(process.env.NPAYLOAD_CLIENT_ID&&(process.env.NPAYLOAD_CLIENT_SECRET||process.env.NPAYLOAD_HMAC_SECRET)),r=U(),i=!!(r?.clientId&&r?.hmacSecret&&!N(r.clientId)&&!N(r.hmacSecret)),c=t||n||a||i,h=[];(process.env.NPAYLOAD_CLIENT_SECRET||process.env.NPAYLOAD_HMAC_SECRET)&&h.push("A client secret is set in the environment. Prefer a short-lived NPAYLOAD_TOKEN, source it from a secret manager, and never commit it to a .env file.");let o=[];c||(e||o.push(process.platform==="linux"?"No OS keychain: install and start a Secret Service (e.g. `gnome-keyring` or KWallet).":"OS keychain is not reachable on this host."),o.push("In a project: run `npx @npayload/sdk init` (provisions machine credentials into .npayload.json).","Interactive: run `npayload login` (stores the session in the OS keychain).","Headless / CI: export NPAYLOAD_CLIENT_ID + NPAYLOAD_CLIENT_SECRET (or NPAYLOAD_TOKEN)."));let l=!1,f=S(process.env.NPAYLOAD_API_URL,"apiUrl")??"https://api.npayload.com",g=S(process.env.NPAYLOAD_AUTH_URL,"authUrl")??null,$=[],L=await G(f,$),_=g?await G(g,$):null,J=L==="reachable",Q=_===null?null:_==="reachable";for(let m of $)o.push(T(`Not probed: ${m.message}`,m));L==="unreachable"&&o.push(`API endpoint ${f} is unreachable \u2014 check your network / status page.`),g&&_==="unreachable"&&o.push(`Auth endpoint ${g} is unreachable \u2014 token minting will fail until it is back.`);let P="n/a",R=B(process.cwd(),"npayload","_generated","contract.lock");if(W(R)){try{P=JSON.parse(ae(R,"utf8")).hash===K?"ok":"stale"}catch{P="stale"}P==="stale"&&o.push("npayload/_generated/contract.lock disagrees with the installed npayload contract \u2014 this project was authored against a different version; re-run `npayload validate` after upgrading (or reinstall the pinned version).")}let x="n/a";try{let m=Y(),C=B(m,"..","permissions.generated.ts"),{projectAllPermissions:Z}=await import("./chunk-EL7XOWA4.mjs"),{checkScopesDrift:X}=await import("./chunk-A7HA64P6.mjs"),A=X(await Z(),C);x=A.ok?"ok":W(C)?"stale":"missing",!A.ok&&A.reason&&o.push(A.reason)}catch{x="n/a"}return{os:process.platform,arch:process.arch,node:process.version,packageManager:se(),keychain:{reachable:e,backend:oe()},credentials:{envToken:n,envClient:a,project:i,keychain:t},authReady:c,stack:{apiUrl:f,apiReachable:J,apiProbe:L,authUrl:g,authReachable:Q,authProbe:_,contractLock:P,permissions:x},warnings:h,remediation:o}}s(ie,"buildReport");function V(e){return e==="reachable"?p.green("reachable"):e==="refused"?p.yellow("refused by this run's estate (TRANSPORT_UNAVAILABLE)"):p.red("unreachable")}s(V,"probeWords");function d(e){return e?p.green("\u2713"):p.dim("\u25CB")}s(d,"mark");function pe(e){let t=["",p.bold(" npayload doctor"),""];t.push(` ${p.dim("platform")} ${e.os} ${e.arch} \xB7 node ${e.node} \xB7 pm ${e.packageManager}`),t.push(` ${d(e.keychain.reachable)} ${p.dim("keychain")} ${e.keychain.backend} \u2014 ${e.keychain.reachable?p.green("reachable"):p.yellow("not reachable")}`),t.push(""),t.push(` ${p.bold("credentials")}`),t.push(` ${d(e.credentials.project)} project credentials (.npayload.json)`),t.push(` ${d(e.credentials.keychain)} login session in OS keychain`),t.push(` ${d(e.credentials.envClient)} NPAYLOAD_CLIENT_ID + NPAYLOAD_CLIENT_SECRET (env)`),t.push(` ${d(e.credentials.envToken)} NPAYLOAD_TOKEN (env, short-lived)`),t.push(""),t.push(` ${p.bold("stack")}`),t.push(` ${d(e.stack.apiReachable)} API ${p.dim(e.stack.apiUrl)} \u2014 ${V(e.stack.apiProbe)}`),e.stack.authUrl&&e.stack.authProbe!==null&&t.push(` ${d(e.stack.authReachable===!0)} auth ${p.dim(e.stack.authUrl)} \u2014 ${V(e.stack.authProbe)}`),e.stack.contractLock!=="n/a"&&t.push(` ${d(e.stack.contractLock==="ok")} contract.lock \u2014 ${e.stack.contractLock}`),e.stack.permissions!=="n/a"&&t.push(` ${d(e.stack.permissions==="ok")} permissions.generated.ts \u2014 ${e.stack.permissions}`),t.push("");let n=!e.stack.apiReachable||e.stack.authReachable===!1,a=e.stack.apiProbe==="refused"||e.stack.authProbe==="refused";e.authReady?a?t.push(` ${p.yellow("! credentials present, but this run's estate refused a probe \u2014 see next")}`):n?t.push(` ${p.yellow("! credentials present, but the stack is unreachable \u2014 see next")}`):t.push(` ${p.green("\u2713 ready \u2014 credentials present and the stack is reachable")}`):t.push(` ${p.red("\u2716 no credential source available")}`);for(let r of e.warnings)t.push(p.yellow(` ! ${r}`));if(e.remediation.length){t.push(""),t.push(` ${p.bold("next")}`);for(let r of e.remediation)t.push(p.dim(` \u2022 ${r}`))}return t.push(""),t.join(`
15
- `)}s(pe,"renderHuman");function Ue(e){e.command("doctor").description("diagnose OS / package manager / keychain reachability + which credential source is available").option("--output <fmt>","human | table | json | yaml | ndjson").action(async t=>{try{let n=q(t.output),a=await ie();n==="human"?process.stdout.write(pe(a)+`
16
- `):process.stdout.write(`${z(a,n)}
17
- `);let r=a.stack.authReachable===!1;(!a.authReady||!a.stack.apiReachable||r)&&(process.exitCode=1)}catch(n){v(n)}})}s(Ue,"registerDoctor");export{b as a,le as b,ge as c,be as d,ke as e,N as f,q as g,z as h,H as i,K as j,Ae as k,ie as l,Ue as m};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-MPYL6HQR.mjs";import"./chunk-455C67EN.mjs";import"./chunk-LJNU5QHZ.mjs";export{b as adminExtraCommands,d as loadExtraCommandRows,a as loadPrimusCliCommands,c as pipesExtraCommands};
@@ -1 +0,0 @@
1
- import{a}from"./chunk-2OCUKD3K.mjs";import"./chunk-6ZOPXG44.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-UMQ2SWSM.mjs";import"./chunk-YQVQTVHK.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-BMMAZIUY.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as projectAllPermissions};
@@ -1 +0,0 @@
1
- var e="5.0.4";var t=e,i="npayload",o=`${i}/${t}`;export{t as a,i as b,o as c};
@@ -1 +0,0 @@
1
- import{c as E,g as m,h as S}from"./chunk-WE3NRBO6.mjs";import{A,L as f,M as h,N as v,P as O,b as R,ba as N,d as k,da as U,ma as x}from"./chunk-YHY7Y4HD.mjs";import{a as i}from"./chunk-LJNU5QHZ.mjs";function z(n){let e=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{},o={gid:typeof e.gid=="string"?e.gid:typeof e.messageGid=="string"?e.messageGid:void 0},t={};for(let[a,d]of Object.entries(e))a==="gid"||a==="_extra"||(t[a]=d);return Object.defineProperty(o,"_extra",{value:Object.freeze(t),enumerable:!1,configurable:!0,writable:!1}),o}i(z,"toPublishReceipt");var b=new TextEncoder;function y(n){let e="";for(let o=0;o<n.length;o+=1)e+=String.fromCharCode(n[o]);return(typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}i(y,"b64url");async function J(n){return y(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",b.encode(n))))}i(J,"sha256B64url");async function K(n,e){let o={typ:"dpop+jwt",alg:"EdDSA",jwk:{kty:"OKP",crv:"Ed25519",x:n.publicKeyJwk.x}},t={jti:y(globalThis.crypto.getRandomValues(new Uint8Array(16))),htm:e.htm,htu:e.htu,iat:Math.floor((e.nowMs??Date.now())/1e3)};e.accessToken!==void 0&&(t.ath=await J(e.accessToken));let a=`${y(b.encode(JSON.stringify(o)))}.${y(b.encode(JSON.stringify(t)))}`,d=new Uint8Array(await globalThis.crypto.subtle.sign({name:"Ed25519"},n.privateKey,b.encode(a)));return`${a}.${y(d)}`}i(K,"eddsaDpopProof");var L=3e4,I=class{static{i(this,"KernelFrameDoorCredential")}opts;fetchImpl;minted;inflight;constructor(e){this.opts=e,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis)}async accessToken(){let e=this.opts.refreshMarginMs??L;return this.minted&&this.minted.expiresAt-Date.now()>e?this.minted.token:(this.inflight??=this.mint().finally(()=>{this.inflight=void 0}),this.minted=await this.inflight,this.minted.token)}proof(e,r){return K(this.opts.key,{htm:"POST",htu:e,accessToken:r})}async unit(){return O(await this.accessToken())}async mint(){let{tokenUrl:e,clientId:r}=this.opts,o=await K(this.opts.key,{htm:"POST",htu:e}),t=new URLSearchParams({grant_type:"client_credentials",client_id:r,scope:""});this.opts.appId&&t.set("app_id",this.opts.appId),this.opts.env&&t.set("env_id",this.opts.env),this.opts.clientSecret&&t.set("client_secret",this.opts.clientSecret);let d=await N(this.opts.refusal??(()=>{}),s=>new U(s.charAt(0).toUpperCase()+s.slice(1)),this.fetchImpl)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",DPoP:o},body:t.toString()}),c=await d.json().catch(()=>({}));if(!d.ok){let s=typeof c.error=="string"&&c.error!==""?c.error:"oauth_failed",l=typeof c.error_description=="string"&&c.error_description!==""?c.error_description:s;throw new k(`the token endpoint ${e} refused the kernel frame door's token (HTTP ${d.status}, ${s}): ${l}; no frame was posted.`,{code:s,status:d.status})}if(typeof c.access_token!="string"||c.access_token==="")throw new k(`the token endpoint ${e} answered no access_token for the kernel frame door; no frame was posted.`,{code:"oauth_missing_token",status:d.status});if(typeof c.token_type=="string"&&c.token_type.toLowerCase()!=="dpop")throw new k(`the token endpoint ${e} answered a ${c.token_type} token where the kernel frame door needs a DPoP-bound one; no frame was posted.`,{code:"non_dpop_token",status:d.status});let p=typeof c.expires_in=="number"&&c.expires_in>0?c.expires_in:600;return{token:c.access_token,expiresAt:Date.now()+p*1e3}}};function C(n,e){let r=n?.trim();return r!==void 0&&/^app_[a-z0-9]+$/i.test(r)?r:f(e["npayload/appId"])??f(e.appId)??f(e.app)??f(e.app_id)}i(C,"resolveProducerAppId");var $="npayload/npp/app-signing-key/v1",P=[48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32];async function H(n){let e=globalThis.crypto.subtle,r=new TextEncoder,o=await e.importKey("raw",r.encode(n.clientSecret),"HKDF",!1,["deriveBits"]),t=new Uint8Array(await e.deriveBits({name:"HKDF",hash:"SHA-256",salt:r.encode($),info:r.encode(n.clientId)},o,256)),a=new Uint8Array(P.length+t.byteLength);a.set(P,0),a.set(t,P.length),t.fill(0);try{let d=await e.importKey("pkcs8",a,{name:"Ed25519"},!0,["sign"]),c=await e.exportKey("jwk",d);return{privateKey:await e.importKey("jwk",c,{name:"Ed25519"},!1,["sign"]),publicKeyJwk:{kty:c.kty,crv:c.crv,x:c.x}}}finally{a.fill(0)}}i(H,"deriveAppNppSigningKey");async function B(){let n=globalThis.crypto.subtle,e=await n.generateKey({name:"Ed25519"},!0,["sign","verify"]);return{privateKey:e.privateKey,publicKeyJwk:await n.exportKey("jwk",e.publicKey)}}i(B,"generateNppSigningKey");function q(n){let{clientId:e,clientSecret:r}=n.config;return e&&r?H({clientId:e,clientSecret:r}):B()}i(q,"appNppSigningKeyFor");async function ge(n,e){let{privateKey:r,publicKeyJwk:o}=await q(n),t=(await n.auth.getAccessToken([])).token,a=h(t),d=C(e.appId,a),c=v(a);if(!d||!c)throw new Error(`Could not resolve appId/orgId from the access token for NPP provisioning. Claims present: ${Object.keys(a).join(", ")}`);let p=await W(n,e,o),s=globalThis.crypto.getRandomValues(new Uint32Array(1))[0],l=new x({edgeUrl:e.edgeUrl,accessToken:t,appId:d,clientId:e.clientId,jwkThumbprint:p,ed25519PrivateKey:r,...e.sequenceStore?{sequenceStore:e.sequenceStore}:{}},s),w=E(n);return w!==void 0&&S(l,w),l}i(ge,"provisionNppPublisher");async function W(n,e,r){let o;try{o=(await n.send({method:"POST",path:e.kernelHasNoBaseUrl?`${e.baseUrl.replace(/\/+$/,"")}/v1/apps/dpop-keys`:"/v1/apps/dpop-keys",body:{publicKeyJwk:r,algorithm:"EdDSA"}})).jwkThumbprint}catch(t){m(t);let a=t instanceof Error?t.message:String(t);if(/already.?registered|already.?exists|ALREADY_EXISTS/i.test(a))o=await Q(r);else throw t}return o}i(W,"registerAppNppKey");async function fe(n,e){let r=await q(n),o=n.config,t=E(n),a=new I({tokenUrl:`${o.authUrl??"https://auth.npayload.com"}/oauth/token`,clientId:o.clientId,...o.clientSecret!==void 0?{clientSecret:o.clientSecret}:{},...o.appId!==void 0?{appId:o.appId}:{},...o.env!==void 0?{env:o.env}:{},key:r,...t!==void 0?{refusal:i(G=>t.refusal(G),"refusal")}:{}}),d=await a.accessToken(),c=C(e.appId,h(d));if(!c)throw new Error(`Could not resolve appId from the kernel frame door's access token. Claims present: ${Object.keys(h(d)).join(", ")}`);let p=await W(n,e,r.publicKeyJwk),s=typeof e.producerEpoch=="function"?await e.producerEpoch(p):e.producerEpoch,l=globalThis.crypto.getRandomValues(new Uint32Array(1))[0],w=new x({edgeUrl:e.frameDoorUrl,accessToken:i(()=>a.accessToken(),"accessToken"),appId:c,clientId:e.clientId,jwkThumbprint:p,ed25519PrivateKey:r.privateKey,sequenceStore:e.sequenceStore??new A,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},kernel:{readChannel:e.readChannel,producerEpoch:s,credential:a}},l);return t!==void 0&&S(w,t),w}i(fe,"provisionKernelDoorPublisher");var V=Date.UTC(2025,0,1),X=2147483647,D=new Map;function we(n,e=Date.now()){let r=Math.floor((e-V)/1e3),o=D.get(n),t=Math.min(X,Math.max(0,r,o===void 0?0:o+1));return D.set(n,t),t}i(we,"drawClientProducerEpoch");async function Q(n){return R(n)}i(Q,"rfc7638Thumbprint");var _=class extends Error{static{i(this,"IncomingWebhookRefusal")}code;constructor(e,r){super(r),this.name="IncomingWebhookRefusal",this.code=e}};function M(n){if(n.startsWith("whk_"))return"channel";if(n.startsWith("trg_"))return"agent";throw new _("NOT_AN_INCOMING_WEBHOOK",`"${n}" names no incoming webhook: a channel's webhook id starts with whk_, an agent's webhook trigger id with trg_`)}i(M,"ownerOf");var u=i(n=>typeof n=="string"?n:"","str"),T=i(n=>{if(Array.isArray(n))return n;let e=n;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]},"rowsOf"),j=i(n=>typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():null,"iso");async function be(n){let[e,r]=await Promise.all([n.listChannelWebhooks(),n.listAgentWebhookTriggers()]),o=T(e),t=T(r).filter(s=>s.type==="webhook"),a=[...new Set(o.map(s=>u(s.channelGid)).filter(Boolean))],d=new Map;await Promise.all(a.map(async s=>{try{let l=await n.channel(s);d.set(s,u(l?.name)||null)}catch(l){m(l),d.set(s,null)}}));let c=new Map;if(t.length>0)try{for(let s of T(await n.listAgents()))c.set(u(s.gid),u(s.name))}catch(s){m(s)}return[...o.map(s=>({id:u(s.gid),name:u(s.name),deliversTo:{kind:"channel",id:u(s.channelGid),name:d.get(u(s.channelGid))??null},signingSecret:s.hasSigningSecret===!0?"set":"not set",lastDelivery:null,status:u(s.status)})),...t.map(s=>{let l=s.config??{};return{id:u(s.gid),name:u(s.name),deliversTo:{kind:"agent",id:u(s.agentGid),name:c.get(u(s.agentGid))||null},signingSecret:u(l.webhookSecret)!==""?"set":"not set",lastDelivery:j(s.lastTriggeredAt),status:s.enabled===!1?"paused":"active"}})].sort((s,l)=>s.name.localeCompare(l.name)||s.id.localeCompare(l.id))}i(be,"listIncomingWebhooks");async function Ie(n,e){if("channel"in e){let o=await n.createChannelWebhook({channelGid:e.channel,name:e.name,...e.description!==void 0?{description:e.description}:{}});return{id:u(o.gid),name:u(o.name)||e.name,deliversTo:{kind:"channel",id:e.channel},signingSecret:u(o.signingSecret)}}let r=await n.createAgentWebhookTrigger({agentGid:e.agent,name:e.name,...e.description!==void 0?{description:e.description}:{},type:"webhook",config:{},action:{goal:e.goal}});return{id:u(r.gid),name:e.name,deliversTo:{kind:"agent",id:e.agent},signingSecret:u(r.webhookSecret)}}i(Ie,"addIncomingWebhook");async function _e(n,e){if(M(e)==="agent")throw new _("ROTATION_NOT_AVAILABLE",`the signing secret of an agent's webhook trigger (${e}) cannot be rotated yet: revoke it and add a new one`);let r=await n.rotateChannelWebhookSecret(e),o=j(r.previousExpiresAt);return{id:e,signingSecret:u(r.signingSecret),...o?{previousSecretValidUntil:o}:{}}}i(_e,"rotateIncomingWebhookSecret");async function xe(n,e){return M(e)==="channel"?await n.revokeChannelWebhook(e):await n.removeAgentTrigger(e),{id:e,revoked:!0}}i(xe,"revokeIncomingWebhook");var F=class extends Error{static{i(this,"NPayloadError")}type;code;status;requestId;upgradeUrl;raw;constructor(e,r){super(e),this.name="NPayloadError",this.type=r.type,this.code=r.code,this.status=r.status,this.requestId=r.requestId,this.raw=r.raw,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,type:this.type,code:this.code,status:this.status,message:this.message,requestId:this.requestId,...this.upgradeUrl!==void 0?{upgradeUrl:this.upgradeUrl}:{}}}};var Y=new Set(["TRIAL_EXPIRED","QUOTA_EXCEEDED","PAYMENT_METHOD_REQUIRED","PLAN_REQUIRED"]),g=i(n=>typeof n=="string"&&n.length>0?n:void 0,"nonEmpty");function Pe(n){let e=new Set,r=[n];for(;r.length>0;){let o=r.shift();if(o===null||typeof o!="object"||e.has(o))continue;e.add(o);let t=o;if(typeof t.code=="string"&&Y.has(t.code)){let a=t.details!==null&&typeof t.details=="object"?t.details:void 0,d=g(t.upgradePath)??g(t.upgradeUrl)??g(a?.upgradePath)??g(a?.upgradeUrl);if(d!==void 0){let c=g(t.reason)??g(a?.reason)??g(t.message),p=g(t.product)??g(a?.product);return{code:t.code,reason:c,upgradeUrl:d,...p!==void 0?{product:p}:{}}}}for(let a of["details","body","error","data","raw"])t[a]!==void 0&&r.push(t[a])}return null}i(Pe,"extractUpgradeRefusal");export{z as a,ge as b,fe as c,we as d,_ as e,M as f,be as g,Ie as h,_e as i,xe as j,F as k,Pe as l};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-RIBBVOCC.mjs";import"./chunk-76OM2ZBO.mjs";import"./chunk-2OCUKD3K.mjs";import"./chunk-6ZOPXG44.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-UMQ2SWSM.mjs";import"./chunk-YQVQTVHK.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-BMMAZIUY.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as computeFloor,c as coversFloor,b as floorGap};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-76OM2ZBO.mjs";import"./chunk-4NWQCPI4.mjs";import"./chunk-2XQXDEXA.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{b as computePushGrant,a as reconcileOpScopes,c as syncCredentialScopes,d as syncExactGrant};
@@ -1 +0,0 @@
1
- import{i as a,j as b,k as c,l as d,m as e}from"./chunk-FNAZW7X3.mjs";import"./chunk-YQVQTVHK.mjs";import"./chunk-OA73YMB6.mjs";import"./chunk-GKDZ7663.mjs";import"./chunk-BMMAZIUY.mjs";import"./chunk-WE3NRBO6.mjs";import"./chunk-YHY7Y4HD.mjs";import"./chunk-GGXNXM73.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as CliSession,e as appCreateRefusalMessage,d as deviceLogin,b as restoreSession,c as verificationPage};
@@ -1 +0,0 @@
1
- import{$ as b,S as R,T as m,W as h,X as U,Z as k,_ as E,ba as T,da as u,la as A,w}from"./chunk-YHY7Y4HD.mjs";import{a as r}from"./chunk-LJNU5QHZ.mjs";var D=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=k(this.estate,n);return t===void 0?void 0:`${t}. ${this.cureFor(h(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=E(this.estate,t);if(a!==void 0)throw new u(g(`${a}. ${this.cureFor(h(t))}`))}}check(...n){for(let t of n){let a=this.refusal(t);if(a!==void 0)throw new u(g(a))}}with(n){return new e(U([...this.estate.named.map(t=>[t.source,t.url]),...n]),this.cureFor)}};function C(e,n){return T(t=>e.refusal(t),t=>new u(g(t)),n)}r(C,"guardedFetch");var I=Symbol("npayload.dial.refusal");function K(e){let n=new Error(e.message);return n.name="AbortError",n[I]=e,n}r(K,"carried");function v(e){return e instanceof Error?e[I]:void 0}r(v,"refusalCarriedBy");function g(e){return e.charAt(0).toUpperCase()+e.slice(1)}r(g,"capitalised");var d=new WeakMap;function _(e){return d.get(e)?.guard}r(_,"guardOf");function j(e){return d.get(e)?.tokenUrl}r(j,"tokenUrlOf");function H(e){return d.get(e)?.apiUrl}r(H,"apiUrlOf");function F(e,n){let t=n.path;for(let[a,f]of Object.entries(n.pathParams??{}))t=t.replace(`{${a}}`,encodeURIComponent(f));return e.replace(/\/+$/,"")+t}r(F,"requestUrl");function L(e,n){let t=C(n),a,f={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)}},"fetch")},s=new w({config:{...e,httpClient:f}});a=s.dispatcher;let p=`${e.authUrl??m}/oauth/token`,y=e.baseUrl??R;d.set(s,{guard:n,tokenUrl:p,apiUrl:y});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(y,i));try{return await o(i)}catch(l){throw v(l)??l}})}return s}r(L,"dialKernel");function $(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($,"withDialReason");function N(e){if(e instanceof u)throw e}r(N,"rethrowRefusal");function S(e,n){A(e,t=>n.refusal(t))}r(S,"guardTransport");export{D as a,C as b,_ as c,j as d,H as e,L as f,N as g,S as h};
@@ -1,4 +0,0 @@
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 rs}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}[rs.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 os(t){let e=await G.subtle.digest("SHA-256",Gt.encode(t));return ot(e)}i(os,"sha256B64Url");async function Ec(){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(Ec,"generateDpopKeyPair");function ss(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(ss,"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 is(t){if(t)return t();let e=G.getRandomValues(new Uint8Array(16));return ot(e)}i(is,"newJti");function as(t){try{let e=new URL(t);return e.hash="",e.search="",e.toString()}catch{return t}}i(as,"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:ss(t.publicJwk)},o={htm:e.method.toUpperCase(),htu:as(e.url),iat:n,jti:is(e.randomJti)};e.accessToken&&(o.ath=await os(e.accessToken)),e.nonce&&(o.nonce=e.nonce);let s=Yn(JSON.stringify(r)),c=Yn(JSON.stringify(o)),a=`${s}.${c}`,u=await cs(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 cs(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(cs,"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}},us=["source_network_not_allowed","source_network_not_declared"],ds=["thumbprint_not_bound"];function ft(t){return typeof t=="string"&&us.includes(t.toLowerCase())}i(ft,"isSourceNotAllowedCode");function lt(t){return typeof t=="string"&&ds.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")??ls(n)??void 0,s=typeof n=="object"&&n!==null?n:null,c=Re(fs(s)??ps(e)),a=Re(Xt(s)??hs(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&&lt(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=Es(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 fs(t){if(!t)return null;let e=Pe(t);return e?.code?e.code:t.code?t.code:null}i(fs,"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 ls(t){if(typeof t!="object"||t===null)return;let e=Pe(t);return e?.request_id??e?.requestId??t.request_id??t.requestId}i(ls,"extractRequestId");function ps(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(ps,"defaultCodeForStatus");function hs(t){return`Request failed with status ${t}`}i(hs,"defaultMessageForStatus");function Es(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(Es,"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=ws(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=gs(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 vc(t,e){return ht(t,[e])}i(vc,"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 gs(t){try{return new URL(t).origin}catch{return null}}i(gs,"safeOrigin");function ws(t){return[...t].sort().join(" ")}i(ws,"scopeKey");var ys="NPAYLOAD_TEST_RESTART_WINDOW_MS";function or(t=globalThis.process?.env){if(!t||t.VITEST!=="true")return;let e=t[ys];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=ms(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 ms(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(ms,"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 Rs=5,bs=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??Rs,this.probeAfterMs=e.probeAfterMs??bs,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 Ls}from"crypto";function he(t=Date.now){let n=BigInt(t()).toString(16).padStart(12,"0"),r=Ls(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 _s=new Set(["POST","PUT","PATCH","DELETE"]);function Ss(t,e){let n=e.toLowerCase();return Object.keys(t).some(r=>r.toLowerCase()===n)}i(Ss,"hasHeader");function Ts(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(Ts,"withoutHeader");function As(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(As,"headerValue");function vs(t){return new Promise(e=>setTimeout(e,t))}i(vs,"defaultSleep");async function Ns(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})}):vs(t)}i(Ns,"abortableSleep");function Os(t){try{return new URL(t).host}catch{return t}}i(Os,"hostOf");function Cs(t){try{return new URL(t).origin}catch{return t}}i(Cs,"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 Is(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(Is,"parseRateLimit");function Ds(t){return t.get("x-request-id")??t.get("x-npayload-request-id")}i(Ds,"requestIdOf");async function en(t,e){let n=t.fetchImpl??globalThis.fetch,r=t.circuit??new pe,o=t.sleep??((O,T)=>Ns(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=Os(e.url),d=e.method.toUpperCase(),l=_s.has(d)?e.idempotencyKey??As(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={...Ts(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&&!Ss(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(Cs(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=Is(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=Ds(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 ns=P!==void 0?P.body:await Zt(p),x=pt({status:p.status,body:ns,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 Us,Dispatcher as ks,ProxyAgent as Ps,interceptors as xs}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 Ms(t){return typeof t=="string"?new URL(t):t}i(Ms,"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 $s(){let t=rn;return typeof t.getCACertificates=="function"?t.getCACertificates("default"):rn.rootCertificates}i($s,"defaultTrustStore");var xe=class extends ks{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=xs.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 Us({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:[...$s(),...this.ca]}:{minVersion:this.tlsMin}}dispatch(e,n){if(e.origin===void 0)return this.pool.dispatch(e,n);let r=Ms(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 Ps({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 Js}from"async_hooks";var j="1.9.1";var wr=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Bs(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(Bs,"_makeCompatibilityCheck");var yr=Bs(j);var Ks=j.split(".")[0],$e=Symbol.for(`opentelemetry.js.api.${Ks}`),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 Hs="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(Hs,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",Fs=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)||Fs}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 Vs(t){return Sr(t,32)&&t!==un}i(Vs,"isValidTraceId");function qs(t){return Sr(t,16)&&t!==cn}i(qs,"isValidSpanId");function St(t){return Vs(t.traceId)&&qs(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 Ws(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 Ws(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(Ws,"isSpanContext");var Gs=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):Gs}};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 Js;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 Ys(){let t=Ot.getTracerProvider(),n=(typeof t.getDelegate=="function"?t.getDelegate():t)?.constructor?.name??"";return n!==""&&n!=="NoopTracerProvider"}i(Ys,"hostHasTracerProvider");function Xs(){Ar||Ys()&&(Ar=!0,vt.setGlobalContextManager(new pn))}i(Xs,"ensureContextManager");function hn(t){Xs();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 Qs}from"crypto";var zs=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/i;function En(t){return Qs(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*Zs(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(Zs,"parseEventStream");import{createHmac as sf,timingSafeEqual as af}from"crypto";import{readFileSync as gf,writeFileSync as wf}from"fs";var Ct="0.2.0",ei="X-NPayload-Env",ti=/^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;ri(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:(n.authUrl??"https://auth.npayload.com")+"/oauth/token",...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");ai(e);let n=oi(this.config.baseUrl??"https://api.npayload.com",e),r=e.traceparent!==void 0&&ti.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?{[ei]: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:si(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=ci(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)}}}},ni=["apiKey","api_key","orgId","org_id","tenantId","tenant_id","ownerId","hmacSecret","hmac_secret","secret","bearer"];function ri(t){for(let e of ni)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(ri,"rejectForbiddenFields");function oi(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(oi,"composeUrl");function si(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(si,"serialiseBody");function Ir(t){return t&&typeof t=="object"&&"code"in t?String(t.code):"unknown"}i(Ir,"getCode");var ii=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 ai(t){let e=[];for(let n of[t.headers,t.query])if(n)for(let r of Object.keys(n))ii.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(ai,"rejectOrgShapedRequestFields");function ci(t){let e=t?.status;return typeof e=="number"?e:void 0}i(ci,"getStatus");var h=16,Ge=144,K=64,ui=128;function Pr(t){return(t&W.PQ_HYBRID)!==0?ui:K}i(Pr,"publishSignatureLen");var Ae=32,cl=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},xr={ZSTD:1,E2E:2,HLC:4,PQ_HYBRID:64};var Mr=1,$r=0,Br={AT_MOST_ONCE:0,AT_LEAST_ONCE:1,EXACTLY_ONCE:2},ul=Br.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},Kr={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 Dr=5;function Hr(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??Br.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=Dr+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+Dr),o}i(Hr,"encodeHello");var wn=6,Te=32,bn=32,di=8+bn,fi=1,li=8,yn=4+li,Ur=5;function pi(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r,o=e;for(;o<t.byteLength;){if(o+Ur>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+Ur,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===fi){if(r!==void 0)throw new RangeError("HELLO_ACK SESSION_PARAMS carries two identity lists");r=hi(t,n,a,u)}o=u}return r}i(pi,"decodeSessionParamsEntries");function hi(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(hi,"decodeIdentityList");function Fr(t){let e=Ei(t),n=mn(e.prefix,e.nonce);return t.byteLength<=e.sigEnd?[n]:[mn(n,t.slice(e.sigEnd)),n]}i(Fr,"helloAckSigningInputs");function Ei(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(Ei,"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 Vr(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+di;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=pi(t,u);d!==void 0&&(r.identities=d)}return r}i(Vr,"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=Pr(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 gi=10;function qr(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=gi,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(qr,"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},dl=new Set([It.NONE,It.JSONPATH,It.CEL,It.ROUTING_KEY_PREFIX]);function Wr(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)":wi(t)&&e!==Ee.PUSH?"a view mode (OUTCOMES, DEAD_LETTERS, TABLE_HEAD, WINDOW, COUNTERS, UNIT_HEAD) is push-only":null}i(Wr,"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=Wr(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 fl=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Gr=new TextEncoder;function wi(t){return Number.isInteger(t)&&t>=$.OUTCOMES&&t<=$.UNIT_HEAD}i(wi,"isViewMode");var B={RECORD:0,OUTCOME:1,DEAD_LETTER:2,TABLE_HEAD:3,WINDOW:4,COUNTERS:5,UNIT_HEAD:6},yi="npk_view",mi={[B.OUTCOME]:"outcome",[B.DEAD_LETTER]:"dead_letter",[B.TABLE_HEAD]:"table_head",[B.WINDOW]:"window",[B.COUNTERS]:"counters",[B.UNIT_HEAD]:"unit_head"},ll=Gr.encode(yi),pl=[B.OUTCOME,B.DEAD_LETTER,B.TABLE_HEAD,B.WINDOW,B.COUNTERS,B.UNIT_HEAD].map(t=>[t,Gr.encode(mi[t])]);var hl={[$.OUTCOMES]:"kernel:outcomes:",[$.DEAD_LETTERS]:"kernel:dead_letters:",[$.TABLE_HEAD]:"kernel:head:",[$.WINDOW]:"kernel:window:",[$.COUNTERS]:"kernel:counters:",[$.UNIT_HEAD]:"kernel:unit_head:"};var Ri=22,bi=27,Li=27;function _i(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<=Li&&c!==Ri&&c!==bi&&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(_i,"splitHeaderTlvs");var Si=10,Ti=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?Ti:Si,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 Ai=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 Jr(t,e){Dt("channelId",e.channelId),Dt("creditDelta",e.creditDelta),Dt("projectedLagMs",e.projectedLagMs),Dt("bandwidthBudgetBps",e.bandwidthBudgetBps);let n=Ai,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(Jr,"encodeFlowCredit");function Yr(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(Yr,"decodeSysEvent");var Ut=10;function Xr(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&&_i(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(Xr,"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 vi(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+=Pr(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(vi,"frameByteLengthAt");function xt(t){let e=[],n=0;for(;n<t.byteLength;){let r=vi(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 El=Ge-h;var gl=64*1024;function Qr(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(Qr,"buildHuffTable");var wl=(()=>{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 Qr(t)})(),yl=(()=>{let t=new Uint8Array(30).fill(5);return Qr(t)})();var kr=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+kr);return n.set(Y({frameType:y.GOODBYE,flags:0,headerLen:h,sessionId:t,payloadLen:kr}),0),new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(16,e.reasonCode,!1),n}i(zr,"encodeGoodbye");function Zr(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(Zr,"encodePong");var ml=1024*1024;var je=16,Ni=144;var Oi=new Uint8Array([78,80,80,1]),Ci={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},Ii={COMPRESSED:1,ENCRYPTED:2,BATCH:4,URGENT:8,RESERVED_V2:16,EXTENDED_HEADER:32,PQ_HYBRID:64};function Di(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]!==Oi[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(Di,"decodeCommonHeader");var ae=Ni,Ui=3309;var ki=32,Pi="traceparent",Mt={STRING:0,NUMBER:1,BOOL:2,NULL:3};function xi(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(xi,"decodeAttrValue");function Mi(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=xi(f,t.slice(s+1,s+u));s+=u,o.push({key:d,value:l})}return{attributes:o,byteLength:s}}i(Mi,"decodeDeliverAttributes");var Al=new Uint8Array([78,80,80,84]);function $i(t){if(t.byteLength<80)throw new RangeError(`envelope too short for signing input: ${t.byteLength}`);return t.slice(8,80)}i($i,"canonicalDeliverSigningInput");function Bi(t){if(t.byteLength<ae)throw new RangeError(`bytes too short for DELIVER envelope: ${t.byteLength} < ${ae}`);let e=Di(t);if(e.frameType!==Ci.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&ki)!==0){let v=Mi(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===Pi),H=typeof I?.value=="string"?I.value:void 0,_=null;if(e.flags&Ii.PQ_HYBRID){let v=O,p=v+Ui;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=$i(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(Bi,"decodeDeliverFrame");var ao=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 Ki=class extends ao{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}:{}}}},Hi=class extends ao{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,Fi=0,Vi=1,qi=2,Wi=3,Gi=16,ji=17,Ji="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.",Yi="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.",Xi="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 Fi:case qi:case Wi:return await r.save({lastAccepted:c}),{answer:u,sequence:c,verdict:{kind:"stored"}};case Vi: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:Ji}};case ji:if(await r.save({lastAccepted:c}),a&&!s){o={lastAccepted:c};continue}return{answer:u,sequence:c,verdict:{kind:"conflict",reason:Yi}};case Gi:return await r.save({lastAccepted:0n}),{answer:u,sequence:c,verdict:{kind:"rewound",reason:Xi}};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},Qi={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"},eo=85,to=255,no=250,zi=1e3,co="plan_required",uo="internal_apps",Nn="/settings/billing";function fo(t){let e=t.indexOf(":");return e<0?t:t.slice(0,e)}i(fo,"reasonToken");function lo(t){return fo(t)===co}i(lo,"isKernelPlanRefusal");var po="quota_exceeded",On="/settings/billing";function ho(t){return fo(t)===po}i(ho,"isKernelQuotaRefusal");var Eo=class extends Ki{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:uo,upgradeUrl:Nn}),this.name="KernelPlanRequiredError",this.kernelStatus=t,this.kernelStatusName=Q(t)??Ye(t),this.kernelReason=e}},go=class extends Hi{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}},Zi=258,wo=3,Je=new Set([0,1,2,3]);function Q(t){return Pt(t)??Qi[t]}i(Q,"kernelStatusName");var A=16,Sn=22,ro=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)??yo[n];r!==void 0&&(this.reasonName=r)}}},yo={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 ea(){return globalThis.process?.env??{}}i(ea,"processEnv");function oo(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(oo,"classifyDoor");function mo(t={}){if(t.door!==void 0&&t.door.trim()!=="")return oo(t.door.trim(),"option");let n=(t.env??ea())[$t];return n!==void 0&&n.trim()!==""?oo(n.trim(),"env"):{kind:"edge",url:t.edgeUrl,source:"default"}}i(mo,"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 ta(t){return Uint8Array.of(t&255)}i(ta,"tlvU8");function Ce(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t>>>0,!1),e}i(Ce,"tlvU32");function na(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,t,!1),e}i(na,"tlvU64");function Xe(t,e){return t.find(n=>n.type===e)?.value}i(Xe,"findTlv");function so(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1)}i(so,"readU32");function Bt(t,e){let n=Xe(e,D.ACK_STRIDE);if(!n||n[0]!==Sn)return qr(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 Ro=3e4,bo=250;function ra(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(ra,"channelAnswerDocs");async function xn(t,e={}){let n=e.waitMs??Ro,r=e.pollMs??bo,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=ra(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 oa(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(oa,"decodeLinkedError");async function Lo(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(Lo,"encodeKernelPublishFrame");var Tn=64;function _o(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(_o,"kernelSubscribeSigningInput");async function So(t){let e;if(t.sign){e=Ne({sessionId:t.sessionId,envelope:t.envelope,consumerSignature:new Uint8Array(Tn)});let n=await t.sign(_o(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(So,"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 sa(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(sa,"tokenUnitOf");function ia(t){let e=X(t).replace(/-/g,"+").replace(/_/g,"/");return e+"=".repeat((4-e.length%4)%4)}i(ia,"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 aa=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)))}`}},To="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 ca(t){if(t==null)throw new E("KERNEL_DOOR_CONFIG",`no node key source to verify the HELLO_ACK with: ${To}`);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:Ao(t)}}i(ca,"classifyNodeKeys");function Ao(t){let e=t?.keys;if(!Array.isArray(e))throw new E("KERNEL_DOOR_CONFIG",`nodeKeys is not a JWKS document (no keys array): ${To}`);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(Ao,"ed25519KeysOf");async function io(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(io,"importVerifyKeys");async function ua(t,e){let n=ca(t);if("raws"in n)return io(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 io(Ao(o))}i(ua,"loadNodeVerifyKeys");async function da(t,e,n){for(let r of t)try{if(await De().verify({name:"Ed25519"},r,e,n))return!0}catch{}return!1}i(da,"verifiesUnderAny");function fa(){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(fa,"defaultWebSocketFactory");async function la(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(la,"messageBytes");function vo(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(vo,"deliveryTokenOf");function pa(t){if(t===void 0)return{answered:!1,accepted:!1};let e=Q(t.status)??(t.error?yo[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(pa,"ackResultOf");function ha(t){if(t===void 0||t==="beginning")return 0n;if(t==="end")return ro;let e=typeof t=="bigint"?t:t.offset;if(e<0n||e>=ro-1n)throw new RangeError(`start offset out of range: ${e} (0 \u2264 offset < 2^64 \u2212 2)`);return e}i(ha,"startCursorOf");function vn(t,e){return`${t}/${e}`}i(vn,"partitionKey");function Ea(){let t={parkedAt:void 0,moved:Promise.resolve(),wake:i(()=>{},"wake")};return t.moved=new Promise(e=>{t.wake=e}),t}i(Ea,"newFlight");function ga(t,e){t.parkedAt=e;let n=t.wake;t.moved=new Promise(r=>{t.wake=r}),n()}i(ga,"park");function wa(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(wa,"unparking");var ya=/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?):(\d{1,5})$/;function ma(t,e){let n=ya.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(ma,"redirectDoor");var No=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}}},Ra=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=mo({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 ua(e.nodeKeys,e.fetch),s=e.timeoutMs??15e3,c=e.webSocket??fa(),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 la(_.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:ia(w),...e.unit!==void 0?{unit:e.unit}:{},...e.sessionTtlSec!==void 0?{sessionTtlSec:e.sessionTtlSec}:{},...e.followRedirects===!0?{redirectOk:!0}:{}})),O=Hr({sessionId:0,nppVersionMajor:Mr,nppVersionMinor:$r,capabilityFlags:Qe|xr.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=Xr(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=Vr(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 Fr(L))if(await da(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(!ba(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??sa(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!==eo||a===void 0||s>=wo)return c;let u=ma(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=Ea(),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:ta(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 Lo({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,wa(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),ga(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:na(e.cursorId)}),e.tenant!==void 0&&r.push({type:D.TENANT_SELECT,value:ue.encode(e.tenant)});let o=this.key,s=await So({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:ha(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 No(this,e.table,u?so(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=Jr(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(pa(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(zi,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(Zr(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===to?Date.now()+no: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===eo&&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===to){let m=a.seq,g=setTimeout(()=>{let w=this.awaitingReason.get(m);w&&(this.awaitingReason.delete(m),w.waiter.resolve(w.answer))},no);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?so(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=oa(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;lo(d)?u.waiter.reject(new Eo(u.answer.result.statusCode,d)):ho(d)?u.waiter.reject(new go(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=Yr(e).frame;if(r.eventCode!==Zi)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=Bi(e),r=vo(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 ba(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(ba,"bytesEqual");var La=y.PUBLISH,jl=y.BULK_ACK,_a=48;function $n(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}i($n,"copyToArrayBuffer");async function Oo(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:La,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(Oo,"buildSignedPublishFrame");async function Co(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,_a),e}i(Co,"buildSignedSubscribeFrame");function Io(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(Io,"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 Sa(t){return F(t["npayload/orgId"])??F(t.orgId)??F(t.org)??F(t.org_id)??F(t.sub)}i(Sa,"orgOfClaims");async function Do(t){if(t!==void 0)return Sa(Bn(typeof t=="function"?await t():t))}i(Do,"orgOfCredential");var Ta=/^[a-z0-9][a-z0-9._-]{0,127}$/;function Aa(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(Aa,"fnv1aHex");function va(t){return Ta.test(t)?t:`${t.toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,110)||"x"}-h${Aa(t)}`}i(va,"kernelSafeName");function Uo(t,e){return va(`${t}.${e}`)}i(Uo,"kernelUnitFor");function ko(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(ko,"answerDocs");function Zl(t){let e=ko(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(Zl,"channelAnswerNamesKernelTable");function Po(t){for(let e of ko(t)){let n=F(e.appId),r=F(e.envId);if(n!==void 0&&r!==void 0)return Uo(n,r)}}i(Po,"channelAnswerUnit");function ep(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?Uo(n,r):void 0}i(ep,"tokenUnit");var Na={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===Kr.REJECTED_HW_ATTESTATION?"REJECTED_HW_ATTESTATION":void 0)}i(Ft,"nppStatusName");function Vt(t){return Na[t]??Ft(t)}i(Vt,"nppErrorName");var Oa=new Set(["REJECTED_AUTH","SESSION_EXPIRED","REJECTED_SIGNATURE","REJECTED_GRANT"]),Ca=new Set(["DEFERRED_RETRY","DEFERRED_UNDER_REPLICATED","REJECTED_QUOTA"]),Ia=new Set(["FRAME_MALFORMED","PROTOCOL_VIOLATION","UNSUPPORTED","REJECTED_VERSION","REJECTED_QOS"]);function sp(t){return t===void 0?"protocol":Oa.has(t)?"auth":Ca.has(t)?"deferred":Ia.has(t)?"protocol":"admission"}i(sp,"nppRefusalClass");var Da="https://api.npayload.com",Ua="https://auth.npayload.com",Mo="https://npp.npayload.com",xo="npayload.com",ka=new Map([[new URL(Da).hostname,"API"],[new URL(Ua).hostname,"auth host"],[new URL(Mo).hostname,"edge"]]);function Pa(t){return t===xo||t.endsWith(`.${xo}`)}i(Pa,"isProductionHost");function xa(t){let e;try{e=new URL(t).hostname}catch{return}try{e=decodeURIComponent(e)}catch{}return e.toLowerCase().replace(/\.+$/,"")}i(xa,"hostOf");function $o(t){let e=t?.trim();return e||void 0}i($o,"named");function Kn(t){let e=$o(t);if(e===void 0)return;let n=xa(e);if(!(n===void 0||!Pa(n)))return ka.get(n)??"host"}i(Kn,"productionRole");function Bo(t){let e=[];for(let[r,o]of t){let s=$o(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(Bo,"estateOf");var Ma=["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 Ko(t,e=n=>n){return Ma.map(n=>[e(n),t[n]])}i(Ko,"environmentSources");function Ho(t){try{let e=new URL(t).origin;return e&&e!=="null"?e:t}catch{return t}}i(Ho,"shown");function Fo(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} (${Ho(e)}): npayload's production hosts serve its production estate alone`}i(Fo,"dialRefusal");function dp(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} (${Ho(e)}): npayload's production hosts serve its production estate alone`}i(dp,"pageRefusal");function fp(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 ${Mo} is the default of its production estate alone`}i(fp,"noEdgeRefusal");function lp(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(lp,"readDotenvText");var $a=new Set([301,302,303,307,308]),Vo=20,Ba=["authorization","proxy-authorization","cookie","dpop"],Ka=["content-type","content-length","content-encoding","content-language","content-location"];function qo(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(qo,"withoutHeaders");function Ha(t){return typeof t=="string"?t:t instanceof URL?t.href:t.url}i(Ha,"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 Wo(t,e,n){return async(r,o)=>{let s=Ha(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=$a.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===Vo)throw await Hn(l),new TypeError(`fetch failed: more than ${Vo} 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=qo(b,Ka)),qt(g)!==qt(d)&&(b=qo(b,Ba)),u={...u,...C?{method:"GET",body:null}:{},...b!==void 0?{headers:b}:{}},await Hn(l),d=g}}}i(Wo,"dialFetch");var Go=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,Go,{value:!0})}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[Go]===!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]),Fa=`0x${Qe.toString(16).padStart(4,"0")}`,Va=2147483647;function qa(t){let e=t.producerEpoch;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>Va)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(qa,"assertKernelDoorOptions");var Wa=6e4,Ga=50,ja=5e3,Ja="NPAYLOAD_TEST_RESTART_WINDOW_MS";function Ya(){let t=globalThis.process?.env;if(!t||t.VITEST!=="true")return;let e=t[Ja];if(e===void 0||e==="")return;let n=Number(e);return Number.isFinite(n)&&n>=0?n:void 0}i(Ya,"harnessRestartWindowMs");function Xa(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:Ya()??Wa}i(Xa,"restartWindowFor");function Qa(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(Qa,"retryAfterMs");function Jo(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(ja,Ga*2**Math.min(t-1,16))*(.8+Math.random()*.4);return Math.min(Math.max(r??0,Math.round(s)),o)}i(Jo,"nextRepostWaitMs");function Ap(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(Ap,"describeNppRejection");function za(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(za,"linkedErrorSideband");function Za(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(Za,"upstreamFromHeaders");var ec=8*1024;function tc(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(tc,"isNppFrame");function nc(t){let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(0,ec)))}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(nc,"readUpstream");function rc(t,e,n,r){let o=t.headers.get("content-type")??void 0,{upstreamCode:s,upstreamMessage:c}=nc(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(rc,"nonFrameAnswer");function Wn(t){return`0x${t.toString(16).padStart(4,"0")}`}i(Wn,"hex16");function oc(t){for(let[e,n]of Object.entries(y))if(n===t)return e;return`0x${t.toString(16).padStart(2,"0")}`}i(oc,"frameTypeWord");function sc(t,e){return`${t.name??"UNREGISTERED_CODE"} (ERROR ${Wn(t.code)}, HTTP ${e})${t.reason?`: ${t.reason}`:""}`}i(sc,"describeNppRefusal");function ic(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(ic,"readFrameDoorError");function ac(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=ic(e,o);if(f)return new Vn(`npp: the frame door ${n} refused the frame${a}: ${sc(f,t.status)}`,f,c)}let d=u===y.ERROR?"an ERROR frame too short or too malformed to carry its code":`a ${oc(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(ac,"frameDoorRefusal");var Zo=Symbol.for("npayload.transport.npp"),es=Symbol.for("npayload.transport.npp.edge"),ts=Symbol.for("npayload.transport.npp.frameGuard");function vp(t){return typeof t=="object"&&t!==null&&t[Zo]===!0}i(vp,"isNppTransport");function cc(t){return t[es]}i(cc,"nppTransportEdge");function Np(t,e){Object.defineProperty(t,ts,{value:e,configurable:!0})}i(Np,"guardFrames");function Yo(t,e){let n=t[ts];if(n!==void 0)return n(e);let r=typeof process<"u"?process.env:{},o=Bo([["the transport's edgeUrl",cc(t)],...Ko(r)]),s=Fo(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(Yo,"frameRefusal");var Xo=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&&qa(e.kernel),this.cfg=e,Object.defineProperty(this,Zo,{value:!0}),Object.defineProperty(this,es,{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 Co({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=Yo(this,s);if(c!==void 0)throw new ge(`npp: ${c}`,"npp",{url:s});this.credentialOrg??=await Do(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()+Xa(r.restartWindowMs??this.cfg.restartWindowMs),l=this.cfg.kernel?.credential,m=Wo(g=>Yo(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=Jo(g,d,f,void 0);if(P!==void 0){await Qo(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=tc(C)?xt(C):[],T=O[0],I=T!==void 0&&T[4]===y.BULK_ACK?Io(T):void 0;if(zo.has(R.status)||I?.status===ve.DEFERRED_RETRY){let p=Jo(g,d,f,Qa(R.headers));if(p!==void 0){await Qo(p);continue}}if(T===void 0)throw rc(R,C,s,g);if(!I)throw ac(R,T,s,g,o);let _=I.messageGid??R.headers.get("X-NPP-Message-Gid")??void 0,L=za(O,I.seq),v=Za(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":Fa,"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 Oo({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)??Po(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 Qo(t){return new Promise(e=>setTimeout(e,t))}i(Qo,"sleep");export{Ec 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,vc as u,Zs as v,Cr as w,y as x,ve as y,kn as z,Pn as A,ze as B,$t as C,uo as D,Nn as E,lo as F,E as G,mo as H,aa as I,No as J,Ra as K,F as L,Bn as M,Sa as N,Zl as O,ep as P,Ft as Q,sp as R,Da as S,Ua as T,Mo as U,$o as V,Kn as W,Bo as X,Ko as Y,Fo as Z,dp as _,fp as $,lp as aa,Wo as ba,ye as ca,ge as da,Fn as ea,we as fa,Vn as ga,qn as ha,Ap as ia,vp as ja,cc as ka,Np as la,Xo as ma};
@@ -1,2 +0,0 @@
1
- import{a as A}from"./chunk-BMMAZIUY.mjs";import{a as g}from"./chunk-WE3NRBO6.mjs";import{S as d,X as p,Y as u,aa as f}from"./chunk-YHY7Y4HD.mjs";import{a as r}from"./chunk-LJNU5QHZ.mjs";function s(e,n,t){return e||t}r(s,"resolveEndpoint");function O(e,n,t=[]){return A({edge:s(e,"edgeUrl"),npp:!0,guard:n,provisioning:t})}r(O,"resolveEdgeUrl");function P(){return"production"}r(P,"resolveTargetEnv");import{existsSync as l,readFileSync as h}from"fs";import{join as o,resolve as a}from"path";function v(e){if(!l(e))return{};try{return f(h(e,"utf8"))}catch{return{}}}r(v,"dotenvAt");function D(e){try{return l(e)?h(e,"utf8"):void 0}catch{return}}r(D,"textAt");function y(e=process.cwd()){let n=a(e);for(let t=0;t<5;t+=1){if(l(o(n,".npayload.json")))return n;let i=o(n,"..");if(i===n)break;n=i}return a(e)}r(y,"projectRoot");var U=!1;function E(e){if(e!==void 0)return v(o(e,".env"));let n=a(process.cwd()),t=y(n);if(t!==n&&!U){let i=D(o(n,".env"));i!==void 0&&i!==D(o(t,".env"))&&(U=!0,process.stderr.write(`npayload: reading the project's .env (${o(t,".env")}), the one beside its .npayload.json, for this run's estate; the .env in ${n} differs and is not read.
2
- `))}return v(o(t,".env"))}r(E,"projectDotenv");function L(e=[],n){return p([...u(process.env),...u(E(n),t=>`${t} in the project's .env`),...e])}r(L,"cliEstate");function _(e){return`${e==="auth host"?"Name that estate's auth host with NPAYLOAD_AUTH_URL, or name none so the CLI mints at that estate's API":e==="edge"?"Set NPAYLOAD_EDGE_URL to the edge of that estate":"Name that estate's API with NPAYLOAD_API_URL (the CLI dials no address the project's .env names: export it)"}, or name nothing outside npayload's production hosts to use its production estate.`}r(_,"cliCure");function m(e=[],n){return new g(L(e,n),_)}r(m,"cliGuard");function I(e){let n=m(e!==void 0?[["the lane gateway",e]]:[]),t=e??s(process.env.NPAYLOAD_API_URL,"apiUrl",d),c=s(process.env.NPAYLOAD_AUTH_URL,"authUrl")??(n.production?void 0:t);return{apiUrl:t,...c!==void 0?{authUrl:c}:{},guard:n}}r(I,"cliEndpoints");function w(e){let n=e??s(process.env.NPAYLOAD_AUTH_URL,"authUrl"),t=s(process.env.NPAYLOAD_API_URL,"apiUrl");return{base:(n??(m().production?void 0:t)??d).replace(/\/+$/,"")}}r(w,"cliSessionBase");export{s as a,O as b,P as c,E as d,m as e,I as f,w as g};