palbase 0.66.0 → 0.68.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 (96) hide show
  1. package/README.md +3 -2
  2. package/dist/ai/index.js +2 -2
  3. package/dist/ai-sdk/index.js +2 -2
  4. package/dist/backend/engine.js +2 -2
  5. package/dist/backend/env.js +1 -1
  6. package/dist/backend/index.js +8 -8
  7. package/dist/backend/stack.js +1 -1
  8. package/dist/backend/test.js +2 -2
  9. package/dist/chunks/{YO7F2OI2.js → 22GRHCVI.js} +1 -1
  10. package/dist/chunks/{GYB7XBYV.js → 2ZHSNWVZ.js} +2 -2
  11. package/dist/chunks/3OP3YJ63.js +22 -0
  12. package/dist/chunks/{QT7PHIRR.js → 4YV35XDP.js} +2 -2
  13. package/dist/chunks/{PQ23MXWT.js → 5ZXXBM6L.js} +2 -2
  14. package/dist/chunks/{QKAKVJLA.js → 622BI7EV.js} +1 -1
  15. package/dist/chunks/65QZXK2S.js +2 -0
  16. package/dist/chunks/{HECZUS65.js → 7SGTDHXJ.js} +2 -2
  17. package/dist/chunks/{UZERPL37.js → D6EUPFUR.js} +2 -2
  18. package/dist/chunks/EGWQ3EJE.js +21 -0
  19. package/dist/chunks/{4DOKNJUJ.js → EJAGO6ZV.js} +2 -2
  20. package/dist/chunks/{FFRCUMXB.js → F4B6ELAN.js} +2 -2
  21. package/dist/chunks/IZWB7FGX.js +6 -0
  22. package/dist/chunks/{243727GR.js → J7WJF7F4.js} +2 -2
  23. package/dist/chunks/{REON7CA7.js → LUUXXMXH.js} +1 -1
  24. package/dist/chunks/MVY4K43S.js +13 -0
  25. package/dist/chunks/{PZXACOXA.js → OWLXCD3D.js} +1 -1
  26. package/dist/chunks/PP7MW4OT.js +2 -0
  27. package/dist/chunks/{2DGYQO2K.js → QFZ4GCJH.js} +2 -2
  28. package/dist/chunks/QQUIM4VK.js +2 -0
  29. package/dist/chunks/UJLFALKX.js +2 -0
  30. package/dist/chunks/{7JAVCOPA.js → XJLAH42O.js} +1 -1
  31. package/dist/chunks/{ZV6WG4DE.js → XU4G5W72.js} +1 -1
  32. package/dist/chunks/YCDAV3WO.js +2 -0
  33. package/dist/cli.js +275 -273
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +264 -0
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +4 -4
  50. package/package.json +7 -2
  51. package/types/backend/src/decorators.d.ts +1 -8
  52. package/types/backend/src/idempotency.d.ts +18 -0
  53. package/types/backend/src/index.d.ts +1 -1
  54. package/types/backend/src/strings-files.d.ts +5 -6
  55. package/types/cloud/src/generated/project.d.ts +2 -1
  56. package/types/cloud/src/generated/studio.d.ts +3 -3
  57. package/types/internal/src/event.d.ts +1 -1
  58. package/types/internal/src/modules/ai.d.ts +1 -1
  59. package/types/internal/src/modules/analytics.d.ts +1 -1
  60. package/types/internal/src/modules/events.d.ts +5 -4
  61. package/types/internal/src/modules/{purchases.d.ts → iap.d.ts} +2183 -2438
  62. package/types/internal/src/modules/index.d.ts +2 -1
  63. package/types/internal/src/modules/journeys.d.ts +1 -1
  64. package/types/internal/src/modules/notify.d.ts +3 -3
  65. package/types/internal/src/modules/payments.d.ts +3286 -0
  66. package/types/internal/src/modules/stores.d.ts +7 -7
  67. package/types/server/src/{purchases.d.ts → iap.d.ts} +7 -7
  68. package/types/server/src/index.d.ts +2 -1
  69. package/types/server/src/payments.d.ts +65 -0
  70. package/types/server/src/server.d.ts +4 -1
  71. package/types/web/src/client.d.ts +6 -3
  72. package/types/web/src/{purchases.d.ts → iap.d.ts} +46 -56
  73. package/types/web/src/inapp.d.ts +5 -5
  74. package/types/web/src/index.d.ts +2 -1
  75. package/types/web/src/messaging.d.ts +1 -0
  76. package/types/web/src/notify.d.ts +2 -2
  77. package/types/web/src/payments-ui/index.d.ts +7 -0
  78. package/types/web/src/payments-ui/payment-sheet.d.ts +13 -0
  79. package/types/web/src/payments-ui/qr.d.ts +9 -0
  80. package/types/web/src/payments-ui/saved-cards-view.d.ts +7 -0
  81. package/types/web/src/payments-ui/spend-qr-view.d.ts +8 -0
  82. package/types/web/src/payments-ui/theme.d.ts +16 -0
  83. package/types/web/src/payments-ui/types.d.ts +149 -0
  84. package/types/web/src/payments-ui/wallet-topup-sheet.d.ts +7 -0
  85. package/types/web/src/payments.d.ts +281 -0
  86. package/types/web/src/paywall/placement.d.ts +6 -8
  87. package/types/web/src/screen/assets.d.ts +1 -1
  88. package/types/web/src/screen/resolve.d.ts +3 -3
  89. package/dist/chunks/47OT2TAE.js +0 -6
  90. package/dist/chunks/GS7AQ2KQ.js +0 -2
  91. package/dist/chunks/GVC6OZMF.js +0 -13
  92. package/dist/chunks/L5DVXXH3.js +0 -2
  93. package/dist/chunks/MTOW4UUP.js +0 -2
  94. package/dist/chunks/V7X2RHTR.js +0 -21
  95. package/dist/chunks/ZA5NYGQH.js +0 -22
  96. package/dist/chunks/ZY6P5WKM.js +0 -2
@@ -0,0 +1,6 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import"./XU4G5W72.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
3
+ `)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
4
+ `})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
5
+ ${o.map(a=>`- ${a}`).join(`
6
+ `)}`);return{routes:s,warnings:r.warnings()}}export{b as ContractAnalysisError,Gt as analyzeProject,Dt as analyzeRoutes};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./2DGYQO2K.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./QFZ4GCJH.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
2
  var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as N,d as I,e as R}from"./D6EUPFUR.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./LUUXXMXH.js";import{d as A}from"./J7WJF7F4.js";import{a as E,b as z,c as T,e as j}from"./QFZ4GCJH.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
+ `);let t=[],s=this.pending.indexOf(`
4
+ `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
5
+ `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
6
+ `)}return t}};async function*Te(n,e){let t=n.getReader(),s=new TextDecoder,r=new B;try{for(;;){let{done:o,value:d}=await t.read();if(o)break;for(let a of r.consume(s.decode(d,{stream:!0}))){if(a.event==="error")throw new p("network",{code:"stream_failed",message:`stream failed: ${a.payload}`});let l;try{l=JSON.parse(a.payload)}catch{throw new p("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${a.payload.slice(0,120)}`})}yield E(l)}}}finally{e.abort();try{await t.cancel()}catch{}}}var dt={},Ie=new WeakMap;function zt(n,e,t,s,r,o=()=>{}){Ie.set(n,{project:e,machine:t,storage:s,socket:r,me:o})}var Pe=new Map,Re=new WeakMap;function Qt(n,e,t,s,r,o){if(!de(e))throw new p("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let d=ue(n);if(!le(t))throw new TypeError(`${JSON.stringify(String(t))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ce(s),Me(r);for(let a of Object.keys(r))if(ae(a))throw Oe(a);if(o!==void 0)ft(o);else if($e(r))throw new p("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Pe.get(e)??lt(e)).set(d,{machine:t,url:s,tree:r,...o?{transit:{...o}}:{}})}function lt(n){let e=new Map;return Pe.set(n,e),Object.defineProperty(dt,n,{configurable:!0,get(){return ct(this,n,e)}}),e}function ct(n,e,t){let s=Ie.get(n);if(!s)return;let r=t.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...t.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=Re.get(n);o||Re.set(n,o=new Map);let d=o.get(e);if(d?.registration===r)return d.ns;let a={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},l=Object.assign({call:(f,c,h)=>wt(a.machine,f,c,h),join:(f,c,h)=>Ee(s.socket,f,c,h,s.me,be(s.storage))},qe(r.tree,a));return o.set(e,{registration:r,ns:l}),l}function Oe(n){return new p("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(n)}: the name is reserved.`})}function F(n){return typeof n.path=="string"&&typeof n.method=="string"}function ut(n,e){if(n.pathParams!==void 0){if(!Array.isArray(n.pathParams)||!n.pathParams.every(t=>typeof t=="string"))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let t of n.pathParams)if(!n.path.includes(`{${t}}`))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${t}' has no '{${t}}' placeholder in the path.`})}if(n.sse!==void 0&&typeof n.sse!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(n.idempotent!==void 0&&typeof n.idempotent!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(n.upload!==void 0&&typeof n.upload!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(n.upload===!0&&(n.method!=="POST"||n.sse===!0))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(n.sse===!0&&n.input==="query")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(n.input!==void 0&&n.input!=="body"&&n.input!=="query"&&n.input!=="none")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(n.encryption!==void 0&&pt(n,e),n.errors!==void 0){for(let[t,s]of Object.entries(n.errors))if(typeof s!="function")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${t}'] must be a function.`})}}function pt(n,e){let t=n.encryption,s=r=>new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof t!="object"||t===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let d=t[r];if(d!==void 0&&(!Array.isArray(d)||!d.every(a=>typeof a=="string"&&o.some(l=>a===l||a.startsWith(l.endsWith("/")?l:`${l}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(n.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(n.sse===!0&&(t.response?.length??0)>0)throw s("of a streamed answer is none")}function $e(n){return F(n)?n.encryption!==void 0:Object.values(n).some(e=>$e(e))}function ft(n){if(typeof n!="object"||n===null||typeof n.projectId!="string"||!/^[0-9a-f-]{36}$/.test(n.projectId)||typeof n.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(n.signer))throw new p("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Me(n){if(typeof n!="object"||n===null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[t,s]of Object.entries(n)){if(O(t))throw Oe(t);typeof s=="object"&&s!==null&&F(s)?(s.method=s.method.toUpperCase(),ut(s,s.path)):Me(s)}}function qe(n,e){if(F(n))return n.upload===!0?async(...s)=>yt(e,n,s):async(...s)=>Ge(e.machine(),n,s,e.transit);let t={};for(let[s,r]of Object.entries(n))t[s]=qe(r,e);return t}function J(n){if(n==null)return"";let e=Object.entries(n).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new p("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function je(n,e,t){try{return T(n.path,e,t)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(t);throw new p("validation",{code:"invalid_path_parameter",message:`${n.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Ae(n,e){let t=n.pathParams??[],s=n.path;for(let r=0;r<t.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new p("validation",{code:"missing_path_param",message:`${n.path}: path parameter '${t[r]}' must be a string or number`});s=s.replace(`{${t[r]}}`,je(n,`path parameter '${t[r]}'`,o))}return s}var ht=new Set(["POST","PUT","PATCH","DELETE"]);async function Ge(n,e,t,s){let r=e.pathParams??[],o=Ae(e,t),d=o;if(e.input==="none"&&t.length>r.length+1)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:t[r.length],l=e.input==="none"?r.length:r.length+1,f=t[l],c;if(e.input==="query")d+=J(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new p("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else c=a;let h={...f?.headers};if(ht.has(e.method)&&!Object.keys(h).some(y=>y.toLowerCase()==="idempotency-key")&&(h["Idempotency-Key"]=A()),e.encryption!==void 0){if(!s)throw new p("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return gt(n,e,o,a,c,h,f?.signal,r.map((y,i)=>String(t[i])),s)}try{return e.sse===!0?await Be(n,e,d,c,h,f?.signal):await Ke(n,e,d,c,h,f?.signal)}catch(y){throw H(e,y)}}async function gt(n,e,t,s,r,o,d,a,l){let f=e.encryption;for(let c=0;;c++){let h=await _e(l.project,l.config,e.method,e.path,a,c>0);try{let y=e.input==="query"?t+J(await L(h,s,"/query",f.request)):t,i=await L(h,r,"/body",f.request),u={...o,[Q]:h.header};return e.sse===!0?await Be(n,e,y,i,u,d):E(await Se(h,await Ke(n,e,y,i,u,d),f.response,`${e.method} ${e.path}`))}catch(y){if(c===0&&Ce(y))continue;throw H(e,y)}}}function H(n,e){return n.errors&&ie(e)&&Object.hasOwn(n.errors,e.code)?n.errors[e.code](e):e}var mt=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function yt(n,e,t){let s=e.pathParams??[],r=Ae(e,t),o=e.input==="none"?s.length:s.length+1;if(t.length>o+2)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let d=e.input==="none"?void 0:t[s.length],a=t[o],l=t[o+1];if(!(a instanceof Blob))throw new p("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let f=`/storage/upload/${n.name}/${je(e,"the route",r.slice(1))}`;e.input==="query"&&(f+=J(d));let c=vt(e.input==="query"?void 0:d,a),h=c.body.size,y=0,i=u=>{y=u;try{l?.onProgress?.({loaded:u,total:h})}catch{}};l?.onProgress&&i(0);try{let u;try{let m={op:`Upload ${e.path}`,method:"POST",path:f,auth:mt,answers:Ne,body:{kind:"raw",contentType:c.type,value:c.body},signal:l?.signal,...l?.onProgress?{onUploadProgress:k=>i(k)}:{}};u=(await n.storage.send(m)).data}catch(m){throw P(m)?D(m):m}return l?.onProgress&&y<h&&i(h),await Le(e,u,l?.signal)}catch(u){throw H(e,u)}}function vt(n,e){let t=`Palbase-${A()}`,s=a=>a.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(a,l)=>`--${t}\r
7
+ Content-Disposition: form-data; ${a}\r
8
+ Content-Type: ${l}\r
9
+ \r
10
+ `,d=[];return n!==void 0&&d.push(o('name="body"',"application/json"),JSON.stringify(n),`\r
11
+ `),d.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
+ --${t}--\r
13
+ `),{body:new Blob(d),type:`multipart/form-data; boundary=${t}`}}async function wt(n,e,t,s){if(typeof e!="string"||e===""||e==="/")throw new p("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Ge(n(),{method:"POST",path:r},[t,s])}var Ne=Object.fromEntries(Array.from({length:100},(n,e)=>[200+e,"raw"])),bt=[["userJWT"],[]];async function De(n,e,t,s,r,o){let d={op:`${e.method} ${e.path}`,method:e.method,path:t,auth:bt,answers:Ne,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await n.send(d)).data}catch(a){throw P(a)?D(a):a}}async function Ke(n,e,t,s,r,o){return Le(e,await De(n,e,t,s,r,o),o)}async function Le(n,e,t){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw t?.aborted?o:new p("network",{code:"network_error",message:`${n.method} ${n.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return E(JSON.parse(r))}catch(o){throw new p("decode",{code:"invalid_json",message:`${n.method} ${n.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function Be(n,e,t,s,r,o){let d=new AbortController;o&&(o.aborted?d.abort():o.addEventListener("abort",()=>d.abort(),{once:!0}));let a=await De(n,e,t,s,{accept:"text/event-stream",...r},d.signal);if(!a.body)throw new p("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:a.status});return Te(a.body,d)}export{p as a,ie as b,Ue as c,de as d,be as e,M as f,dt as g,zt as h,Qt as i};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
2
  function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{lstat as E,mkdir as k,readdir as b,readFile as j,rename as F,rm as J,writeFile as R}from"node:fs/promises";import{join as $}from"node:path";var o="palbase/strings",g="_meta.json",m=3,S=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function w(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function O(r,t){try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not JSON: ${n.message}`)}}async function M(r){let t=$(r,o);try{if(!(await E(t)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let n=new Map;for(let e of await b(t,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);n.set(e.name,await j($(t,e.name),"utf8"))}return n.size===0?void 0:n}async function N(r){let t=await M(r);if(t===void 0)return;let n=t.get(g);if(n===void 0)throw new Error(`${o}/${g} is missing: it names the source language, and without it the language files are not a table`);let e=O(n,`${o}/${g}`);if(!S(e))throw new Error(`${o}/${g}: not a JSON object`);let c=e.version;if(c!==m)throw new Error(`${o}/${g}: version ${JSON.stringify(c)} is not one this reads (${m})`);let s=e.source;if(typeof s!="string"||w(s)!==s)throw new Error(`${o}/${g}: source ${JSON.stringify(s)} is not a language tag as it is written (${w(String(s))??"en, en-US, zh-Hans"})`);let f=new Map;for(let u of[...t.keys()].sort()){if(u===g)continue;let i=u.slice(0,-5),a=`${o}/${u}`,l=w(i);if(l===void 0)throw new Error(`${a}: ${JSON.stringify(i)} is not a language tag`);if(l!==i)throw new Error(`${a}: the language is written ${l} \u2014 name the file ${l}.json`);if(i===s)throw new Error(`${a}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${a}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let d=O(t.get(u),a);if(!S(d))throw new Error(`${a}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[p,y]of Object.entries(d)){if(typeof y!="string")throw new Error(`${a}: the translation of ${JSON.stringify(p)} is not a string`);h.set(p,y)}f.set(i,h)}return{format:c,source:s,languages:f}}async function P(r){let t=await N(r);if(t===void 0)return;let n={};Object.setPrototypeOf(n,null);for(let[e,c]of t.languages)for(let[s,f]of c)Object.hasOwn(n,s)||(n[s]={},Object.setPrototypeOf(n[s],null)),n[s][e]=f;return{source:t.source,locales:[t.source,...t.languages.keys()],strings:n}}export{P as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
2
- import{a as g,b}from"./7JAVCOPA.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,b}from"./XJLAH42O.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{l as w}from"./65QZXK2S.js";import{b as c}from"./QFZ4GCJH.js";var P=new Set(["succeeded","requires_capture","failed","canceled","expired"]);function S(o){return P.has(o)}var W=new Set(["payments.payment.succeeded","payments.payment.failed","payments.payment.canceled","payments.payment.requires_capture"]),E=new Set(["payments.wallet.balance_changed","payments.wallet.hold_changed"]);function T(o){if(typeof o!="object"||o===null)return null;let e=o;return e.source!=="palbase.payments"||typeof e.intent_id!="string"||e.intent_id.length===0||typeof e.status!="string"||e.status.length===0?null:{source:"palbase.payments",intent_id:e.intent_id,status:e.status,...typeof e.decline_code=="string"&&e.decline_code.length>0?{decline_code:e.decline_code}:{},...typeof e.return_url=="string"&&e.return_url.length>0?{return_url:e.return_url}:{}}}var A={insufficient_funds:"Insufficient funds on this card. Please try another payment method.",card_declined:"Your card was declined by the issuing bank.",do_not_honor:"Your bank declined this transaction. Please contact your bank or use another card.",expired_card:"This card has expired. Please use a valid card.",incorrect_cvc:"The security code (CVC/CVV) is incorrect.",incorrect_number:"The card number is invalid.",invalid_expiry:"The card expiration date is invalid.",authentication_required:"Additional 3D Secure verification is required by your bank.",three_ds_failed:"3D Secure verification failed or was canceled.",otp_invalid:"The verification code is incorrect. Please try again.",otp_expired:"The verification code has expired. Please request a new one.",fraud_suspected:"This transaction was declined for security reasons.",velocity_exceeded:"Too many failed payment attempts. Please wait a moment and try again.",limit_exceeded:"This transaction exceeds your card limit.",card_not_permitted:"This card is not enabled for online or international transactions.",processing_error:"A temporary payment processing error occurred. Please try again.",provider_unavailable:"The payment provider is temporarily unavailable. Please try again.",wallet_frozen:"This wallet is currently frozen and cannot be charged.",wallet_insufficient_balance:"Insufficient wallet balance for this payment."};function B(o){return o?A[o]??"Payment was declined. Please try another payment method.":"Payment could not be completed. Please try again."}var _=class{api;profile;methods;wallet;subscriptions;session;socket;ref;origin;walletListeners=new Set;walletWatch;walletFollowing;lastBalances;eventListeners=new Set;eventWatch;eventFollowing;constructor(e,t,i,s,d){this.api=w.client(e),this.session=t,this.socket=i,this.ref=s,this.origin=d,this.profile={get:async n=>(await this.api.getMyProfile({signal:n?.signal})).data,update:async(n,a)=>(await this.api.updateMyProfile({body:n,signal:a?.signal})).data},this.methods={list:async n=>(await this.api.listMyMethods({signal:n?.signal})).data.methods,add:async(n={})=>{let a={...n.channel!==void 0?{channel:n.channel}:{},...n.vault!==void 0?{vault:n.vault}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}};return(await this.api.addMyMethod({body:a,signal:n.signal})).data.next_action},remove:async(n,a)=>{await this.api.deleteMyMethod({path:{method_id:n},signal:a?.signal})}},this.wallet={balances:async n=>{let a=this.session.snapshot()?.userId,l=(await this.api.listMyWallets({signal:n?.signal})).data.balances;return this.walletWatch&&this.walletWatch.userId===a&&this.offerBalances(this.walletWatch,l),l},balance:async(n,a)=>(await this.wallet.balances(a)).find(u=>u.wallet_key===n),topUp:async n=>{let a={wallet_key:n.walletKey,amount:n.amount,...n.channel!==void 0?{channel:n.channel}:{},...n.methodId!==void 0?{method_id:n.methodId}:{},...n.saveMethod!==void 0?{save_method:n.saveMethod}:{},...n.useMasterpass!==void 0?{use_masterpass:n.useMasterpass}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}},l=n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:void 0;return(await this.api.topUpMyWallet({body:a,headers:l,signal:n.signal})).data},createSpendToken:async n=>{let a={wallet_key:n.walletKey,...n.maxAmount!==void 0?{max_amount:n.maxAmount}:{},...n.ttlSeconds!==void 0?{ttl_seconds:n.ttlSeconds}:{}};return(await this.api.createMySpendToken({body:a,signal:n.signal})).data},onChange:n=>this.onWalletChange(n)},this.subscriptions={list:async n=>(await this.api.listMySubscriptions({query:{limit:n?.limit,cursor:n?.cursor},signal:n?.signal})).data,cancel:async(n,a)=>(await this.api.cancelMySubscription({path:{subscription_id:n},signal:a?.signal})).data}}async capabilities(e={}){return(await this.api.getCapabilities({query:{...e.currency!==void 0?{currency:e.currency}:{},...e.channel!==void 0?{channel:e.channel}:{}},signal:e.signal})).data}async installments(e){let t={amount:e.amount,currency:e.currency,...e.bin!==void 0?{bin:e.bin}:{},...e.methodId!==void 0?{method_id:e.methodId}:{},...e.channel!==void 0?{channel:e.channel}:{}};return(await this.api.lookupInstallments({body:t,signal:e.signal})).data}async getIntent(e,t={}){return(await this.api.getIntent({path:{intent_id:e},query:t.clientSecret?{client_secret:t.clientSecret}:void 0,signal:t.signal})).data}async confirm(e,t={}){let i={...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.methodId!==void 0?{method_id:t.methodId}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{},...t.useMasterpass!==void 0?{use_masterpass:t.useMasterpass}:{},...t.phone!==void 0?{phone:t.phone}:{},...t.buyer!==void 0?{buyer:t.buyer}:{},...t.installments!==void 0?{installments:t.installments}:{},...t.providerOptions!==void 0?{provider_options:t.providerOptions}:{}},s=t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0;return(await this.api.confirmIntent({path:{intent_id:e},body:i,headers:s,signal:t.signal})).data}async submitOtp(e,t){let i={challenge_id:t.challengeId,otp:t.otp,...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{}};return(await this.api.submitIntentOtp({path:{intent_id:e},body:i,signal:t.signal})).data}async portal(e,t={}){let i={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createMyPortal({body:i,signal:t.signal})).data.url}async waitForIntent(e,t={}){let i=t.timeoutMs??3e5;if(t.signal?.aborted)throw t.signal.reason;return new Promise((s,d)=>{let n=!1,a=!1,l=!1,u=this.socket.channel(`payment_intent:${this.ref}:${e}`),h=()=>{v!==void 0&&clearTimeout(v),x(),u.leave(),y.removeEventListener?.("message",g),t.signal?.removeEventListener("abort",f)},I=r=>{n||(n=!0,h(),s(r))},p=r=>{n||(n=!0,h(),d(r))},m=async()=>{if(!n){if(a){l=!0;return}a=!0;try{for(;;){l=!1;try{let r=await this.getIntent(e,{clientSecret:t.clientSecret,signal:t.signal});if(S(r.status)){I(r);return}}catch(r){if(t.signal?.aborted){p(t.signal.reason);return}if(r instanceof c&&(r.status===401||r.status===403||r.status===404)){p(r);return}}if(n||!l)return}}finally{a=!1}}},x=u.on("broadcast",r=>{typeof r.event=="string"&&W.has(r.event)&&m()}),g=r=>{if(r.origin&&r.origin!=="null"&&r.origin!==this.origin)return;let b=T(r.data);b&&b.intent_id===e&&m()},f=()=>p(t.signal?.reason),y=globalThis;y.addEventListener?.("message",g),t.signal?.addEventListener("abort",f,{once:!0});let v=i>0?setTimeout(()=>{p(new c({op:"WaitForIntent",status:0,code:"payment_timeout",message:`timed out waiting for payment intent ${e}`}))},i):void 0;u.join().catch(()=>{}),m()})}async present(e,t={}){let i=t.clientSecret??e.client_secret,s=e.status!==void 0&&e.amount!==void 0?e:await this.getIntent(e.id,{clientSecret:i,signal:t.signal});for(let d=0;d<6;d++){if(S(s.status))return s;let n=s.next_action;if(!n||n.type==="none")return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal});if(n.type==="redirect"){if(!n.url)throw new c({op:"PresentIntent",status:0,code:"invalid_next_action",message:"redirect next_action is missing url"});if(t.onRedirect)await t.onRedirect(n.url,n);else{let a=globalThis.location;if(!a)throw new c({op:"PresentIntent",status:0,code:"redirect_unavailable",message:"provide onRedirect in non-browser environments"});a.assign(n.url)}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}if(n.type==="embed"){let a;if(t.onEmbed){let l=await t.onEmbed(n);typeof l=="function"&&(a=l)}else if(t.container)a=k(t.container,n);else throw new c({op:"PresentIntent",status:0,code:"embed_container_required",message:"provide container or onEmbed to present an embedded 3DS/checkout action"});try{return await this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}finally{a?.()}}if(n.type==="otp"||n.type==="masterpass"){if(!t.onOtp)throw new c({op:"PresentIntent",status:0,code:"otp_handler_required",message:"provide onOtp to complete an OTP or Masterpass verification step"});let a=n.challenge_id??"",l=await t.onOtp({intentId:s.id,challengeId:a,maskedPhone:n.masked_phone??n.masterpass?.phone,expiresAt:n.expires_at,masterpass:n.masterpass});if(l===null)throw new c({op:"PresentIntent",status:0,code:"payment_canceled",message:"verification canceled by customer"});let u=typeof l=="string"?l:l.otp,h=typeof l=="string"?void 0:l.saveMethod;s=await this.submitOtp(s.id,{challengeId:a,otp:u,clientSecret:i,saveMethod:h,signal:t.signal});continue}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}return this.getIntent(s.id,{clientSecret:i,signal:t.signal})}onEvent(e){return this.eventListeners.add(e),this.eventListeners.size===1&&this.startEvents(),()=>{this.eventListeners.delete(e)&&this.eventListeners.size===0&&this.stopEvents()}}onWalletChange(e){if(this.walletListeners.add(e),this.walletListeners.size===1)this.startWalletWatch();else if(this.lastBalances!==void 0){let t=this.lastBalances;queueMicrotask(()=>this.walletListeners.has(e)&&M(e,t))}return()=>{this.walletListeners.delete(e)&&this.walletListeners.size===0&&this.stopWalletWatch()}}startWalletWatch(){this.walletFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followWallet(t)}),this.session.session().then(e=>{this.walletFollowing&&!this.walletWatch&&this.lastBalances===void 0&&this.followWallet(e)})}stopWalletWatch(){this.walletFollowing?.(),this.walletFollowing=void 0,this.unfollowWallet(),this.lastBalances=void 0}followWallet(e){if(this.unfollowWallet(),!e){this.tellBalances(null);return}let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i={userId:e.userId,channel:t,off:()=>{},maxVersion:-1,reading:!1,wanted:!1},s=t.on("broadcast",d=>{typeof d.event=="string"&&E.has(d.event)&&this.walletChanged(i)});i.off=s,this.walletWatch=i,t.join().catch(()=>{}),this.readBalances(i)}unfollowWallet(){let e=this.walletWatch;e&&(this.walletWatch=void 0,e.off(),e.channel.leave())}walletChanged(e){this.walletWatch===e&&(e.reading?e.wanted=!0:this.readBalances(e))}async readBalances(e){e.reading=!0;try{for(;;){e.wanted=!1;try{let t=(await this.api.listMyWallets()).data.balances;if(this.walletWatch!==e)return;this.offerBalances(e,t)}catch{}if(this.walletWatch!==e||!e.wanted)return}}finally{e.reading=!1}}offerBalances(e,t){if(this.walletWatch!==e)return;let i=t.reduce((s,d)=>Math.max(s,d.version),0);e.maxVersion>=0&&i<e.maxVersion||(e.maxVersion=i,this.tellBalances(t))}tellBalances(e){if(!(this.lastBalances===null&&e===null)){this.lastBalances=e;for(let t of[...this.walletListeners])M(t,e)}}startEvents(){this.eventFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followEvents(t)}),this.session.session().then(e=>{this.eventFollowing&&!this.eventWatch&&this.followEvents(e)})}stopEvents(){this.eventFollowing?.(),this.eventFollowing=void 0,this.unfollowEvents()}followEvents(e){if(this.unfollowEvents(),!e)return;let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i=t.on("broadcast",s=>{if(typeof s.event!="string")return;let d={type:s.event,payload:s.payload};for(let n of[...this.eventListeners])try{n(d)}catch{}});this.eventWatch={userId:e.userId,channel:t,off:i},t.join().catch(()=>{})}unfollowEvents(){let e=this.eventWatch;e&&(this.eventWatch=void 0,e.off(),e.channel.leave())}};function k(o,e){let i=o.ownerDocument.createElement("iframe");return i.setAttribute("data-palbase-payments-frame",""),i.setAttribute("title","Secure Payment Verification"),i.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.style.width="100%",i.style.minHeight="480px",i.style.border="0",i.style.borderRadius="8px",i.style.background="#ffffff",e.html?i.srcdoc=e.html:e.url&&(i.src=e.url),o.replaceChildren(i),()=>{i.remove()}}function M(o,e){try{o(e)}catch{}}export{P as a,S as b,T as c,B as d,_ as e,k as f};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as O,g as w,l as F,m as _,s as D}from"./22GRHCVI.js";import{b as h}from"./QFZ4GCJH.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=j(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var X={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function U(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.68.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let u=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var Y={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function G(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Y,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.66.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
2
  var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as x}from"./622BI7EV.js";import{a as ae}from"./OWLXCD3D.js";import{a as C,b as H,c as U,d as L,e as I,f as N,g as $,i as D,j as F,k as B,l as q,m as V,n as z,o as J,p as Y,q as G}from"./65QZXK2S.js";import{a as w,c as Q,d as ee,e as te,f as ne,h as re,i as se,j as A,k as ie,l as oe,o as R}from"./LUUXXMXH.js";import{a as X,b as Z}from"./J7WJF7F4.js";import{b as P,d as v}from"./QFZ4GCJH.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},xe=6e4,Oe=1e3;function O(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},xe),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=ee(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await te(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let t=this.now();for(;O(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Oe-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let t;try{t=re(e.header).kid}catch{throw new f("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(t),s;try{s=ne(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new S(t,await se(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof Q?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return R(e,t,r,async(s,i)=>{if(!ie(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await oe(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return R(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var je=/^pb_[a-z0-9]+_s/;function j(n){if(ae())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!je.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=Z(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??X),t=z.client(e);return{ai:C.client(e),analytics:H.client(e),auth:U.client(e),cache:L.client(e),calls:I.client(e),fields:new x({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:N.client(e),iap:$.client(e),machines:D.client(e),messaging:F.client(e),notify:B.client(e),payments:q.client(e),realtime:V.client(e),secrets:t,storage:J.client(e),stores:Y.client(e),workspaces:G.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},We=300,Me=/^[0-9]{1,12}$/,Ce=/^[0-9a-f]{64}$/,le=8,He=/^whsec_[0-9A-Za-z]{32,}$/,Ue=1024*1024;async function de(n){if(typeof n.secret!="string"||!He.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ce(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(pe(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Fe(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ce(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=pe(n.body),{t,v1:r}=ue(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,De(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Ne(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ue(n){let e=n.toleranceSeconds??We;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let l=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(l==="t"){if(s!==void 0||!Me.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(l==="v1"){if(!Ce.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===le)throw new h("malformed_signature",`Palbase-Signature carries at most ${le} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Le(n,e,t={}){let r=await Ie(n,t.maxBytes??Ue);return de({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ie(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:c}=await s.read();if(a)break;if(o+=c.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(c)}let d=new Uint8Array(o),l=0;for(let a of i)d.set(a,l),l+=a.byteLength;return d}function pe(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ne(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function $e(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function De(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Fe(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var he=60,Be=60,qe=8*1024,Ve=1e5;function K(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function me(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function fe(n){let e=me(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var _=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ve){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function ze(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return K(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function ye(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function ge(n,e,t,r){let s=Re=>{throw new u("proof",`the DPoP proof is not taken: ${Re}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>qe)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=fe(o[0]),l=fe(o[1]);if(!d||!l)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await ze(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let c;try{c=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=me(o[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,p,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof l.htm!="string"||l.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(l.htm)}, not ${t.method}`);let y=typeof l.htu=="string"?ye(l.htu):void 0,g=ye(t.url);if(!y||!g||y!==g)return s(`it is for ${String(l.htu)}, not ${g??t.url}`);let Te=r/1e3;if(typeof l.iat!="number"||Math.abs(l.iat-Te)>he)return s("it was not made within a minute of now");let Pe=K(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(l.ath!==Pe)return s("it is not for this token (ath)");if(typeof l.jti!="string"||l.jti===""||l.jti.length>256)return s("it has no jti (or one longer than 256)");let Ae=K(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(l.jti)));return{jkt:e,jti:Ae,until:(l.iat+he+Be)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},b=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},Je=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Ye(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof P&&r.status===401&&!Je.has(r.code))return!1;throw new b("a session's standing could not be told",{cause:r})}}}var W={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},we=60,Ge=16*1024,Xe=10*6e4,Ze=5e4,be=n=>typeof n=="string"&&Object.hasOwn(W,n),M=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new _;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Ge)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ke(r[0]),i=ke(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!be(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let l=await this.key(d);if(!l)throw new u("unknown_key",`no key ${d} in the project's key set`);if(l.alg!==o)throw new u("algorithm",`key ${d} is ${l.alg}, the token says ${o}`);let a=Se(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let c=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(W[l.alg].verify,l.key,a,c).catch(()=>!1))throw new u("signature","the signature does not verify");let m=this.check(i),y=i.cnf,g;if(y!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof y!="object"||y===null||typeof y.jkt!="string"||y.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await ge(e,y.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:et(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:ve(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(l){let a=this.standings.get(t),c=this.now();if(a&&c<a.at+this.standingStaleMs)return a.until=Math.min(c+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new b("a session's standing cannot be read now",{cause:l})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Ze&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+we<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-we>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Xe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new b("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new b("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!be(o))continue;let d=W[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:l,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=tt(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ve(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Qe.test(s)?`${r}://${s}${e.pathname}`:""}var Qe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function et(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function tt(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function Se(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function ke(n){let e=Se(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function nt(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var E=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function rt(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let l={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:l})).data;if(a.status!=="held")throw new E(a);let c={customer_id:a.customer,spend_id:a.id},p;try{p=await r(a)}catch(m){throw await n.iap.releaseSpend({path:c}).catch(()=>{}),m}return await n.iap.commitSpend({path:c}),p}var st=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function it(n){return n!==void 0&&st.has(n)}function ot(n,e){return{[_e]:!0,commitAmount:n,value:e}}var _e=Symbol("palbase.payments.settleWalletHold");function at(n){return typeof n=="object"&&n!==null&&_e in n}var T=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function lt(n,e,t){let{idempotencyKey:r,walletKey:s,amount:i,ttlSeconds:o,reference:d,metadata:l}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(i)||i<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:s,amount:i,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{reference:d}:{},...l!==void 0?{metadata:l}:{}},c=(await n.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(c.status!=="active")throw new T(c);let p;try{p=await t(c)}catch(m){throw await n.payments.releaseWalletHold({path:{hold_id:c.id}}).catch(()=>{}),m}return at(p)?(p.commitAmount<=0?await n.payments.releaseWalletHold({path:{hold_id:c.id}}):await n.payments.commitWalletHold({path:{hold_id:c.id},body:{amount:p.commitAmount}}),p.value):(await n.payments.commitWalletHold({path:{hold_id:c.id}}),p)}function dt(n){return n.type.startsWith("payments.")}async function*ct(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var ut=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,pt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ee(n){return!ut.test(n)||pt.test(n)||/_PROXY$/i.test(n)}var ht=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function ft(n){return ht.test(n)}async function yt(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(t!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=j({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],l=[],a=[];for(let[c,p]of Object.entries(o.values)){if(Ee(c)){a.push(c);continue}if(e[c]!==void 0&&e[c]!==""){l.push(c);continue}e[c]=p,d.push(c)}return{set:t,loaded:d.sort(),kept:l.sort(),refused:a.sort()}}export{f as a,k as b,S as c,j as d,h as e,de as f,ce as g,ue as h,Le as i,u as j,b as k,Ye as l,M as m,ve as n,nt as o,E as p,rt as q,it as r,ot as s,T as t,lt as u,dt as v,ct as w,Ee as x,ft as y,yt as z};