@zuplo/cli 6.74.12 → 6.74.14

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 (81) hide show
  1. package/node_modules/@posthog/core/dist/featureFlagUtils.d.ts +1 -0
  2. package/node_modules/@posthog/core/dist/featureFlagUtils.d.ts.map +1 -1
  3. package/node_modules/@posthog/core/dist/featureFlagUtils.js +31 -0
  4. package/node_modules/@posthog/core/dist/featureFlagUtils.mjs +29 -1
  5. package/node_modules/@posthog/core/dist/index.d.ts +1 -1
  6. package/node_modules/@posthog/core/dist/index.d.ts.map +1 -1
  7. package/node_modules/@posthog/core/dist/index.js +9 -0
  8. package/node_modules/@posthog/core/dist/index.mjs +2 -2
  9. package/node_modules/@posthog/core/dist/utils/index.d.ts +1 -0
  10. package/node_modules/@posthog/core/dist/utils/index.d.ts.map +1 -1
  11. package/node_modules/@posthog/core/dist/utils/index.js +45 -18
  12. package/node_modules/@posthog/core/dist/utils/index.mjs +1 -0
  13. package/node_modules/@posthog/core/dist/utils/json-utils.d.ts +6 -0
  14. package/node_modules/@posthog/core/dist/utils/json-utils.d.ts.map +1 -0
  15. package/node_modules/@posthog/core/dist/utils/json-utils.js +128 -0
  16. package/node_modules/@posthog/core/dist/utils/json-utils.mjs +94 -0
  17. package/node_modules/@posthog/core/package.json +2 -2
  18. package/node_modules/@posthog/core/src/featureFlagUtils.ts +35 -0
  19. package/node_modules/@posthog/core/src/index.ts +1 -0
  20. package/node_modules/@posthog/core/src/utils/index.ts +1 -0
  21. package/node_modules/@posthog/core/src/utils/json-utils.spec.ts +115 -0
  22. package/node_modules/@posthog/core/src/utils/json-utils.ts +148 -0
  23. package/node_modules/@posthog/types/dist/posthog-config.d.ts +25 -1
  24. package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
  25. package/node_modules/@posthog/types/dist/posthog.d.ts +4 -0
  26. package/node_modules/@posthog/types/dist/posthog.d.ts.map +1 -1
  27. package/node_modules/@posthog/types/package.json +1 -1
  28. package/node_modules/@posthog/types/src/posthog-config.ts +26 -1
  29. package/node_modules/@posthog/types/src/posthog.ts +4 -0
  30. package/node_modules/@zuplo/core/customer.cli.minified.js +254 -254
  31. package/node_modules/@zuplo/core/index.minified.js +251 -251
  32. package/node_modules/@zuplo/core/package.json +1 -1
  33. package/node_modules/@zuplo/graphql/package.json +1 -1
  34. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  35. package/node_modules/@zuplo/otel/package.json +1 -1
  36. package/node_modules/@zuplo/runtime/out/esm/{chunk-SMQPMERU.js → chunk-4CDML74A.js} +2 -2
  37. package/node_modules/@zuplo/runtime/out/esm/chunk-4POCC75H.js +37 -0
  38. package/node_modules/@zuplo/runtime/out/esm/chunk-4POCC75H.js.map +1 -0
  39. package/node_modules/@zuplo/runtime/out/esm/{chunk-AVDTZRWM.js → chunk-CJFLOF27.js} +2 -2
  40. package/node_modules/@zuplo/runtime/out/esm/{chunk-2UG5Z76T.js → chunk-RAZK5G27.js} +2 -2
  41. package/node_modules/@zuplo/runtime/out/esm/{chunk-VVVYHDCV.js → chunk-YFAVPQDX.js} +4 -4
  42. package/node_modules/@zuplo/runtime/out/esm/{chunk-VVVYHDCV.js.map → chunk-YFAVPQDX.js.map} +1 -1
  43. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  44. package/node_modules/@zuplo/runtime/out/esm/internal/index.js +1 -1
  45. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  46. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
  47. package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +1 -1
  48. package/node_modules/@zuplo/runtime/package.json +1 -1
  49. package/node_modules/express-rate-limit/dist/index.cjs +6 -1
  50. package/node_modules/express-rate-limit/dist/index.mjs +6 -1
  51. package/node_modules/express-rate-limit/package.json +6 -6
  52. package/node_modules/tar/dist/commonjs/index.min.js +1 -1
  53. package/node_modules/tar/dist/commonjs/index.min.js.map +3 -3
  54. package/node_modules/tar/dist/commonjs/list.d.ts.map +1 -1
  55. package/node_modules/tar/dist/commonjs/list.js +10 -2
  56. package/node_modules/tar/dist/commonjs/list.js.map +1 -1
  57. package/node_modules/tar/dist/commonjs/options.d.ts +1 -1
  58. package/node_modules/tar/dist/commonjs/options.d.ts.map +1 -1
  59. package/node_modules/tar/dist/commonjs/options.js.map +1 -1
  60. package/node_modules/tar/dist/esm/index.min.js +2 -2
  61. package/node_modules/tar/dist/esm/index.min.js.map +3 -3
  62. package/node_modules/tar/dist/esm/list.d.ts.map +1 -1
  63. package/node_modules/tar/dist/esm/list.js +10 -2
  64. package/node_modules/tar/dist/esm/list.js.map +1 -1
  65. package/node_modules/tar/dist/esm/options.d.ts +1 -1
  66. package/node_modules/tar/dist/esm/options.d.ts.map +1 -1
  67. package/node_modules/tar/dist/esm/options.js.map +1 -1
  68. package/node_modules/tar/package.json +1 -1
  69. package/node_modules/undici/lib/core/request.js +12 -1
  70. package/node_modules/undici/lib/dispatcher/client-h1.js +11 -2
  71. package/node_modules/undici/lib/handler/retry-handler.js +34 -0
  72. package/node_modules/undici/lib/web/cookies/util.js +79 -9
  73. package/node_modules/undici/package.json +1 -1
  74. package/package.json +8 -8
  75. package/node_modules/@zuplo/runtime/out/esm/chunk-7AMMYBFQ.js +0 -37
  76. package/node_modules/@zuplo/runtime/out/esm/chunk-7AMMYBFQ.js.map +0 -1
  77. /package/node_modules/@zuplo/runtime/out/esm/{chunk-SMQPMERU.js.map → chunk-4CDML74A.js.map} +0 -0
  78. /package/node_modules/@zuplo/runtime/out/esm/{chunk-7AMMYBFQ.js.LEGAL.txt → chunk-4POCC75H.js.LEGAL.txt} +0 -0
  79. /package/node_modules/@zuplo/runtime/out/esm/{chunk-AVDTZRWM.js.map → chunk-CJFLOF27.js.map} +0 -0
  80. /package/node_modules/@zuplo/runtime/out/esm/{chunk-2UG5Z76T.js.map → chunk-RAZK5G27.js.map} +0 -0
  81. /package/node_modules/@zuplo/runtime/out/esm/{chunk-VVVYHDCV.js.LEGAL.txt → chunk-YFAVPQDX.js.LEGAL.txt} +0 -0
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{c as Je,d as Ke,f as oh,g as rh}from"./chunk-AVDTZRWM.js";import{a as X,b as GR}from"./chunk-2UG5Z76T.js";import{a as Le}from"./chunk-QGAJTUPE.js";import{A as $,B as Ce,C as Pa,D as Cr,E as KR,F as WR,G as p,H as ed,I as YR,J as td,L as QR,M as Aa,N as XR,O as ew,a as Ta,b as Ze,c as Si,e as Ve,f as st,g as ZR,h as nh,i as Rr,j as BR,k as y,l as VR,m as Xl,n as V,o as me,p as wr,q as JR,r as Pe,s as N,t as A,u as Ee,v as he,w as Ri,x as Bo,y as ie,z as qe}from"./chunk-SMQPMERU.js";import{a as ce}from"./chunk-UKQQD2JN.js";import{A as ER,B as OR,C as kR,D as _R,E as xR,F as MR,G as Vl,H as LR,I as NR,J as Jl,K as Kl,L as qR,M as Wl,N as Yl,O as $R,P as zR,Q as DR,R as UR,S as jR,T as HR,U as FR,V as Ql,W as De,X as U,Y as I,Z as O,_ as j,a as Ye,b as lR,c as yi,d as dR,e as bi,f as pR,g as mR,h as hR,i as fR,j as gR,k as yR,l as bR,m as SR,n as RR,o as wR,p as CR,q as IR,r as vR,s as Hl,t as Fl,u as Gl,v as Zl,w as Bl,x as TR,y as PR,z as AR}from"./chunk-7AMMYBFQ.js";import{a as i,b as Ax,d as Ex}from"./chunk-TYV53J3B.js";var rC=Ax(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.parse=$0;vd.serialize=z0;var _0=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,x0=/^[\u0021-\u003A\u003C-\u007E]*$/,M0=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,L0=/^[\u0020-\u003A\u003D-\u007E]*$/,N0=Object.prototype.toString,q0=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function $0(t,e){let n=new q0,o=t.length;if(o<2)return n;let r=e?.decode||D0,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s),u=c===-1?o:c;if(a>u){s=t.lastIndexOf(";",a-1)+1;continue}let l=nC(t,s,a),d=oC(t,a,l),m=t.slice(l,d);if(n[m]===void 0){let h=nC(t,a+1,u),g=oC(t,u,h),f=r(t.slice(h,g));n[m]=f}s=u+1}while(s<o);return n}i($0,"parse");function nC(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(nC,"startIndex");function oC(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(oC,"endIndex");function z0(t,e,n){let o=n?.encode||encodeURIComponent;if(!_0.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!x0.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+r;if(!n)return s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);s+="; Max-Age="+n.maxAge}if(n.domain){if(!M0.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!L0.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!U0(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);s+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.partitioned&&(s+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return s}i(z0,"serialize");function D0(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(D0,"decode");function U0(t){return N0.call(t)==="[object Date]"}i(U0,"isDate")});var W=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let o=`No system logger found for context with requestId '${e.requestId}'`;throw j.console.error(o),new De(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function nt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${O.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",O.instance.deploymentName??"unknown"),t.set("User-Agent",O.instance.systemUserAgent),t.set("zp-compat-date",O.instance.build.COMPATIBILITY_DATE??"none")}i(nt,"setZuploHeaders");var nd=["openai","anthropic","google","mistral","xai"],Ox=60;async function tw(t){let e=await Ze("supported-models",{});return new Ve(e,t)}i(tw,"createSupportedModelsCache");async function Ea(t){return(await tw(t)).get("models")}i(Ea,"getCachedSupportedModels");async function Ht(t){let e=W.getLogger(t),n=await Ea(t);if(n)return e.info("Using cached supported models data",{providersCount:Object.keys(n.modelsByProvider).length,providers:Object.keys(n.modelsByProvider)}),{modelsByProvider:n.modelsByProvider,providerMetadata:n.providerMetadata};let o=new Headers({"content-type":"application/json"});nt(o,t.requestId);let r=new URL(`/v2/buckets/${Je.ZUPLO_SERVICE_BUCKET_ID}/providers?includeDeprecated=true`,O.instance.zuploEdgeApiUrl).toString(),s=await st({retryDelayMs:100,retries:5},r,{method:"GET",headers:o});if(s.status===404){await s.body?.cancel(),e.warn("AI provider assignment catalog endpoint is unavailable; using legacy provider catalog");let m=new URL(`/v1/buckets/${Je.ZUPLO_SERVICE_BUCKET_ID}/providers?includeDeprecated=true`,O.instance.zuploEdgeApiUrl).toString();s=await st({retryDelayMs:100,retries:5},m,{method:"GET",headers:o})}if(s.status!==200){let m="Failed to fetch supported models from Gateway service";try{let h=await s.text(),g=JSON.parse(h);e.error(m,g),m=`${m}: ${g.message||s.statusText}`}catch{e.error(m,{status:s.status}),m=`${m}: ${s.status}`}throw new Error(m)}let a=await s.json();e.info("Gateway service response received",{providersCount:Object.keys(a.data).length,providers:Object.keys(a.data),totalModels:Object.values(a.data).reduce((m,h)=>m+h.length,0)});let c={};for(let[m,h]of Object.entries(a.data)){let g=m.toLowerCase();c[g]={};for(let f of h)c[g][f.model]=f}let u={};for(let[m,h]of Object.entries(a.providers))u[m.toLowerCase()]=h;let l={modelsByProvider:c,providerMetadata:u};return(await tw(t)).put("models",l,Ox),{modelsByProvider:c,providerMetadata:u}}i(Ht,"getSupportedModels");function ih(t,e){let n=t.provider.toLowerCase();if(!t.environmentVariable)return n;for(let[o,r]of Object.entries(e))if(r.envVarName===t.environmentVariable)return o;return n}i(ih,"resolveProviderLabel");function nw(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(nw,"describeProviderAssignments");function kn(t,e,n,o,r,s){let a=e.toLowerCase(),c=r[a];if(!c)return s.warn("Provider not found in supported models list",{provider:e,model:t}),0;let u=c[t];if(!u)return s.warn("Model not found in supported models list for provider",{provider:e,model:t}),0;let l=n*u.inputCostPerToken,d=o*u.outputCostPerToken;return l+d}i(kn,"calculateModelCost");function ow(t,e,n,o){let r=e.toLowerCase(),s=o[r];if(!s)return!1;let a=s[t];return a?a.kind===n&&a.status==="active":!1}i(ow,"isModelSupported");function rw(t,e,n){let o=t.toLowerCase(),r=n[o];return r?Object.values(r).filter(s=>s.kind===e&&s.status==="active").map(s=>s.model):[]}i(rw,"getModelsByProviderAndKind");var uw=Symbol("ai-gateway-model-selection"),iw=Symbol("ai-gateway-model-routing"),Ir='Use "providerName/model", for example "openai/gpt-5".',sh=["completions","embeddings"],sw=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function Vo(t,e,n){throw new I(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(Vo,"invalid");function Nt(t,e,n,o){return o?o(t,e,n):Vo(t,e,n)}i(Nt,"reject");function ah(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(ah,"isRecord");function rn(t,e,n){if(typeof t!="string")return Nt(e,"must be a string",Ir,n);if(t.length===0)return Nt(e,"must not be empty",Ir,n);if(t.trim()!==t||/\s/.test(t))return Nt(e,`contains whitespace in '${t}'`,Ir,n);let o=t.indexOf("/");if(o===-1)return Nt(e,`'${t}' has no provider name separator`,Ir,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?Nt(e,`'${t}' has an empty provider name`,Ir,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?Nt(e,`'${t}' has an empty model`,Ir,n):s.startsWith("/")?Nt(e,`'${t}' starts the model with an extra "/"`,Ir,n):{provider:r,model:s,raw:t}:Nt(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(rn,"parseModelRef");function kx(t,e,n){let o=typeof t=="string"?{main:t}:ah(t)?t:{};if(typeof t!="string"&&!ah(t))return Nt(e,"must be a model reference string or an object",'Set it to "providerName/model" or { main: "openai/gpt-5" }',n);let r=Object.keys(o).filter(l=>!sw.includes(l));if(r.length>0)return Nt(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${sw.join(", ")}`,n);if(Object.keys(o).length===0)return Nt(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=rn(o.main,`${e}.main`,n);if(o.backup===null)return Nt(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return Nt(`${e}.quotaFallback`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);let a=o.backup===void 0?void 0:rn(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:rn(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return Nt(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return Nt(`${e}.quotaFallback`,`must differ from '${e}.main'`,"Choose a different quota fallback model or omit 'quotaFallback'",n);let u=o.fallbackTimeoutSeconds;if(u!==void 0){if(a===void 0)return Nt(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return Nt(`${e}.fallbackTimeoutSeconds`,`is a string '${u}', not a number`,"Remove the quotes and set it to a number from 1 through 300",n);if(typeof u!="number"||!Number.isFinite(u)||u<1)return Nt(`${e}.fallbackTimeoutSeconds`,"must be a finite number greater than or equal to 1","Set it to a number from 1 through 300",n);if(u>300)return Nt(`${e}.fallbackTimeoutSeconds`,"must not exceed the platform request duration of 300 seconds","Set it to 300 or less so the backup can run before the request ends",n)}return{main:s.raw,...a===void 0?{}:{backup:a.raw},...u===void 0?{}:{fallbackTimeoutSeconds:u},...c===void 0?{}:{quotaFallback:c.raw}}}i(kx,"normalizeAIGatewayRouteTarget");async function lw(t){let{modelsByProvider:e,providerMetadata:n}=await Ht(t),r=[...new Set([...Object.keys(e),...Object.keys(n)])].map(a=>{let c=n[a],u=Object.values(e[a]??{}).map(l=>({model:l.model,capability:l.kind,status:l.status,inputCostPerToken:l.inputCostPerToken,outputCostPerToken:l.outputCostPerToken}));return{providerName:a,...c?.baseUrl===void 0?{}:{baseUrl:c.baseUrl},...c?.isCustom===void 0?{}:{isCustom:c.isCustom},...c?.providerType===void 0?{}:{providerType:c.providerType.toLowerCase()},models:u}}),s=new Map;for(let[a,c]of Object.entries(n))c.envVarName!==void 0&&s.set(a.toLowerCase(),c.envVarName);return{providers:r,providerEnvironmentVariables:s,modelsByProvider:e,providerMetadata:n}}i(lw,"loadProviders");function _x(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(_x,"conventionEnvironmentVariable");function aw(t){return t&&Je[t]?.trim()||void 0}i(aw,"nonEmptyEnvironmentValue");function xx(t){let{provider:e,providerEnvironmentVariables:n,path:o}=t,r=n.get(e.toLowerCase()),s=_x(e),a=aw(r)??aw(s);if(a===void 0){let c=r?` (catalog binding '${r}' is empty)`:"";return Vo(o,`could not resolve an API key for provider name '${e}'. No key binding found in your account's AI providers${c} and conventional environment variable '${s}' is not set`,`Add an AI provider named '${e}' with an API key in the Zuplo Portal, or set '${s}'`)}return a}i(xx,"resolveApiKey");function Mx(t){let{provider:e,providers:n,path:o}=t,r=n.find(({providerName:a})=>a.toLowerCase()===e.toLowerCase());if(r!==void 0)return r.providerName;let s=n.map(({providerName:a})=>a).sort().join(", ");Vo(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(Mx,"resolveCatalogEntryLabel");function Lx(t){let{provider:e,model:n,capability:o,modelsByProvider:r,providerMetadata:s,path:a}=t,c=e.toLowerCase(),l=s[c]?.providerType?.toLowerCase();if(l===void 0||!nd.some(m=>m===l))return;let d=r[c]?.[n];d?.kind===o&&d.status==="active"||(d?.kind===o&&Vo(a,`model '${n}' is not active for provider name '${e}'`,`Update provider '${e}' model selections to use an active model, or use another provider name that offers it`),Vo(a,`model '${n}' is not included in model selections for provider name '${e}'`,`Update provider '${e}' model selections to include '${n}', or use another provider name that offers it`))}i(Lx,"assertAssignmentOffersModel");function cw(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(cw,"cloneRouting");function Nx(t,e){ce.set(t,uw,e)}i(Nx,"setModelSelection");function fn(t){return ce.get(t,uw)}i(fn,"getModelSelection");var wi={async load(t){let{providers:e}=await lw(t);return e}},Yn={async set(t,e){if(!ah(e))return Vo("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!sh.includes(d));if(n.length>0)return Vo(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=sh.filter(d=>e[d]!==void 0);if(o.length===0)return Vo("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=kx(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await lw(t),l={};for(let d of sh){let m=r[d];if(typeof m!="object")continue;let h=rn(m.main,`routing.${d}.main`),g=m.backup?rn(m.backup,`routing.${d}.backup`):void 0,f=m.quotaFallback?rn(m.quotaFallback,`routing.${d}.quotaFallback`):void 0,R=new Map;for(let[w,v]of[["main",h],["backup",g],["quotaFallback",f]])if(v){let T=Mx({provider:v.provider,providers:s,path:`routing.${d}.${w}`});Lx({provider:T,model:v.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${w}`});let P={...v,provider:T};R.set(w,P)}let S=i(w=>{let v=R.get(w);if(v===void 0)throw new Error(`Missing resolved AI Gateway routing field '${w}'`);return{provider:v.provider,model:v.model,apiKey:xx({provider:v.provider,providerEnvironmentVariables:a,path:`routing.${d}.${w}`})}},"toCandidate");l[d]={candidates:[S("main"),...g?[S("backup")]:[]],...g?{fallbackTimeoutSeconds:m.fallbackTimeoutSeconds??60}:{},...f?{quotaFallback:S("quotaFallback")}:{}}}Nx(t,{byCapability:l}),ce.set(t,iw,cw(r))},get(t){let e=ce.get(t,iw);return e===void 0?void 0:cw(e)}};var qx=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),$x=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Ot(t){let e=new URL(t.url).pathname;for(let[n,o]of $x)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Ot,"getFormat");async function zx(t){let e=Ot(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(zx,"getRequestBody");async function Dx(t,e){let n=Ot(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(Dx,"getResponseBody");function ch(t){let e=t?.usage;if(!e||typeof e!="object")return;let n=i(c=>typeof c=="number"?c:void 0,"num"),o=n(e.input_tokens)??n(e.prompt_tokens),r=n(e.output_tokens)??n(e.completion_tokens);if(o===void 0&&r===void 0)return;let s=o??0,a=r??0;return{promptTokens:s,completionTokens:a,totalTokens:n(e.total_tokens)??s+a}}i(ch,"getUsage");function mt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>mt(e)).filter(Boolean).join(" ");if(t&&typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking;if(typeof e.input_text=="string")return e.input_text;if(e.content!==void 0)return mt(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(mt,"flattenMessageContent");function vr(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(mt(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(mt(e.system)),typeof e.instructions=="string"&&n.push(e.instructions),typeof e.input=="string")n.push(e.input);else if(Array.isArray(e.input))for(let o of e.input)n.push(mt(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(mt(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(mt(o.content));return Array.isArray(e.content)&&n.push(mt(e.content)),n.filter(Boolean).join(`
25
+ import{c as Je,d as Ke,f as oh,g as rh}from"./chunk-CJFLOF27.js";import{a as X,b as GR}from"./chunk-RAZK5G27.js";import{a as Le}from"./chunk-QGAJTUPE.js";import{A as $,B as Ce,C as Pa,D as Cr,E as KR,F as WR,G as p,H as ed,I as YR,J as td,L as QR,M as Aa,N as XR,O as ew,a as Ta,b as Ze,c as Si,e as Ve,f as st,g as ZR,h as nh,i as Rr,j as BR,k as y,l as VR,m as Xl,n as V,o as me,p as wr,q as JR,r as Pe,s as N,t as A,u as Ee,v as he,w as Ri,x as Bo,y as ie,z as qe}from"./chunk-4CDML74A.js";import{a as ce}from"./chunk-UKQQD2JN.js";import{A as ER,B as OR,C as kR,D as _R,E as xR,F as MR,G as Vl,H as LR,I as NR,J as Jl,K as Kl,L as qR,M as Wl,N as Yl,O as $R,P as zR,Q as DR,R as UR,S as jR,T as HR,U as FR,V as Ql,W as De,X as U,Y as I,Z as O,_ as j,a as Ye,b as lR,c as yi,d as dR,e as bi,f as pR,g as mR,h as hR,i as fR,j as gR,k as yR,l as bR,m as SR,n as RR,o as wR,p as CR,q as IR,r as vR,s as Hl,t as Fl,u as Gl,v as Zl,w as Bl,x as TR,y as PR,z as AR}from"./chunk-4POCC75H.js";import{a as i,b as Ax,d as Ex}from"./chunk-TYV53J3B.js";var rC=Ax(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.parse=$0;vd.serialize=z0;var _0=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,x0=/^[\u0021-\u003A\u003C-\u007E]*$/,M0=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,L0=/^[\u0020-\u003A\u003D-\u007E]*$/,N0=Object.prototype.toString,q0=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function $0(t,e){let n=new q0,o=t.length;if(o<2)return n;let r=e?.decode||D0,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s),u=c===-1?o:c;if(a>u){s=t.lastIndexOf(";",a-1)+1;continue}let l=nC(t,s,a),d=oC(t,a,l),m=t.slice(l,d);if(n[m]===void 0){let h=nC(t,a+1,u),g=oC(t,u,h),f=r(t.slice(h,g));n[m]=f}s=u+1}while(s<o);return n}i($0,"parse");function nC(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(nC,"startIndex");function oC(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(oC,"endIndex");function z0(t,e,n){let o=n?.encode||encodeURIComponent;if(!_0.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!x0.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+r;if(!n)return s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);s+="; Max-Age="+n.maxAge}if(n.domain){if(!M0.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!L0.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!U0(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);s+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.partitioned&&(s+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return s}i(z0,"serialize");function D0(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(D0,"decode");function U0(t){return N0.call(t)==="[object Date]"}i(U0,"isDate")});var W=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let o=`No system logger found for context with requestId '${e.requestId}'`;throw j.console.error(o),new De(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function nt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${O.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",O.instance.deploymentName??"unknown"),t.set("User-Agent",O.instance.systemUserAgent),t.set("zp-compat-date",O.instance.build.COMPATIBILITY_DATE??"none")}i(nt,"setZuploHeaders");var nd=["openai","anthropic","google","mistral","xai"],Ox=60;async function tw(t){let e=await Ze("supported-models",{});return new Ve(e,t)}i(tw,"createSupportedModelsCache");async function Ea(t){return(await tw(t)).get("models")}i(Ea,"getCachedSupportedModels");async function Ht(t){let e=W.getLogger(t),n=await Ea(t);if(n)return e.info("Using cached supported models data",{providersCount:Object.keys(n.modelsByProvider).length,providers:Object.keys(n.modelsByProvider)}),{modelsByProvider:n.modelsByProvider,providerMetadata:n.providerMetadata};let o=new Headers({"content-type":"application/json"});nt(o,t.requestId);let r=new URL(`/v2/buckets/${Je.ZUPLO_SERVICE_BUCKET_ID}/providers?includeDeprecated=true`,O.instance.zuploEdgeApiUrl).toString(),s=await st({retryDelayMs:100,retries:5},r,{method:"GET",headers:o});if(s.status===404){await s.body?.cancel(),e.warn("AI provider assignment catalog endpoint is unavailable; using legacy provider catalog");let m=new URL(`/v1/buckets/${Je.ZUPLO_SERVICE_BUCKET_ID}/providers?includeDeprecated=true`,O.instance.zuploEdgeApiUrl).toString();s=await st({retryDelayMs:100,retries:5},m,{method:"GET",headers:o})}if(s.status!==200){let m="Failed to fetch supported models from Gateway service";try{let h=await s.text(),g=JSON.parse(h);e.error(m,g),m=`${m}: ${g.message||s.statusText}`}catch{e.error(m,{status:s.status}),m=`${m}: ${s.status}`}throw new Error(m)}let a=await s.json();e.info("Gateway service response received",{providersCount:Object.keys(a.data).length,providers:Object.keys(a.data),totalModels:Object.values(a.data).reduce((m,h)=>m+h.length,0)});let c={};for(let[m,h]of Object.entries(a.data)){let g=m.toLowerCase();c[g]={};for(let f of h)c[g][f.model]=f}let u={};for(let[m,h]of Object.entries(a.providers))u[m.toLowerCase()]=h;let l={modelsByProvider:c,providerMetadata:u};return(await tw(t)).put("models",l,Ox),{modelsByProvider:c,providerMetadata:u}}i(Ht,"getSupportedModels");function ih(t,e){let n=t.provider.toLowerCase();if(!t.environmentVariable)return n;for(let[o,r]of Object.entries(e))if(r.envVarName===t.environmentVariable)return o;return n}i(ih,"resolveProviderLabel");function nw(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(nw,"describeProviderAssignments");function kn(t,e,n,o,r,s){let a=e.toLowerCase(),c=r[a];if(!c)return s.warn("Provider not found in supported models list",{provider:e,model:t}),0;let u=c[t];if(!u)return s.warn("Model not found in supported models list for provider",{provider:e,model:t}),0;let l=n*u.inputCostPerToken,d=o*u.outputCostPerToken;return l+d}i(kn,"calculateModelCost");function ow(t,e,n,o){let r=e.toLowerCase(),s=o[r];if(!s)return!1;let a=s[t];return a?a.kind===n&&a.status==="active":!1}i(ow,"isModelSupported");function rw(t,e,n){let o=t.toLowerCase(),r=n[o];return r?Object.values(r).filter(s=>s.kind===e&&s.status==="active").map(s=>s.model):[]}i(rw,"getModelsByProviderAndKind");var uw=Symbol("ai-gateway-model-selection"),iw=Symbol("ai-gateway-model-routing"),Ir='Use "providerName/model", for example "openai/gpt-5".',sh=["completions","embeddings"],sw=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function Vo(t,e,n){throw new I(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(Vo,"invalid");function Nt(t,e,n,o){return o?o(t,e,n):Vo(t,e,n)}i(Nt,"reject");function ah(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(ah,"isRecord");function rn(t,e,n){if(typeof t!="string")return Nt(e,"must be a string",Ir,n);if(t.length===0)return Nt(e,"must not be empty",Ir,n);if(t.trim()!==t||/\s/.test(t))return Nt(e,`contains whitespace in '${t}'`,Ir,n);let o=t.indexOf("/");if(o===-1)return Nt(e,`'${t}' has no provider name separator`,Ir,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?Nt(e,`'${t}' has an empty provider name`,Ir,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?Nt(e,`'${t}' has an empty model`,Ir,n):s.startsWith("/")?Nt(e,`'${t}' starts the model with an extra "/"`,Ir,n):{provider:r,model:s,raw:t}:Nt(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(rn,"parseModelRef");function kx(t,e,n){let o=typeof t=="string"?{main:t}:ah(t)?t:{};if(typeof t!="string"&&!ah(t))return Nt(e,"must be a model reference string or an object",'Set it to "providerName/model" or { main: "openai/gpt-5" }',n);let r=Object.keys(o).filter(l=>!sw.includes(l));if(r.length>0)return Nt(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${sw.join(", ")}`,n);if(Object.keys(o).length===0)return Nt(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=rn(o.main,`${e}.main`,n);if(o.backup===null)return Nt(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return Nt(`${e}.quotaFallback`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);let a=o.backup===void 0?void 0:rn(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:rn(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return Nt(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return Nt(`${e}.quotaFallback`,`must differ from '${e}.main'`,"Choose a different quota fallback model or omit 'quotaFallback'",n);let u=o.fallbackTimeoutSeconds;if(u!==void 0){if(a===void 0)return Nt(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return Nt(`${e}.fallbackTimeoutSeconds`,`is a string '${u}', not a number`,"Remove the quotes and set it to a number from 1 through 300",n);if(typeof u!="number"||!Number.isFinite(u)||u<1)return Nt(`${e}.fallbackTimeoutSeconds`,"must be a finite number greater than or equal to 1","Set it to a number from 1 through 300",n);if(u>300)return Nt(`${e}.fallbackTimeoutSeconds`,"must not exceed the platform request duration of 300 seconds","Set it to 300 or less so the backup can run before the request ends",n)}return{main:s.raw,...a===void 0?{}:{backup:a.raw},...u===void 0?{}:{fallbackTimeoutSeconds:u},...c===void 0?{}:{quotaFallback:c.raw}}}i(kx,"normalizeAIGatewayRouteTarget");async function lw(t){let{modelsByProvider:e,providerMetadata:n}=await Ht(t),r=[...new Set([...Object.keys(e),...Object.keys(n)])].map(a=>{let c=n[a],u=Object.values(e[a]??{}).map(l=>({model:l.model,capability:l.kind,status:l.status,inputCostPerToken:l.inputCostPerToken,outputCostPerToken:l.outputCostPerToken}));return{providerName:a,...c?.baseUrl===void 0?{}:{baseUrl:c.baseUrl},...c?.isCustom===void 0?{}:{isCustom:c.isCustom},...c?.providerType===void 0?{}:{providerType:c.providerType.toLowerCase()},models:u}}),s=new Map;for(let[a,c]of Object.entries(n))c.envVarName!==void 0&&s.set(a.toLowerCase(),c.envVarName);return{providers:r,providerEnvironmentVariables:s,modelsByProvider:e,providerMetadata:n}}i(lw,"loadProviders");function _x(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(_x,"conventionEnvironmentVariable");function aw(t){return t&&Je[t]?.trim()||void 0}i(aw,"nonEmptyEnvironmentValue");function xx(t){let{provider:e,providerEnvironmentVariables:n,path:o}=t,r=n.get(e.toLowerCase()),s=_x(e),a=aw(r)??aw(s);if(a===void 0){let c=r?` (catalog binding '${r}' is empty)`:"";return Vo(o,`could not resolve an API key for provider name '${e}'. No key binding found in your account's AI providers${c} and conventional environment variable '${s}' is not set`,`Add an AI provider named '${e}' with an API key in the Zuplo Portal, or set '${s}'`)}return a}i(xx,"resolveApiKey");function Mx(t){let{provider:e,providers:n,path:o}=t,r=n.find(({providerName:a})=>a.toLowerCase()===e.toLowerCase());if(r!==void 0)return r.providerName;let s=n.map(({providerName:a})=>a).sort().join(", ");Vo(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(Mx,"resolveCatalogEntryLabel");function Lx(t){let{provider:e,model:n,capability:o,modelsByProvider:r,providerMetadata:s,path:a}=t,c=e.toLowerCase(),l=s[c]?.providerType?.toLowerCase();if(l===void 0||!nd.some(m=>m===l))return;let d=r[c]?.[n];d?.kind===o&&d.status==="active"||(d?.kind===o&&Vo(a,`model '${n}' is not active for provider name '${e}'`,`Update provider '${e}' model selections to use an active model, or use another provider name that offers it`),Vo(a,`model '${n}' is not included in model selections for provider name '${e}'`,`Update provider '${e}' model selections to include '${n}', or use another provider name that offers it`))}i(Lx,"assertAssignmentOffersModel");function cw(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(cw,"cloneRouting");function Nx(t,e){ce.set(t,uw,e)}i(Nx,"setModelSelection");function fn(t){return ce.get(t,uw)}i(fn,"getModelSelection");var wi={async load(t){let{providers:e}=await lw(t);return e}},Yn={async set(t,e){if(!ah(e))return Vo("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!sh.includes(d));if(n.length>0)return Vo(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=sh.filter(d=>e[d]!==void 0);if(o.length===0)return Vo("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=kx(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await lw(t),l={};for(let d of sh){let m=r[d];if(typeof m!="object")continue;let h=rn(m.main,`routing.${d}.main`),g=m.backup?rn(m.backup,`routing.${d}.backup`):void 0,f=m.quotaFallback?rn(m.quotaFallback,`routing.${d}.quotaFallback`):void 0,R=new Map;for(let[w,v]of[["main",h],["backup",g],["quotaFallback",f]])if(v){let T=Mx({provider:v.provider,providers:s,path:`routing.${d}.${w}`});Lx({provider:T,model:v.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${w}`});let P={...v,provider:T};R.set(w,P)}let S=i(w=>{let v=R.get(w);if(v===void 0)throw new Error(`Missing resolved AI Gateway routing field '${w}'`);return{provider:v.provider,model:v.model,apiKey:xx({provider:v.provider,providerEnvironmentVariables:a,path:`routing.${d}.${w}`})}},"toCandidate");l[d]={candidates:[S("main"),...g?[S("backup")]:[]],...g?{fallbackTimeoutSeconds:m.fallbackTimeoutSeconds??60}:{},...f?{quotaFallback:S("quotaFallback")}:{}}}Nx(t,{byCapability:l}),ce.set(t,iw,cw(r))},get(t){let e=ce.get(t,iw);return e===void 0?void 0:cw(e)}};var qx=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),$x=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Ot(t){let e=new URL(t.url).pathname;for(let[n,o]of $x)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Ot,"getFormat");async function zx(t){let e=Ot(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(zx,"getRequestBody");async function Dx(t,e){let n=Ot(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(Dx,"getResponseBody");function ch(t){let e=t?.usage;if(!e||typeof e!="object")return;let n=i(c=>typeof c=="number"?c:void 0,"num"),o=n(e.input_tokens)??n(e.prompt_tokens),r=n(e.output_tokens)??n(e.completion_tokens);if(o===void 0&&r===void 0)return;let s=o??0,a=r??0;return{promptTokens:s,completionTokens:a,totalTokens:n(e.total_tokens)??s+a}}i(ch,"getUsage");function mt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>mt(e)).filter(Boolean).join(" ");if(t&&typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking;if(typeof e.input_text=="string")return e.input_text;if(e.content!==void 0)return mt(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(mt,"flattenMessageContent");function vr(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(mt(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(mt(e.system)),typeof e.instructions=="string"&&n.push(e.instructions),typeof e.input=="string")n.push(e.input);else if(Array.isArray(e.input))for(let o of e.input)n.push(mt(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(mt(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(mt(o.content));return Array.isArray(e.content)&&n.push(mt(e.content)),n.filter(Boolean).join(`
26
26
  `)}i(vr,"extractAllText");async function*Ux(t,e){let n=Ot(t),o=e.clone().body;if(!o||!n)return;let r=o.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await r.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
27
27
 
28
28
  `))!==-1;){let d=a.slice(0,l);a=a.slice(l+2);let m=jx(d,n);m&&(yield m)}}}finally{r.releaseLock()}}i(Ux,"getStreamEvents");function jx(t,e){let n=t.split(`
@@ -330,7 +330,7 @@ ${s}`)}return r.join(`
330
330
 
331
331
  `)}i(vy,"buildResponseCapture");var tU="https://aisec.akamai.com/fai/v1/fai-configurations/{configurationId}/detect";async function Ty(t){let{content:e,type:n,configurationId:o,apiKey:r,context:s,detectUrl:a}=t;if(!e)return{kind:"ok"};let c=(a??tU).replace("{configurationId}",o),u={clientRequestId:s.requestId};n==="input"?u.llmInput=e:u.llmOutput=e;let l;try{l=await j.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","Fai-Api-Key":r},body:JSON.stringify(u)})}catch(g){return{kind:"error",error:new Error("Akamai Firewall for AI request failed",{cause:g})}}if(!l.ok){let g="";try{g=await l.text()}catch{}return{kind:"error",error:new Error(`Akamai Firewall for AI returned ${l.status} ${l.statusText}${g?`: ${g}`:""}`)}}let d;try{d=await l.json()}catch(g){return{kind:"error",error:new Error("Akamai Firewall for AI response was not valid JSON",{cause:g})}}let m=d.rulesTriggered.find(g=>g.action==="deny");if(m)return{kind:"deny",rule:m};let h=d.rulesTriggered.filter(g=>g.action==="alert");return h.length>0?{kind:"alert",rules:h}:{kind:"ok"}}i(Ty,"callAkamaiDetect");var nU=Ye("zuplo:policies:AkamaiFirewallForAiPolicy");function sl(t,e){let n=t.configurationId,o=t["api-key"];if(!n)throw new I(`Invalid configuration for policy '${e}' - configurationId is required`);if(!o)throw new I(`Invalid configuration for policy '${e}' - api-key is required`);return{configurationId:n,apiKey:o,onWarn:t.onWarn??"log",throwOnError:t.throwOnError??!0,detectUrl:t.detectUrl}}i(sl,"resolveSharedOptions");function EP(t,e,n,o){let r=o==="request"?"Request":"Response";return z.forbidden(e,n,{detail:`${r} blocked by Akamai Firewall for AI during ${o} inspection: ${t.message}`,akamaiFirewall:{ruleId:t.ruleId,category:t.category,riskScore:t.riskScore,action:t.action,source:o}})}i(EP,"buildBlockedProblem");function oU(t,e,n){for(let o of t)e.log.warn({ruleId:o.ruleId,category:o.category,riskScore:o.riskScore,source:n},`Akamai Firewall for AI alert (${n}): ${o.message}`)}i(oU,"logAlertRules");async function al(t){let{content:e,type:n,source:o,config:r,request:s,context:a}=t,c=W.getLogger(a),u=Date.now();if(!e)return c.debug(`Akamai Firewall for AI: no ${o} content captured, skipping detect call`),null;c.debug(`Akamai Firewall for AI: calling detect for ${o}`,{contentLength:e.length,type:n});let l=await Ty({content:e,type:n,configurationId:r.configurationId,apiKey:r.apiKey,context:a,detectUrl:r.detectUrl}),d=Date.now()-u;switch(nU(`Akamai Firewall for AI: ${o} check completed with outcome=${l.kind} latency=${d}ms`),c.debug(`Akamai Firewall for AI: ${o} check completed`,{outcome:l.kind,latency:d}),l.kind){case"ok":return null;case"deny":return Q(`policy.akamai-firewall-for-ai.${o}.blocked`),a.log.warn({ruleId:l.rule.ruleId,category:l.rule.category,riskScore:l.rule.riskScore,source:o},`Akamai Firewall for AI denied ${o}: ${l.rule.message}`),EP(l.rule,s,a,o);case"alert":switch(Q(`policy.akamai-firewall-for-ai.${o}.alert`),r.onWarn){case"block":return a.log.warn({ruleId:l.rules[0].ruleId,category:l.rules[0].category,riskScore:l.rules[0].riskScore,source:o},`Akamai Firewall for AI alert promoted to block (${o}): ${l.rules[0].message}`),EP(l.rules[0],s,a,o);case"log":return oU(l.rules,a,o),null;case"none":return null}break;case"error":if(Q(`policy.akamai-firewall-for-ai.${o}.error`),r.throwOnError)throw c.error(l.error,`Akamai Firewall for AI ${o} check failed; throwing (throwOnError=true)`),l.error;return a.log.error(l.error,`Akamai Firewall for AI ${o} check failed; allowing through (throwOnError=false)`),null}return null}i(al,"runDetect");var rU=Ye("zuplo:policies:AkamaiFirewallForAiInboundPolicy"),OP=i(async(t,e,n,o)=>{let r=W.getLogger(e),s=Date.now();try{let a=sl(n,o),c=await Iy(t,n.capture);return await al({content:c,type:"input",source:"request",config:a,request:t,context:e})??t}finally{let a=Date.now()-s;rU(`AkamaiFirewallForAiInboundPolicy completed - latency ${a}ms`),r.debug("AkamaiFirewallForAiInboundPolicy completed",{latency:a})}},"AkamaiFirewallForAiInboundPolicy");F("akamai-firewall-for-ai",OP);var iU=Ye("zuplo:policies:AkamaiFirewallForAiOutboundPolicy"),kP=i(async(t,e,n,o,r)=>{let s=W.getLogger(n),a=Date.now();try{let c=sl(o,r),u=await vy(t,e,o.capture);return await al({content:u,type:"output",source:"response",config:c,request:e,context:n})??t}finally{let c=Date.now()-a;iU(`AkamaiFirewallForAiOutboundPolicy completed - latency ${c}ms`),s.debug("AkamaiFirewallForAiOutboundPolicy completed",{latency:c})}},"AkamaiFirewallForAiOutboundPolicy");et("akamai-firewall-for-ai",kP);var xP=new WeakMap,_P={},Py=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){xP.set(e,n)}};async function MP(t,e,n,o){if(!n.statusCodes)throw new I(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=eo(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=xP.get(e),c=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new U(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);c=Ro(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let m={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.assign(n.dimensions??{},a?.dimensions)},h=_P[n.apiKey];if(!h){let g=n.apiKey,f=t.headers.get("zm-test-id")??"";h=new Ne({name:"amberflo-ingest-meter",msDelay:10,dispatchFunction:i(async R=>{try{let S=n.url??"https://app.amberflo.io/ingest",w=await j.fetch(S,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":f}});w.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${w.status}: ${await w.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${S.message}`),S}},"dispatchFunction")}),_P[g]=h}h.enqueue(m),e.waitUntil(h.waitUntilFlushed())}}),t}i(MP,"AmberfloMeteringInboundPolicy");F("amberflo-metering",MP);var LP="key-metadata-cache-type",sU="/v3/key-auth/validate";function aU(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(aU,"getKeyValue");async function bm(t,e,n,o){let r,s;if(n.bucketId)r=n.bucketId,s="bucketId";else if(n.bucketName)r=n.bucketName,s="bucketName";else if(Je.ZUPLO_SERVICE_BUCKET_ID)r=Je.ZUPLO_SERVICE_BUCKET_ID,s="bucketId";else if(Je.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r=Je.ZUPLO_API_KEY_SERVICE_BUCKET_NAME,s="bucketName";else throw new I(`ApiKeyInboundPolicy '${o}' - no bucketId or bucketName property provided and neither ZUPLO_SERVICE_BUCKET_ID nor ZUPLO_API_KEY_SERVICE_BUCKET_NAME environment variables are set`);if(!O.instance.authApiJWT)throw new I(`ApiKeyInboundPolicy '${o}' - this deployment has no Zuplo JWT (__ZUPLO_AUTH_API_JWT), which is required to call the API key validation service. Re-deploy the environment; if you are running locally, run 'zuplo link' to pull the environment configuration.`);let a=new URL(sU,O.instance.zuploEdgeApiUrl).toString(),c={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketId:n.bucketId??"",bucketName:n.bucketName??r,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(c.cacheTtlSeconds<60)throw new I(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${c.cacheTtlSeconds}' is invalid`);let u=i(T=>c.allowUnauthenticatedRequests?t:z.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),l=t.headers.get(c.authHeader);if(!l)return u("No Authorization Header");if(!l.toLowerCase().startsWith(c.authScheme.toLowerCase()))return u("Invalid Authorization Scheme");let d=aU(l,c);if(!d||d==="")return u("No key present");let m=await cU(d),h=await Ze(o,c),g=new Ve(h,e),f=await g.get(m);if(f&&f.isValid===!0)return t.user=f.user,t;if(f&&!f.isValid)return f.typeId!==LP&&W.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${f.typeId}'`,f),u("Authorization Failed");let R=new Headers({"content-type":"application/json"});nt(R,e.requestId);let S=await st({retryDelayMs:5,retries:2,logger:W.getLogger(e)},a,{method:"POST",headers:R,body:JSON.stringify({key:d,[s]:r})});if(S.status!==200){try{let T=await S.text(),P=JSON.parse(T);e.log.error("Unexpected response from key service",P)}catch{e.log.error("Invalid response from key service")}throw new U(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${S.status}`)}let w=await S.json();if(!w.authorized)return e.log.info(`ApiKeyInboundPolicy '${o}' - unauthorized response from Key Service`),u("Authorization Failed");if(!w.id||!w.name)throw new U(`ApiKeyInboundPolicy '${o}' - Key Service authorized the key but returned an incomplete payload (missing id or name)`);let v={isValid:!0,typeId:LP,user:{apiKeyId:w.id,sub:w.name,data:w.metadata}};return t.user=v.user,g.put(m,v,c.cacheTtlSeconds),t}i(bm,"ApiKeyInboundPolicy");async function cU(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(cU,"hashValue");F("api-key",bm);var uU=bm;async function NP(t){if(t.events.length===0)return;let e=new Headers({"content-type":"application/json","x-zp-bucket-id":t.bucketId});nt(e,t.requestId??"audit-log-batch");let n=new URL("/v1/runtime/audit-events",O.instance.remoteLogURL),o=await j.fetch(n.toString(),{method:"POST",headers:e,body:JSON.stringify({events:t.events})});if(!o.ok)throw new Error(`audit-log ingest returned ${o.status}`)}i(NP,"postAuditLogBatch");var lU=250,cl=new Map;function qP(t){let e=cl.get(t);return e||(e=new Ne({name:`audit-log:${t}`,msDelay:lU,dispatchFunction:i(async n=>{await NP({bucketId:t,events:n})},"dispatchFunction")}),cl.set(t,e),e)}i(qP,"getOrCreateBatcher");var dU={queryParams:!0,user:!0,ipAddress:!0,geolocation:!0};function pU(t){return{queryParams:t?.queryParams??!0,user:t?.user??!0,ipAddress:t?.ipAddress??!0,geolocation:t?.geolocation??!0}}i(pU,"resolveInclude");var $P=new Map;function zP(t,e,n){let o=e?t.incomingRequestProperties:void 0;return{country:n?.country??o?.country,region:n?.region??o?.region,city:n?.city??o?.city}}i(zP,"resolveGeo");function mU(t,e,n,o,r){let s=new URL(t.url),a=typeof t.user?.sub=="string"?t.user.sub:void 0;return{specversion:"1.0",id:crypto.randomUUID(),source:`//zuplo.com/buckets/${n}/api-gateway`,type:`${o}.request`,time:new Date().toISOString(),datacontenttype:"application/json",bucketid:n,actorsub:r.user?a:void 0,actortype:a?"user":"anonymous",requestid:e.requestId,httpmethod:t.method,httpurl:r.queryParams?`${s.pathname}${s.search}`:s.pathname,ipaddress:r.ipAddress?e.incomingRequestProperties.ip:void 0,useragent:t.headers.get("user-agent")??void 0,...zP(e,r.geolocation)}}i(mU,"buildBaseEvent");var Ay=class extends ue{static{i(this,"AuditLogInboundPolicy")}static policyType="audit-logs";#e;#t;#o;#n;static log(e,n){try{let o=Je.ZUPLO_SERVICE_BUCKET_ID,r=o??"",s=r?cl.get(r):void 0;if(!s&&cl.size===1)for(let[u,l]of cl)r=u,s=l;if(!s){o||e.log.warn("AuditLogInboundPolicy.log called without a bucket id in environment");return}let a=$P.get(r)??dU,c={specversion:"1.0",id:crypto.randomUUID(),source:`//zuplo.com/buckets/${r}/handler`,type:n.type,time:new Date().toISOString(),datacontenttype:"application/json",bucketid:r,requestid:e.requestId,subject:n.subject,actorsub:n.actor?.sub,actortype:n.actor?.type??"anonymous",actoremail:n.actor?.email,actorconnection:n.actor?.connection,resources:n.resources,success:n.success,...zP(e,a.geolocation,n),mcpserver:n.mcp?.server,mcpvirtualserver:n.mcp?.virtualServer,mcptool:n.mcp?.tool,data:n.data};s.enqueue(c),e.waitUntil(s.waitUntilFlushed())}catch(o){e.log.error(o,"AuditLogInboundPolicy.log failed")}}constructor(e,n){super(e,n),this.#e=e?.bucketId??Je.ZUPLO_SERVICE_BUCKET_ID??"",this.#t=e?.eventTypeBase??"com.zuplo.api",this.#n=pU(e?.include);let o=e?.samplingRate;this.#o=typeof o=="number"&&o>=0&&o<=1?o:1,this.#e&&($P.set(this.#e,this.#n),qP(this.#e))}async handler(e,n){if(!this.#e)return n.log.error(`AuditLogInboundPolicy '${this.policyName}' - no bucket id configured`),e;if(this.#o<1&&Math.random()>=this.#o)return e;let o=qP(this.#e),r=mU(e,n,this.#e,this.#t,this.#n);return n.addResponseSendingFinalHook(async(s,a)=>{try{let c=typeof a.user?.sub=="string"?a.user.sub:void 0,u={...r,actorsub:this.#n.user?c??r.actorsub:void 0,actortype:c?"user":r.actortype,httpstatus:s.status,success:s.status>=200&&s.status<400};o.enqueue(u);try{lt.getContextExtensions(n).auditLogEventId=u.id}catch{}n.waitUntil(o.waitUntilFlushed())}catch(c){n.log.error(c,"AuditLogInboundPolicy emit failed")}}),e}};import{createRemoteJWKSet as fU,jwtVerify as _y}from"jose";import{createLocalJWKSet as hU}from"jose";var Ey=class{constructor(e,n,o){this.cache=n;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}cache;static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,n){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,n)}catch(o){if(o instanceof Oy&&this.coolingDown()===!1)return await this.reload(),this.local(e,n);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",O.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(n=>{this.local=hU(n),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(n=>{throw this.pendingFetch=void 0,n}),await this.pendingFetch}async fetchJwks(e,n,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,c=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{c=!0,s.abort()},n));let u;try{u=await j.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers})}catch(l){throw c?new ky("JWKS fetch timed out"):l}finally{a!==void 0&&clearTimeout(a)}if(u.status!==200)throw new Ns("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await u.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Ns("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function DP(t,e,n){let o=new Ey(t,e,n),r=i(async(s,a)=>o.getKey(s,a),"remoteJWKSet");return Object.defineProperty(r,"reload",{value:i(()=>o.reload(),"value"),enumerable:!0,configurable:!1,writable:!1}),r}i(DP,"createRemoteJWKSet");var Ns=class extends U{static{i(this,"JWKSError")}},Oy=class extends Ns{static{i(this,"JWKSNoMatchingKey")}},ky=class extends Ns{static{i(this,"JWKSTimeout")}};var ul={},UP={},gU=3e4;async function yU(t,e,n,o){if(!ul[t]){let r=!1;if("useExperimentalInMemoryCache"in e&&typeof e.useExperimentalInMemoryCache=="boolean"&&(r=e.useExperimentalInMemoryCache),r){let s=await Ze(n,e),a=new Ve(s,o);ul[t]=DP(new URL(t),a,e.headers?{headers:e.headers}:void 0)}else ul[t]=fU(new URL(t),e.headers?{headers:e.headers}:void 0)}return ul[t]}i(yU,"ensureJwksVerifier");var bU=i((t,e)=>async(n,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new I("Invalid State - jwkUrl not set");let r=o.jwkUrl,s=await yU(r,o,t,e);try{let{payload:a}=await _y(n,s,{issuer:o.issuer,audience:o.audience});return a}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&a.code==="ERR_JWKS_NO_MATCHING_KEY"&&ul[r]===s&&typeof s.reload=="function"){let c=Date.now(),u=UP[r]??0;if(c-u>=gU){UP[r]=c;try{await s.reload()}catch{throw a}let{payload:l}=await _y(n,s,{issuer:o.issuer,audience:o.audience});return l}}throw a}},"createJwkVerifier");var SU=i(async(t,e)=>{let n;if(e.secret===void 0)throw new I("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:o}=await _y(t,n,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier");function RU(t){let e=Xe.instance,o=`/.well-known/oauth-protected-resource${t.pathname}`;return Hn.some(a=>a instanceof Qu||a instanceof Yu)?!0:e.routeData.routes.some(a=>{let c=a.pathPattern||a.path;try{return new Xp({pathname:c}).test({pathname:o})}catch{return!1}})}i(RU,"ensureOAuthResourceMetadataRouteExists");var Jt=i(async(t,e,n,o)=>{let r=n.authHeader??"Authorization",s=t.headers.get(r),a="bearer ",c=i(g=>z.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new I(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new I(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?bU(o,e):SU,d=await i(async()=>{if(!s){let f=new URL(t.url);if(n.oAuthResourceMetadataEnabled&&RU(f)){let R=new URL(`/.well-known/oauth-protected-resource${f.pathname}`,f.origin);return z.unauthorized(t,e,{detail:"Bearer token required"},{"WWW-Authenticate":`Bearer resource_metadata="${R.toString()}"`})}return c("No authorization header")}if(s.toLowerCase().indexOf(a)!==0)return c("Invalid bearer token format for authorization header");let g=s.substring(a.length);if(!g||g.length===0)return c("No bearer token on authorization header");try{return await u(g,n)}catch(f){let R=new URL(t.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,f):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,f),c("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return n.allowUnauthenticatedRequests===!0?t:d;let m=n.subPropertyName??"sub",h=d[m];return h?(t.user={sub:h,data:d},t):c(`Token is not valid, no '${m}' property found.`)},"OpenIdJwtInboundPolicy");F("open-id-jwt-auth",Jt);var jP=i(async(t,e,n,o)=>Jt(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,oAuthResourceMetadataEnabled:n.oAuthResourceMetadataEnabled},o),"Auth0JwtInboundPolicy");F("auth0-jwt-auth",jP);function $e(t,e,n="policy",o){let r=`${n} '${e}'`;if(!Er(t))throw new I(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let s=i((u,l,d)=>{let m=t[u],h=o?`${o}.${String(u)}`:String(u);if(!(d&&m===void 0)){if(m===void 0)throw new I(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"){if(!Array.isArray(m))throw new I(`Value of '${h}' on ${r} must be an array. Received type ${typeof m}.`)}else if(typeof m!==l)throw new I(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof m}.`);if(typeof m=="string"&&m.length===0)throw new I(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof m=="number"&&Number.isNaN(m))throw new I(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((u,l)=>(s(u,l,!0),{optional:a,required:c}),"optional"),c=i((u,l)=>(s(u,l,!1),{optional:a,required:c}),"required");return{optional:a,required:c}}i($e,"optionValidator");var HP=new Map;function wU(t){let e=[],n=0;for(;n<t.length;){if(t[n]==="."){n++;continue}if(t[n]==="["){for(n++;n<t.length&&/\s/.test(t[n]);)n++;let o=t[n];if(o!=='"'&&o!=="'"){for(;n<t.length&&t[n]!=="]";)n++;n++;continue}n++;let r=n;for(;n<t.length&&t[n]!==o;)n++;let s=t.substring(r,n);for(e.push(s),n++;n<t.length&&/\s/.test(t[n]);)n++;t[n]==="]"&&n++}else{let o=n;for(;n<t.length&&t[n]!=="."&&t[n]!=="[";)n++;let r=t.substring(o,n).trim();r.length>0&&e.push(r)}}return e}i(wU,"parsePropertyPath");function Sm(t,e){let n="$authzen-prop(";if(!t.startsWith(n)||!t.endsWith(")"))return t;let o=t.slice(n.length,-1),r=HP.get(o);r||(r=wU(o),HP.set(o,r));let s=e;for(let a of r){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(Sm,"evaluateAuthzenProp");var FP=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),xy=class t extends ue{static{i(this,"AuthZenInboundPolicy")}static policyType="authzen";#e;#t;constructor(e,n){if(super(e,n),$e(e,n).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new I(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new I(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new I(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new I(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new I(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=`${e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`}/access/v1/evaluation`;try{new URL(this.#e)}catch(o){throw new I(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
332
332
  ${o}`)}}async handler(e,n){let o=this.options.throwOnError!==!1;try{await this.#r(n);let r=this.options.debug===!0,s={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:n};s.action?.name!==void 0&&(s.action.name=Sm(s.action.name,a)),s.subject?.id!==void 0&&(s.subject.id=Sm(s.subject.id,a)),s.resource?.id!==void 0&&(s.resource.id=Sm(s.resource.id,a)),r&&n.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,s);let c=t.getAuthorizationPayload(n);c&&Object.assign(s,c),r&&n.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:c,final:s}),this.#o(n,!s.subject?.type||!s.subject?.id,"Missing required subject type or id"),this.#o(n,!s.resource?.type||!s.resource?.id,"Missing required resource type or id"),this.#o(n,!s.action,"Missing required action");let u={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(u.authorization=this.options.authorizerAuthorizationHeader);let l=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(s),headers:u});if(!l.ok){let m=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
333
- ${await l.text()}`;if(o)throw new Error(m);return n.log.error(m),e}let d=await l.json();if(r&&n.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#n(e,n,d.reason)}catch(r){if(o)throw r;n.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${r}`)}return e}#o(e,n,o){if(n){let r=`${this.policyType} '${this.policyName}' - ${o}`;if(this.options.throwOnError)throw new I(r);e.log.warn(r)}}async#n(e,n,o){return z.forbidden(e,n,{detail:o})}async#r(e){if(!this.#t){let n=await Ze(this.policyName,this.options);this.#t=new Ve(n,e)}}static setAuthorizationPayload(e,n){ce.set(e,FP,n)}static getAuthorizationPayload(e){return ce.get(e,FP)}};var Rm=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(`${e.pdpUsername}:${e.pdpPassword}`)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}options;static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let n=await j.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!n.ok)throw new Error(`Request to PDP service failed with response status ${n.status}.`);return await n.json()}};var My=class t extends ue{static{i(this,"AxiomaticsAuthZInboundPolicy")}static policyType="axiomatics-authz";pdpService;static#e;static setAuthAttributes(e,n){t.#e||(t.#e=new WeakMap),t.#e.set(e,{Request:n})}constructor(e,n){super(e,n),$e(e,n).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Rm(e)}async handler(e,n){let o=i(a=>this.options.allowUnauthorizedRequests?e:z.forbidden(e,n,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=t.#e?.get(n)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([c,u])=>{a.push({AttributeId:`request.params.${c}`,Value:u})}),r.searchParams.forEach((c,u)=>{a.push({AttributeId:`request.query.${u}`,Value:c})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:n}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:n}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:n});try{n.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return n.log.debug("PDP Response",a),a.Response.every(c=>c.Decision==="Permit")?e:(n.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return n.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),z.internalServerError(e,n)}}populateOptionAttributes({optionName:e,authzRequestCategory:n,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(c=>{c.value?a.push({AttributeId:c.attributeId,Value:c.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,n,a)}}addAttributesToCategory(e,n,o){e.Request[n]||(e.Request[n]=[]),e.Request[n].length===0?e.Request[n].push({Attribute:[]}):e.Request[n][0].Attribute=e.Request[n][0].Attribute??[],e.Request[n][0].Attribute.push(...o)}};var GP=i(async(t,e,n)=>{let o=t.headers.get("Authorization"),r="basic ",s=i(l=>z.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),m=d.indexOf(":");if(m===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,m),g=d.substring(m+1),f=n.accounts.find(R=>R.username===h&&R.password===g);return f||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return n.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");F("basic-auth",GP);function wm(t){return{second:t.getSeconds(),minute:t.getMinutes(),hour:t.getHours(),day:t.getDate(),month:t.getMonth(),weekday:t.getDay(),year:t.getFullYear()}}i(wm,"extractDateElements");function ZP(t,e){return new Date(t,e+1,0).getDate()}i(ZP,"getDaysInMonth");function Ly(t,e){return t<=e?e-t:6-t+e+1}i(Ly,"getDaysBetweenWeekdays");var Cm=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:n,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!n||n.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((u,l)=>u-l),this.minutes=Array.from(n).sort((u,l)=>u-l),this.hours=Array.from(o).sort((u,l)=>u-l),this.days=Array.from(r).sort((u,l)=>u-l),this.months=Array.from(s).sort((u,l)=>u-l),this.weekdays=Array.from(a).sort((u,l)=>u-l);let c=i((u,l,d)=>{if(l.some(m=>typeof m!="number"||m%1!==0||m<d.min||m>d.max))throw new Error(`${u} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");c("seconds",this.seconds,{min:0,max:59}),c("minutes",this.minutes,{min:0,max:59}),c("hours",this.hours,{min:0,max:23}),c("days",this.days,{min:1,max:31}),c("months",this.months,{min:0,max:11}),c("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(u=>u).reverse(),minutes:this.minutes.map(u=>u).reverse(),hours:this.hours.map(u=>u).reverse(),days:this.days.map(u=>u).reverse(),months:this.months.map(u=>u).reverse(),weekdays:this.weekdays.map(u=>u).reverse()}}findAllowedHour(e,n){return e==="next"?this.hours.find(o=>o>=n):this.reversed.hours.find(o=>o<=n)}findAllowedMinute(e,n){return e==="next"?this.minutes.find(o=>o>=n):this.reversed.minutes.find(o=>o<=n)}findAllowedSecond(e,n){return e==="next"?this.seconds.find(o=>o>n):this.reversed.seconds.find(o=>o<n)}findAllowedTime(e,n){let o=this.findAllowedHour(e,n.hour);if(o!==void 0)if(o===n.hour){let r=this.findAllowedMinute(e,n.minute);if(r!==void 0)if(r===n.minute){let s=this.findAllowedSecond(e,n.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?n.minute+1:n.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?n.hour+1:n.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,n,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=ZP(n,o),a=this.days.length!==31,c=this.weekdays.length!==7;if(!a&&!c)return r>s?e==="next"?void 0:s:r;let u;a&&(u=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),u!==void 0&&u>s&&(u=void 0));let l;if(c){let d=new Date(n,o,r).getDay(),m=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(m!==void 0){let h=e==="next"?Ly(d,m):Ly(m,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(u!==void 0&&l!==void 0)return e==="next"?Math.min(u,l):Math.max(u,l);if(u!==void 0)return u;if(l!==void 0)return l}getNextDate(e=new Date){let n=wm(e),o=n.year,r=this.months.findIndex(a=>a>=n.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let c=o+Math.floor((r+a)/this.months.length),u=this.months[(r+a)%this.months.length],l=c===n.year&&u===n.month,d=this.findAllowedDayInMonth("next",c,u,l?n.day:1),m=l&&d===n.day;if(d!==void 0&&m){let h=this.findAllowedTime("next",n);if(h!==void 0)return new Date(c,u,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",c,u,d+1),m=!1}if(d!==void 0&&!m)return new Date(c,u,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,n){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??n),o.push(r);return o}*getNextDatesIterator(e,n){let o;for(;;){if(o=this.getNextDate(e),e=o,n&&n.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let n=wm(e),o=n.year,r=this.reversed.months.findIndex(a=>a<=n.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let c=o-Math.floor((r+a)/this.reversed.months.length),u=this.reversed.months[(r+a)%this.reversed.months.length],l=c===n.year&&u===n.month,d=this.findAllowedDayInMonth("prev",c,u,l?n.day:31),m=l&&d===n.day;if(d!==void 0&&m){let h=this.findAllowedTime("prev",n);if(h!==void 0)return new Date(c,u,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",c,u,d-1),m=!1)}if(d!==void 0&&!m)return new Date(c,u,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,n){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??n),o.push(r);return o}*getPrevDatesIterator(e,n){let o;for(;;){if(o=this.getPrevDate(e),e=o,n&&n.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:n,minute:o,hour:r,day:s,month:a,weekday:c}=wm(e);return this.seconds.indexOf(n)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(c)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(c)!==-1}};var CU={min:0,max:59},IU={min:0,max:59},vU={min:0,max:23},TU={min:1,max:31},PU={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},AU={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},EU={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ii(t,e){let n=new Set;if(t==="*"){for(let d=e.min;d<=e.max;d=d+1)n.add(d);return n}let o=t.split(",");if(o.length>1)return o.forEach(d=>{ii(d,e).forEach(h=>n.add(h))}),n;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let m=parseInt(d,10);if(Number.isNaN(m))throw new Error(`Failed to parse ${t}: ${d} is NaN.`);if(m<e.min||m>e.max)throw new Error(`Failed to parse ${t}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return m},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(t);if(s===null)return n.add(r(t)),n;let a=s[1]==="*"?e.min:r(s[3]),c=s[1]==="*"?e.max:r(s[4]);if(a>c)throw new Error(`Failed to parse ${t}: Invalid range (start: ${a}, end: ${c}).`);let u=s[6],l=1;if(u!==void 0){if(l=parseInt(u,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${u} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${u} to be greater than 0.`)}for(let d=a;d<=c;d=d+l)n.add(d);return n}i(ii,"parseElement");function Ny(t){if(typeof t!="string")throw new TypeError("Invalid cron expression: must be of type string.");t=EU[t.toLowerCase()]??t;let e=t.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let n=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],c=e.length===6?e[5]:e[4];return new Cm({seconds:ii(n,CU),minutes:ii(o,IU),hours:ii(r,vU),days:ii(s,TU),months:new Set(Array.from(ii(a,PU)).map(u=>u-1)),weekdays:new Set(Array.from(ii(c,AU)).map(u=>u%7))})}i(Ny,"parseCronExpression");var qy=class extends ue{static{i(this,"BrownoutInboundPolicy")}static policyType="brownout";crons;constructor(e,n){if(super(e,n),$e(e,n).optional("problem","object"),e.problem&&$e(e.problem,n,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new I(`Value of 'cronSchedule' on policy '${n}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Ny(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Ny(o))}async handler(e,n){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=z.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return z.format(s,e,n)}return e}};var OU="caching",kU=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _U(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(_U,"digestMessage");var xU=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,m]of t.headers.entries())n.includes(d)&&o.push({key:d.toLowerCase(),value:m});o.sort((d,m)=>d.key.localeCompare(m.key));let r=await _U(JSON.stringify(o)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function BP(t,e,n,o){let r=await Ze(o,n),s=await caches.open(r),a=co(t,e,{cacheType:"http",policyType:OU,policyName:o});if(!(n?.cacheHttpMethods?.map(h=>h.toUpperCase())??["GET"]).includes(t.method.toUpperCase()))return Qe(e,{...a,outcome:"skip",reason:"method"}),t;let u=await xU(t,n),l=Date.now(),d=await s.match(u),m=Date.now()-l;return d?(Qe(e,{...a,outcome:"hit",latencyMs:m,statusCode:d.status}),d):(Qe(e,{...a,outcome:"miss",latencyMs:m}),e.addEventListener("responseSent",h=>{try{let g=n.statusCodes??[200,206,301,302,303,404,410],f=h.response.clone();if(!g.includes(f.status)){In(e,{...a,outcome:"not_stored",reason:"status",statusCode:f.status});return}let R=n?.expirationSecondsTtl??60,S=new Response(f.body,f);kU.forEach(v=>S.headers.delete(v)),S.headers.set("cache-control",`s-maxage=${R}`);let w=Date.now();e.waitUntil(s.put(u,S).then(()=>In(e,{...a,outcome:"store",statusCode:f.status,latencyMs:Date.now()-w})).catch(()=>In(e,{...a,outcome:"error",reason:"store-error",statusCode:f.status,latencyMs:Date.now()-w})))}catch(g){e.log.error(`Error in caching-inbound-policy '${o}': "${g.message}"`,g)}}),t)}i(BP,"CachingInboundPolicy");F("caching",BP);var MU=/^[A-Za-z0-9&'^\-$!`#%.+~_|/]+$/,Im=/^[\x21-\x7e]+$/,qs={akamai:{label:"Akamai",targetedHeader:"edge-control",targetedSyntax:"edge-control",readsHeaders:["edge-control"],tagHeader:"edge-cache-tag",tagSeparator:",",maxTagLength:128,maxTags:128,maxTagHeaderBytes:8192,tagPattern:MU,tagCharset:"alphanumerics and & ' ^ - $ ! ` # % . + ~ _ | / (no spaces, commas, colons or brackets)",supportsStaleDirectives:!1},fastly:{label:"Fastly",targetedHeader:"surrogate-control",targetedSyntax:"cache-control",readsHeaders:["surrogate-control"],tagHeader:"surrogate-key",tagSeparator:" ",maxTagLength:1024,maxTags:Number.POSITIVE_INFINITY,maxTagHeaderBytes:16384,tagPattern:Im,tagCharset:"any printable ASCII except spaces",supportsStaleDirectives:!0},cloudflare:{label:"Cloudflare",targetedHeader:"cloudflare-cdn-cache-control",targetedSyntax:"cache-control",readsHeaders:["cloudflare-cdn-cache-control","cdn-cache-control"],tagHeader:"cache-tag",tagSeparator:",",maxTagLength:1024,maxTags:Number.POSITIVE_INFINITY,maxTagHeaderBytes:16384,tagPattern:Im,tagCharset:"any printable ASCII except spaces",supportsStaleDirectives:!0},cloudfront:{label:"CloudFront",targetedHeader:null,targetedSyntax:"cache-control",readsHeaders:[],tagHeader:null,tagSeparator:",",maxTagLength:0,maxTags:0,maxTagHeaderBytes:0,tagPattern:Im,tagCharset:"n/a \u2014 CloudFront has no purge-by-tag support",supportsStaleDirectives:!0},generic:{label:"an RFC 9213 CDN",targetedHeader:"cdn-cache-control",targetedSyntax:"cache-control",readsHeaders:["cdn-cache-control"],tagHeader:null,tagSeparator:",",maxTagLength:0,maxTags:0,maxTagHeaderBytes:0,tagPattern:Im,tagCharset:"n/a \u2014 no purge-tag header is defined for this dialect",supportsStaleDirectives:!0}};function $y(t,e){return e!==void 0?e:qs[t].targetedHeader===null?"s-maxage":"targeted"}i($y,"resolveStrategy");var LU=["no-store","no-cache","private"];function NU(t){let e=new Map;if(!t)return e;for(let n of t.split(",")){let o=n.trim();if(o.length===0)continue;let r=o.indexOf("=");if(r===-1){e.set(o.toLowerCase(),!0);continue}let s=o.slice(0,r).trim().toLowerCase(),a=o.slice(r+1).trim();e.set(s,a.replace(/^"(.*)"$/,"$1"))}return e}i(NU,"parseCacheControl");function qU(t){return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}i(qU,"parseVary");function $U(t,e){let n=new Set,o=[];for(let r of[...t,...e]){let s=r.trim().toLowerCase();if(!(s.length===0||n.has(s))){if(s==="*")return"*";n.add(s),o.push(s)}}return o.join(", ")}i($U,"unionVary");function zU(t,e){let n=t.get(e);if(typeof n!="string")return;let o=Number(n);return Number.isFinite(o)&&o>=0?Math.floor(o):void 0}i(zU,"numericDirective");function DU(t){let e=[[86400,"d"],[3600,"h"],[60,"m"]];for(let[n,o]of e)if(t>=n&&t%n===0)return`${t/n}${o}`;return`${t}s`}i(DU,"formatEdgeControlDuration");function UU(t,e,n){if(t.targetedSyntax==="edge-control"){let r=[`cache-maxage=${DU(e.maxAge)}`];return n&&r.push("!no-store"),r.join(" ")}let o=[`max-age=${e.maxAge}`];return e.staleWhileRevalidate!==void 0&&o.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&o.push(`stale-if-error=${e.staleIfError}`),o.join(", ")}i(UU,"renderEdgeDirectives");function jU(t,e){if(t.visibility==="no-store")return"no-store";let n=[];return t.visibility!==void 0&&n.push(t.visibility),t.maxAge!==void 0&&n.push(`max-age=${t.maxAge}`),t.noCache&&n.push("no-cache"),t.mustRevalidate&&n.push("must-revalidate"),e!==void 0&&(n.push(`s-maxage=${e.maxAge}`),e.staleWhileRevalidate!==void 0&&n.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&n.push(`stale-if-error=${e.staleIfError}`)),n.join(", ")}i(jU,"renderClientCacheControl");var HU=["s-maxage","stale-while-revalidate","stale-if-error"];function FU(t,e){let n=[];for(let o of(t??"").split(",")){let r=o.trim();if(r.length===0)continue;let s=r.split("=")[0].trim().toLowerCase();HU.includes(s)||n.push(r)}return n.push(`s-maxage=${e.maxAge}`),e.staleWhileRevalidate!==void 0&&n.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&n.push(`stale-if-error=${e.staleIfError}`),n.join(", ")}i(FU,"appendEdgeDirectives");function GU(t,e){if(e.has("no-store")||t.visibility==="no-store")return{visibility:"no-store"};let n=zU(e,"max-age"),o={mustRevalidate:t.mustRevalidate===!0||e.has("must-revalidate"),noCache:t.noCache===!0||e.has("no-cache")};e.has("private")||t.visibility==="private"?o.visibility="private":t.visibility!==void 0&&(o.visibility=t.visibility);let r=[t.maxAge,n].filter(s=>s!==void 0);return r.length>0&&(o.maxAge=Math.min(...r)),o}i(GU,"mergeStrictest");function VP(t){let e=qs[t.vendor],n={set:{},remove:[],warnings:[],edgeSuppressed:!1},o=NU(t.upstream.get("cache-control")),r=t.upstream.get("set-cookie")!==null,s=LU.find(m=>o.has(m)),a=t.config.cache===!1,c=t.respectUpstream&&(s!==void 0||r);if(a||c)return c&&n.warnings.push(s!==void 0?`Upstream sent \`cache-control: ${s}\`, so no CDN cache headers were set. Set \`respectUpstream: false\` to override it.`:"Upstream set a cookie on this response, so no CDN cache headers were set. Set `respectUpstream: false` to override it."),n.edgeSuppressed=!0,n.remove.push(...e.readsHeaders),e.tagHeader!==null&&n.remove.push(e.tagHeader),a&&t.clientMode!=="preserve"&&(n.set["cache-control"]="no-store"),n;let u=t.config.edge;if(t.clientMode!=="preserve"){let m=t.config.client??{},h=t.clientMode==="strictest"?GU(m,o):m,g=t.strategy==="s-maxage"?u:void 0;g!==void 0&&h.visibility==="no-store"&&n.warnings.push('The client policy resolved to `no-store`, which cannot carry an `s-maxage`, so the configured edge TTL was not emitted. Remove `client.visibility: "no-store"`, or set `cache: false` if the response is genuinely uncacheable.');let f=jU(h,g);f.length>0?n.set["cache-control"]=f:t.clientMode==="replace"&&n.remove.push("cache-control")}else t.strategy==="s-maxage"&&u!==void 0&&(n.set["cache-control"]=FU(t.upstream.get("cache-control"),u));let l=u!==void 0&&t.strategy==="targeted"?e.targetedHeader:null;n.remove.push(...e.readsHeaders.filter(m=>m!==l)),u===void 0?n.warnings.push("No edge `maxAge` was resolved from the options or the cacheConfig function, so no CDN cache header was set."):t.strategy==="targeted"&&(e.targetedHeader===null?n.warnings.push(`${e.label} reads no targeted cache header, so the edge TTL was not emitted. Use \`strategy: "s-maxage"\`.`):(!e.supportsStaleDirectives&&(u.staleWhileRevalidate!==void 0||u.staleIfError!==void 0)&&n.warnings.push(`${e.label}'s \`${e.targetedHeader}\` header cannot express \`stale-while-revalidate\` or \`stale-if-error\`, so the cacheConfig function's stale window was not emitted. Configure stale serving in Property Manager, or set \`strategy: "s-maxage"\` to emit it on \`Cache-Control\` instead.`),n.set[e.targetedHeader]=UU(e,u,!t.respectUpstream)));let d=t.config.tags??[];if(d.length>0&&e.tagHeader===null&&n.warnings.push(`${e.label} has no purge-by-tag support, so ${d.length} tag(s) were not emitted.`),e.tagHeader!==null){let{accepted:m,errors:h}=JP(e,d);n.warnings.push(...h),m.length>0?n.set[e.tagHeader]=m.join(e.tagSeparator):n.remove.push(e.tagHeader)}if(t.vary.length>0){let m=$U(t.vary,qU(t.upstream.get("vary")));m.length>0&&(n.set.vary=m,t.vendor==="akamai"&&n.warnings.push("Emitting `Vary` on Akamai suppresses edge caching until Cache ID Modification is configured in Property Manager."))}return n}i(VP,"buildCdnCacheControlPlan");function JP(t,e){let n=[],o=[],r=new TextEncoder,s=0;for(let a of e){if(a.length===0)continue;if(a.length>t.maxTagLength){o.push(`Cache tag "${a}" is ${a.length} characters; ${t.label} allows ${t.maxTagLength}. Shorten the tag \u2014 an over-long tag is silently dropped at the edge.`);continue}if(!t.tagPattern.test(a)||a.includes(t.tagSeparator)){o.push(`Cache tag "${a}" contains characters ${t.label} does not accept. ${t.label} allows ${t.tagCharset}, and never the separator ("${t.tagSeparator}"). Alphanumerics, dashes and underscores are accepted by every CDN, so prefer those if you may switch.`);continue}if(n.length>=t.maxTags){o.push(`More than ${t.maxTags} cache tags for ${t.label}; "${a}" and any after it were dropped.`);break}let c=r.encode(a).length+(n.length>0?1:0);if(s+c>t.maxTagHeaderBytes){o.push(`Cache tag header exceeds ${t.maxTagHeaderBytes} bytes for ${t.label}; "${a}" and any after it were dropped.`);break}s+=c,n.push(a)}return{accepted:n,errors:o}}i(JP,"selectValidTags");function KP(t){let e=qs[t.vendor],n=[];if(t.edge===void 0&&!t.hasCacheConfigFunction&&n.push("options.edge is required unless options.cacheConfig supplies the policy at runtime. Add `edge: { maxAge: <seconds> }`, which is the TTL the CDN may serve this response for."),t.strategy==="targeted"&&e.targetedHeader===null&&n.push(`options.strategy is "targeted" but ${e.label} reads no targeted cache header \u2014 only \`Cache-Control: s-maxage\`. Set \`strategy: "s-maxage"\`.`),t.strategy==="targeted"&&!e.supportsStaleDirectives&&t.edge!==void 0&&(t.edge.staleWhileRevalidate!==void 0||t.edge.staleIfError!==void 0)&&n.push(`${e.label}'s \`${e.targetedHeader}\` header cannot express \`stale-while-revalidate\` or \`stale-if-error\`. Configure stale serving in Property Manager and remove these options, or set \`strategy: "s-maxage"\` to emit them on \`Cache-Control\` instead.`),t.tags.length>0&&e.tagHeader===null&&n.push(t.vendor==="cloudfront"?"options.tags is set but CloudFront has no purge-by-tag support. Remove the tags and invalidate by path instead.":`options.tags is set but no purge-tag header is defined for ${e.label}. Remove the tags, or set \`cdn\` to the CDN actually in front of this gateway.`),t.tags.length>0&&e.tagHeader!==null){let{errors:o}=JP(e,t.tags);n.push(...o)}return n}i(KP,"validateStaticConfig");var WP=new WeakMap;function vm(t,e){return typeof t=="string"&&Object.hasOwn(e,t)}i(vm,"isOneOf");var YP={targeted:!0,"s-maxage":!0},QP={strictest:!0,replace:!0,preserve:!0},Tm={public:!0,private:!0,"no-store":!0};function $s(t){return Number.isSafeInteger(t)&&t>=0}i($s,"isSeconds");function Pm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(Pm,"isConfigObject");function XP(t){if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(typeof t[e]!="string")return!1;return!0}i(XP,"isStringArray");function ZU(t){let e=[],n=t;if(n.strategy!==void 0&&!vm(n.strategy,YP)&&e.push(`options.strategy must be one of ${Object.keys(YP).join(", ")}. An unrecognised value matches no branch, so no edge cache header is emitted at all.`),n.client!==void 0)if(!Pm(n.client))e.push("options.client must be an object.");else{let o=n.client;o.maxAge!==void 0&&!$s(o.maxAge)&&e.push("options.client.maxAge must be a non-negative whole number of seconds."),o.mode!==void 0&&!vm(o.mode,QP)&&e.push(`options.client.mode must be one of ${Object.keys(QP).join(", ")}. An unrecognised value falls through to \`replace\`, the least restrictive mode \u2014 a typo here would silently stop the policy honouring an upstream \`private\`.`);for(let r of["mustRevalidate","noCache"])o[r]!==void 0&&typeof o[r]!="boolean"&&e.push(`options.client.${r} must be a boolean. A truthy non-boolean such as the string "false" would add the directive rather than omit it.`);o.visibility!==void 0&&!vm(o.visibility,Tm)&&e.push(`options.client.visibility must be one of ${Object.keys(Tm).join(", ")}. An unrecognised value is dropped, so no visibility directive is sent.`)}if(n.edge!==void 0)if(!Pm(n.edge))e.push("options.edge must be an object, e.g. `{ maxAge: 1800 }`.");else{let o=n.edge;$s(o.maxAge)||e.push("options.edge.maxAge must be a non-negative whole number of seconds. Anything else renders as `max-age=undefined`/`max-age=NaN`, which a CDN discards \u2014 disabling the caching you configured.");for(let r of["staleWhileRevalidate","staleIfError"])o[r]!==void 0&&!$s(o[r])&&e.push(`options.edge.${r} must be a non-negative whole number of seconds.`)}for(let o of["tags","vary"])n[o]!==void 0&&!XP(n[o])&&e.push(`options.${o} must be an array of strings. A bare string is iterated character by character.`);return n.respectUpstream!==void 0&&typeof n.respectUpstream!="boolean"&&e.push("options.respectUpstream must be a boolean."),e}i(ZU,"collectShapeErrors");function BU(t,e){if(typeof t!="object"||t===null)throw new I(`CdnCacheControlOutboundPolicy '${e}' - options must be an object. See the policy documentation for the supported fields.`);if(WP.has(t))return;let n=t.cdn;if(typeof n!="string"||!Object.hasOwn(qs,n))throw new I(`CdnCacheControlOutboundPolicy '${e}' - options.cdn is required and must be one of ${Object.keys(qs).join(", ")}. It has no default because each CDN reads a different header for shared-cache TTL and purge tags, so a wrong guess fails silently; use "generic" for an RFC 9213 CDN that is not listed.`);let o=ZU(t);if(o.length===0&&o.push(...KP({vendor:t.cdn,strategy:$y(t.cdn,t.strategy),edge:t.edge,tags:t.tags??[],hasCacheConfigFunction:eA(t.cacheConfig)})),o.length>0)throw new I(`Invalid options on \`cdn-cache-control-outbound\` policy "${e}". Validation failed:
333
+ ${await l.text()}`;if(o)throw new Error(m);return n.log.error(m),e}let d=await l.json();if(r&&n.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#n(e,n,d.reason)}catch(r){if(o)throw r;n.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${r}`)}return e}#o(e,n,o){if(n){let r=`${this.policyType} '${this.policyName}' - ${o}`;if(this.options.throwOnError)throw new I(r);e.log.warn(r)}}async#n(e,n,o){return z.forbidden(e,n,{detail:o})}async#r(e){if(!this.#t){let n=await Ze(this.policyName,this.options);this.#t=new Ve(n,e)}}static setAuthorizationPayload(e,n){ce.set(e,FP,n)}static getAuthorizationPayload(e){return ce.get(e,FP)}};var Rm=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(`${e.pdpUsername}:${e.pdpPassword}`)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}options;static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let n=await j.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!n.ok)throw new Error(`Request to PDP service failed with response status ${n.status}.`);return await n.json()}};var My=class t extends ue{static{i(this,"AxiomaticsAuthZInboundPolicy")}static policyType="axiomatics-authz";pdpService;static#e;static setAuthAttributes(e,n){t.#e||(t.#e=new WeakMap),t.#e.set(e,{Request:n})}constructor(e,n){super(e,n),$e(e,n).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Rm(e)}async handler(e,n){let o=i(a=>this.options.allowUnauthorizedRequests?e:z.forbidden(e,n,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=t.#e?.get(n)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([c,u])=>{a.push({AttributeId:`request.params.${c}`,Value:u})}),r.searchParams.forEach((c,u)=>{a.push({AttributeId:`request.query.${u}`,Value:c})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:n}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:n}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:n});try{n.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return n.log.debug("PDP Response",a),a.Response.every(c=>c.Decision==="Permit")?e:(n.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return n.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),z.internalServerError(e,n)}}populateOptionAttributes({optionName:e,authzRequestCategory:n,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(c=>{c.value?a.push({AttributeId:c.attributeId,Value:c.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,n,a)}}addAttributesToCategory(e,n,o){e.Request[n]||(e.Request[n]=[]),e.Request[n].length===0?e.Request[n].push({Attribute:[]}):e.Request[n][0].Attribute=e.Request[n][0].Attribute??[],e.Request[n][0].Attribute.push(...o)}};var GP=i(async(t,e,n)=>{let o=t.headers.get("Authorization"),r="basic ",s=i(l=>z.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),m=d.indexOf(":");if(m===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,m),g=d.substring(m+1),f=n.accounts.find(R=>R.username===h&&R.password===g);return f||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return n.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");F("basic-auth",GP);function wm(t){return{second:t.getSeconds(),minute:t.getMinutes(),hour:t.getHours(),day:t.getDate(),month:t.getMonth(),weekday:t.getDay(),year:t.getFullYear()}}i(wm,"extractDateElements");function ZP(t,e){return new Date(t,e+1,0).getDate()}i(ZP,"getDaysInMonth");function Ly(t,e){return t<=e?e-t:6-t+e+1}i(Ly,"getDaysBetweenWeekdays");var Cm=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:n,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!n||n.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((u,l)=>u-l),this.minutes=Array.from(n).sort((u,l)=>u-l),this.hours=Array.from(o).sort((u,l)=>u-l),this.days=Array.from(r).sort((u,l)=>u-l),this.months=Array.from(s).sort((u,l)=>u-l),this.weekdays=Array.from(a).sort((u,l)=>u-l);let c=i((u,l,d)=>{if(l.some(m=>typeof m!="number"||m%1!==0||m<d.min||m>d.max))throw new Error(`${u} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");c("seconds",this.seconds,{min:0,max:59}),c("minutes",this.minutes,{min:0,max:59}),c("hours",this.hours,{min:0,max:23}),c("days",this.days,{min:1,max:31}),c("months",this.months,{min:0,max:11}),c("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(u=>u).reverse(),minutes:this.minutes.map(u=>u).reverse(),hours:this.hours.map(u=>u).reverse(),days:this.days.map(u=>u).reverse(),months:this.months.map(u=>u).reverse(),weekdays:this.weekdays.map(u=>u).reverse()}}findAllowedHour(e,n){return e==="next"?this.hours.find(o=>o>=n):this.reversed.hours.find(o=>o<=n)}findAllowedMinute(e,n){return e==="next"?this.minutes.find(o=>o>=n):this.reversed.minutes.find(o=>o<=n)}findAllowedSecond(e,n){return e==="next"?this.seconds.find(o=>o>n):this.reversed.seconds.find(o=>o<n)}findAllowedTime(e,n){let o=this.findAllowedHour(e,n.hour);if(o!==void 0)if(o===n.hour){let r=this.findAllowedMinute(e,n.minute);if(r!==void 0)if(r===n.minute){let s=this.findAllowedSecond(e,n.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?n.minute+1:n.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?n.hour+1:n.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,n,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=ZP(n,o),a=this.days.length!==31,c=this.weekdays.length!==7;if(!a&&!c)return r>s?e==="next"?void 0:s:r;let u;a&&(u=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),u!==void 0&&u>s&&(u=void 0));let l;if(c){let d=new Date(n,o,r).getDay(),m=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(m!==void 0){let h=e==="next"?Ly(d,m):Ly(m,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(u!==void 0&&l!==void 0)return e==="next"?Math.min(u,l):Math.max(u,l);if(u!==void 0)return u;if(l!==void 0)return l}getNextDate(e=new Date){let n=wm(e),o=n.year,r=this.months.findIndex(a=>a>=n.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let c=o+Math.floor((r+a)/this.months.length),u=this.months[(r+a)%this.months.length],l=c===n.year&&u===n.month,d=this.findAllowedDayInMonth("next",c,u,l?n.day:1),m=l&&d===n.day;if(d!==void 0&&m){let h=this.findAllowedTime("next",n);if(h!==void 0)return new Date(c,u,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",c,u,d+1),m=!1}if(d!==void 0&&!m)return new Date(c,u,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,n){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??n),o.push(r);return o}*getNextDatesIterator(e,n){let o;for(;;){if(o=this.getNextDate(e),e=o,n&&n.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let n=wm(e),o=n.year,r=this.reversed.months.findIndex(a=>a<=n.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let c=o-Math.floor((r+a)/this.reversed.months.length),u=this.reversed.months[(r+a)%this.reversed.months.length],l=c===n.year&&u===n.month,d=this.findAllowedDayInMonth("prev",c,u,l?n.day:31),m=l&&d===n.day;if(d!==void 0&&m){let h=this.findAllowedTime("prev",n);if(h!==void 0)return new Date(c,u,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",c,u,d-1),m=!1)}if(d!==void 0&&!m)return new Date(c,u,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,n){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??n),o.push(r);return o}*getPrevDatesIterator(e,n){let o;for(;;){if(o=this.getPrevDate(e),e=o,n&&n.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:n,minute:o,hour:r,day:s,month:a,weekday:c}=wm(e);return this.seconds.indexOf(n)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(c)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(c)!==-1}};var CU={min:0,max:59},IU={min:0,max:59},vU={min:0,max:23},TU={min:1,max:31},PU={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},AU={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},EU={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ii(t,e){let n=new Set;if(t==="*"){for(let d=e.min;d<=e.max;d=d+1)n.add(d);return n}let o=t.split(",");if(o.length>1)return o.forEach(d=>{ii(d,e).forEach(h=>n.add(h))}),n;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let m=parseInt(d,10);if(Number.isNaN(m))throw new Error(`Failed to parse ${t}: ${d} is NaN.`);if(m<e.min||m>e.max)throw new Error(`Failed to parse ${t}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return m},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(t);if(s===null)return n.add(r(t)),n;let a=s[1]==="*"?e.min:r(s[3]),c=s[1]==="*"?e.max:r(s[4]);if(a>c)throw new Error(`Failed to parse ${t}: Invalid range (start: ${a}, end: ${c}).`);let u=s[6],l=1;if(u!==void 0){if(l=parseInt(u,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${u} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${u} to be greater than 0.`)}for(let d=a;d<=c;d=d+l)n.add(d);return n}i(ii,"parseElement");function Ny(t){if(typeof t!="string")throw new TypeError("Invalid cron expression: must be of type string.");t=EU[t.toLowerCase()]??t;let e=t.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let n=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],c=e.length===6?e[5]:e[4];return new Cm({seconds:ii(n,CU),minutes:ii(o,IU),hours:ii(r,vU),days:ii(s,TU),months:new Set(Array.from(ii(a,PU)).map(u=>u-1)),weekdays:new Set(Array.from(ii(c,AU)).map(u=>u%7))})}i(Ny,"parseCronExpression");var qy=class extends ue{static{i(this,"BrownoutInboundPolicy")}static policyType="brownout";crons;constructor(e,n){if(super(e,n),$e(e,n).optional("problem","object"),e.problem&&$e(e.problem,n,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new I(`Value of 'cronSchedule' on policy '${n}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Ny(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Ny(o))}async handler(e,n){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=z.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return z.format(s,e,n)}return e}};var OU="caching",kU=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _U(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(_U,"digestMessage");var xU=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,m]of t.headers.entries())n.includes(d)&&o.push({key:d.toLowerCase(),value:m});o.sort((d,m)=>d.key.localeCompare(m.key));let r=await _U(JSON.stringify(o)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function BP(t,e,n,o){let r=await Ze(o,n),s=await caches.open(r),a=co(t,e,{cacheType:"http",policyType:OU,policyName:o});if(!(n?.cacheHttpMethods?.map(h=>h.toUpperCase())??["GET"]).includes(t.method.toUpperCase()))return Qe(e,{...a,outcome:"skip",reason:"method"}),t;let u=await xU(t,n),l=Date.now(),d=await s.match(u),m=Date.now()-l;return d?(Qe(e,{...a,outcome:"hit",latencyMs:m,statusCode:d.status}),d):(Qe(e,{...a,outcome:"miss",latencyMs:m}),e.addEventListener("responseSent",h=>{try{let g=n.statusCodes??[200,206,301,302,303,404,410],f=h.response.clone();if(!g.includes(f.status)){In(e,{...a,outcome:"not_stored",reason:"status",statusCode:f.status});return}let R=n?.expirationSecondsTtl??60,S=new Response(f.body,f);kU.forEach(v=>S.headers.delete(v)),S.headers.set("cache-control",`s-maxage=${R}`);let w=Date.now();e.waitUntil(s.put(u,S).then(()=>In(e,{...a,outcome:"store",statusCode:f.status,latencyMs:Date.now()-w})).catch(()=>In(e,{...a,outcome:"error",reason:"store-error",statusCode:f.status,latencyMs:Date.now()-w})))}catch(g){e.log.error(`Error in caching-inbound-policy '${o}': "${g.message}"`,g)}}),t)}i(BP,"CachingInboundPolicy");F("caching",BP);var MU=/^[A-Za-z0-9&'^\-$!`#%.+~_|/]+$/,Im=/^[\x21-\x7e]+$/,qs={akamai:{label:"Akamai",targetedHeader:"edge-control",targetedSyntax:"edge-control",readsHeaders:["edge-control"],tagHeader:"edge-cache-tag",tagSeparator:",",maxTagLength:128,maxTags:128,maxTagHeaderBytes:8192,tagPattern:MU,tagCharset:"alphanumerics and & ' ^ - $ ! ` # % . + ~ _ | / (no spaces, commas, colons or brackets)",supportsStaleDirectives:!1},fastly:{label:"Fastly",targetedHeader:"surrogate-control",targetedSyntax:"cache-control",readsHeaders:["surrogate-control"],tagHeader:"surrogate-key",tagSeparator:" ",maxTagLength:1024,maxTags:Number.POSITIVE_INFINITY,maxTagHeaderBytes:16384,tagPattern:Im,tagCharset:"any printable ASCII except spaces",supportsStaleDirectives:!0},cloudflare:{label:"Cloudflare",targetedHeader:"cloudflare-cdn-cache-control",targetedSyntax:"cache-control",readsHeaders:["cloudflare-cdn-cache-control","cdn-cache-control"],tagHeader:"cache-tag",tagSeparator:",",maxTagLength:1024,maxTags:Number.POSITIVE_INFINITY,maxTagHeaderBytes:16384,tagPattern:Im,tagCharset:"any printable ASCII except spaces",supportsStaleDirectives:!0},cloudfront:{label:"CloudFront",targetedHeader:null,targetedSyntax:"cache-control",readsHeaders:[],tagHeader:null,tagSeparator:",",maxTagLength:0,maxTags:0,maxTagHeaderBytes:0,tagPattern:Im,tagCharset:"n/a \u2014 CloudFront has no purge-by-tag support",supportsStaleDirectives:!0},generic:{label:"an RFC 9213 CDN",targetedHeader:"cdn-cache-control",targetedSyntax:"cache-control",readsHeaders:["cdn-cache-control"],tagHeader:null,tagSeparator:",",maxTagLength:0,maxTags:0,maxTagHeaderBytes:0,tagPattern:Im,tagCharset:"n/a \u2014 no purge-tag header is defined for this dialect",supportsStaleDirectives:!0}};function $y(t,e){return e!==void 0?e:qs[t].targetedHeader===null?"s-maxage":"targeted"}i($y,"resolveStrategy");var LU=["no-store","no-cache","private"];function NU(t){let e=new Map;if(!t)return e;for(let n of t.split(",")){let o=n.trim();if(o.length===0)continue;let r=o.indexOf("=");if(r===-1){e.set(o.toLowerCase(),!0);continue}let s=o.slice(0,r).trim().toLowerCase(),a=o.slice(r+1).trim();e.set(s,a.replace(/^"(.*)"$/,"$1"))}return e}i(NU,"parseCacheControl");function qU(t){return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}i(qU,"parseVary");function $U(t,e){let n=new Set,o=[];for(let r of[...t,...e]){let s=r.trim().toLowerCase();if(!(s.length===0||n.has(s))){if(s==="*")return"*";n.add(s),o.push(s)}}return o.join(", ")}i($U,"unionVary");function zU(t,e){let n=t.get(e);if(typeof n!="string")return;let o=Number(n);return Number.isFinite(o)&&o>=0?Math.floor(o):void 0}i(zU,"numericDirective");function DU(t){let e=[[86400,"d"],[3600,"h"],[60,"m"]];for(let[n,o]of e)if(t>=n&&t%n===0)return`${t/n}${o}`;return`${t}s`}i(DU,"formatEdgeControlDuration");function UU(t,e,n){if(t.targetedSyntax==="edge-control"){let r=[`cache-maxage=${DU(e.maxAge)}`];return n&&r.push("!no-store"),r.join(" ")}let o=[`max-age=${e.maxAge}`];return e.staleWhileRevalidate!==void 0&&o.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&o.push(`stale-if-error=${e.staleIfError}`),o.join(", ")}i(UU,"renderEdgeDirectives");function jU(t,e){if(t.visibility==="no-store")return"no-store";let n=[];return t.visibility!==void 0&&n.push(t.visibility),t.maxAge!==void 0&&n.push(`max-age=${t.maxAge}`),t.noCache&&n.push("no-cache"),t.mustRevalidate&&n.push("must-revalidate"),e!==void 0&&(n.push(`s-maxage=${e.maxAge}`),e.staleWhileRevalidate!==void 0&&n.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&n.push(`stale-if-error=${e.staleIfError}`)),n.join(", ")}i(jU,"renderClientCacheControl");var HU=["s-maxage","stale-while-revalidate","stale-if-error"];function FU(t,e){let n=[];for(let o of(t??"").split(",")){let r=o.trim();if(r.length===0)continue;let s=r.split("=")[0].trim().toLowerCase();HU.includes(s)||n.push(r)}return n.push(`s-maxage=${e.maxAge}`),e.staleWhileRevalidate!==void 0&&n.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&n.push(`stale-if-error=${e.staleIfError}`),n.join(", ")}i(FU,"appendEdgeDirectives");function GU(t,e){if(e.has("no-store")||t.visibility==="no-store")return{visibility:"no-store"};let n=zU(e,"max-age"),o={mustRevalidate:t.mustRevalidate===!0||e.has("must-revalidate"),noCache:t.noCache===!0||e.has("no-cache")};e.has("private")||t.visibility==="private"?o.visibility="private":t.visibility!==void 0&&(o.visibility=t.visibility);let r=[t.maxAge,n].filter(s=>s!==void 0);return r.length>0&&(o.maxAge=Math.min(...r)),o}i(GU,"mergeStrictest");function VP(t){let e=qs[t.vendor],n={set:{},remove:[],warnings:[],edgeSuppressed:!1},o=NU(t.upstream.get("cache-control")),r=t.upstream.get("set-cookie")!==null,s=LU.find(m=>o.has(m)),a=t.config.cache===!1,c=t.respectUpstream&&(s!==void 0||r);if(t.vary.length>0){let m=$U(t.vary,qU(t.upstream.get("vary")));m.length>0&&(n.set.vary=m,t.vendor==="akamai"&&!a&&!c&&n.warnings.push("Emitting `Vary` on Akamai suppresses edge caching until Cache ID Modification is configured in Property Manager."))}if(a||c)return c&&n.warnings.push(s!==void 0?`Upstream sent \`cache-control: ${s}\`, so no CDN cache headers were set. Set \`respectUpstream: false\` to override it.`:"Upstream set a cookie on this response, so no CDN cache headers were set. Set `respectUpstream: false` to override it."),n.edgeSuppressed=!0,n.remove.push(...e.readsHeaders),e.tagHeader!==null&&n.remove.push(e.tagHeader),a&&t.clientMode!=="preserve"&&(n.set["cache-control"]="no-store"),n;let u=t.config.edge;if(t.clientMode!=="preserve"){let m=t.config.client??{},h=t.clientMode==="strictest"?GU(m,o):m,g=t.strategy==="s-maxage"?u:void 0;g!==void 0&&h.visibility==="no-store"&&n.warnings.push('The client policy resolved to `no-store`, which cannot carry an `s-maxage`, so the configured edge TTL was not emitted. Remove `client.visibility: "no-store"`, or set `cache: false` if the response is genuinely uncacheable.');let f=jU(h,g);f.length>0?n.set["cache-control"]=f:t.clientMode==="replace"&&n.remove.push("cache-control")}else t.strategy==="s-maxage"&&u!==void 0&&(n.set["cache-control"]=FU(t.upstream.get("cache-control"),u));let l=u!==void 0&&t.strategy==="targeted"?e.targetedHeader:null;n.remove.push(...e.readsHeaders.filter(m=>m!==l)),u===void 0?n.warnings.push("No edge `maxAge` was resolved from the options or the cacheConfig function, so no CDN cache header was set."):t.strategy==="targeted"&&(e.targetedHeader===null?n.warnings.push(`${e.label} reads no targeted cache header, so the edge TTL was not emitted. Use \`strategy: "s-maxage"\`.`):(!e.supportsStaleDirectives&&(u.staleWhileRevalidate!==void 0||u.staleIfError!==void 0)&&n.warnings.push(`${e.label}'s \`${e.targetedHeader}\` header cannot express \`stale-while-revalidate\` or \`stale-if-error\`, so the cacheConfig function's stale window was not emitted. Configure stale serving in Property Manager, or set \`strategy: "s-maxage"\` to emit it on \`Cache-Control\` instead.`),n.set[e.targetedHeader]=UU(e,u,!t.respectUpstream)));let d=t.config.tags??[];if(d.length>0&&e.tagHeader===null&&n.warnings.push(`${e.label} has no purge-by-tag support, so ${d.length} tag(s) were not emitted.`),e.tagHeader!==null){let{accepted:m,errors:h}=JP(e,d);n.warnings.push(...h),m.length>0?n.set[e.tagHeader]=m.join(e.tagSeparator):n.remove.push(e.tagHeader)}return n}i(VP,"buildCdnCacheControlPlan");function JP(t,e){let n=[],o=[],r=new TextEncoder,s=0;for(let a of e){if(a.length===0)continue;if(a.length>t.maxTagLength){o.push(`Cache tag "${a}" is ${a.length} characters; ${t.label} allows ${t.maxTagLength}. Shorten the tag \u2014 an over-long tag is silently dropped at the edge.`);continue}if(!t.tagPattern.test(a)||a.includes(t.tagSeparator)){o.push(`Cache tag "${a}" contains characters ${t.label} does not accept. ${t.label} allows ${t.tagCharset}, and never the separator ("${t.tagSeparator}"). Alphanumerics, dashes and underscores are accepted by every CDN, so prefer those if you may switch.`);continue}if(n.length>=t.maxTags){o.push(`More than ${t.maxTags} cache tags for ${t.label}; "${a}" and any after it were dropped.`);break}let c=r.encode(a).length+(n.length>0?1:0);if(s+c>t.maxTagHeaderBytes){o.push(`Cache tag header exceeds ${t.maxTagHeaderBytes} bytes for ${t.label}; "${a}" and any after it were dropped.`);break}s+=c,n.push(a)}return{accepted:n,errors:o}}i(JP,"selectValidTags");function KP(t){let e=qs[t.vendor],n=[];if(t.edge===void 0&&!t.hasCacheConfigFunction&&n.push("options.edge is required unless options.cacheConfig supplies the policy at runtime. Add `edge: { maxAge: <seconds> }`, which is the TTL the CDN may serve this response for."),t.strategy==="targeted"&&e.targetedHeader===null&&n.push(`options.strategy is "targeted" but ${e.label} reads no targeted cache header \u2014 only \`Cache-Control: s-maxage\`. Set \`strategy: "s-maxage"\`.`),t.strategy==="targeted"&&!e.supportsStaleDirectives&&t.edge!==void 0&&(t.edge.staleWhileRevalidate!==void 0||t.edge.staleIfError!==void 0)&&n.push(`${e.label}'s \`${e.targetedHeader}\` header cannot express \`stale-while-revalidate\` or \`stale-if-error\`. Configure stale serving in Property Manager and remove these options, or set \`strategy: "s-maxage"\` to emit them on \`Cache-Control\` instead.`),t.tags.length>0&&e.tagHeader===null&&n.push(t.vendor==="cloudfront"?"options.tags is set but CloudFront has no purge-by-tag support. Remove the tags and invalidate by path instead.":`options.tags is set but no purge-tag header is defined for ${e.label}. Remove the tags, or set \`cdn\` to the CDN actually in front of this gateway.`),t.tags.length>0&&e.tagHeader!==null){let{errors:o}=JP(e,t.tags);n.push(...o)}return n}i(KP,"validateStaticConfig");var WP=new WeakMap;function vm(t,e){return typeof t=="string"&&Object.hasOwn(e,t)}i(vm,"isOneOf");var YP={targeted:!0,"s-maxage":!0},QP={strictest:!0,replace:!0,preserve:!0},Tm={public:!0,private:!0,"no-store":!0};function $s(t){return Number.isSafeInteger(t)&&t>=0}i($s,"isSeconds");function Pm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(Pm,"isConfigObject");function XP(t){if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(typeof t[e]!="string")return!1;return!0}i(XP,"isStringArray");function ZU(t){let e=[],n=t;if(n.strategy!==void 0&&!vm(n.strategy,YP)&&e.push(`options.strategy must be one of ${Object.keys(YP).join(", ")}. An unrecognised value matches no branch, so no edge cache header is emitted at all.`),n.client!==void 0)if(!Pm(n.client))e.push("options.client must be an object.");else{let o=n.client;o.maxAge!==void 0&&!$s(o.maxAge)&&e.push("options.client.maxAge must be a non-negative whole number of seconds."),o.mode!==void 0&&!vm(o.mode,QP)&&e.push(`options.client.mode must be one of ${Object.keys(QP).join(", ")}. An unrecognised value falls through to \`replace\`, the least restrictive mode \u2014 a typo here would silently stop the policy honouring an upstream \`private\`.`);for(let r of["mustRevalidate","noCache"])o[r]!==void 0&&typeof o[r]!="boolean"&&e.push(`options.client.${r} must be a boolean. A truthy non-boolean such as the string "false" would add the directive rather than omit it.`);o.visibility!==void 0&&!vm(o.visibility,Tm)&&e.push(`options.client.visibility must be one of ${Object.keys(Tm).join(", ")}. An unrecognised value is dropped, so no visibility directive is sent.`)}if(n.edge!==void 0)if(!Pm(n.edge))e.push("options.edge must be an object, e.g. `{ maxAge: 1800 }`.");else{let o=n.edge;$s(o.maxAge)||e.push("options.edge.maxAge must be a non-negative whole number of seconds. Anything else renders as `max-age=undefined`/`max-age=NaN`, which a CDN discards \u2014 disabling the caching you configured.");for(let r of["staleWhileRevalidate","staleIfError"])o[r]!==void 0&&!$s(o[r])&&e.push(`options.edge.${r} must be a non-negative whole number of seconds.`)}for(let o of["tags","vary"])n[o]!==void 0&&!XP(n[o])&&e.push(`options.${o} must be an array of strings. A bare string is iterated character by character.`);return n.respectUpstream!==void 0&&typeof n.respectUpstream!="boolean"&&e.push("options.respectUpstream must be a boolean."),e}i(ZU,"collectShapeErrors");function BU(t,e){if(typeof t!="object"||t===null)throw new I(`CdnCacheControlOutboundPolicy '${e}' - options must be an object. See the policy documentation for the supported fields.`);if(WP.has(t))return;let n=t.cdn;if(typeof n!="string"||!Object.hasOwn(qs,n))throw new I(`CdnCacheControlOutboundPolicy '${e}' - options.cdn is required and must be one of ${Object.keys(qs).join(", ")}. It has no default because each CDN reads a different header for shared-cache TTL and purge tags, so a wrong guess fails silently; use "generic" for an RFC 9213 CDN that is not listed.`);let o=ZU(t);if(o.length===0&&o.push(...KP({vendor:t.cdn,strategy:$y(t.cdn,t.strategy),edge:t.edge,tags:t.tags??[],hasCacheConfigFunction:eA(t.cacheConfig)})),o.length>0)throw new I(`Invalid options on \`cdn-cache-control-outbound\` policy "${e}". Validation failed:
334
334
  ${o.map(r=>` - ${r}`).join(`
335
335
  `)}`);WP.set(t,void 0)}i(BU,"assertValidOptions");function eA(t){return t!=null}i(eA,"hasCacheConfig");function VU(t,e){if(!eA(t.cacheConfig))return;let n=t.cacheConfig;if(!n.module||typeof n.module!="object")throw new I(`CdnCacheControlOutboundPolicy '${e}' - options.cacheConfig.module must be a module reference in the format \`$import(./modules/my-module)\`.`);if(!n.export)throw new I(`CdnCacheControlOutboundPolicy '${e}' - options.cacheConfig.export must name the export holding your cache config function, for example \`default\`.`);let o=n.module[n.export];if(typeof o!="function")throw new I(`CdnCacheControlOutboundPolicy '${e}' - options.cacheConfig.module has no function exported as '${n.export}'. Check the export name.`);return o}i(VU,"loadConfigFunction");function JU(t,e){if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function must return an object or undefined, got ${Array.isArray(t)?"an array":typeof t}.`);let n=t,o={};if(n.cache!==void 0&&typeof n.cache!="boolean")throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a \`cache\` that is not a boolean. Return \`{ cache: false }\` to skip caching this response.`);if(n.cache===!1)return{cache:!1};if(n.edge!==void 0){if(!Pm(n.edge))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a non-object \`edge\`. Return \`{ edge: { maxAge: <seconds> } }\`.`);let r=n.edge;for(let s of["staleWhileRevalidate","staleIfError"])if(r[s]!==void 0&&!$s(r[s]))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned an \`edge.${s}\` that is not a non-negative whole number of seconds.`);if(!$s(r.maxAge))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned an \`edge.maxAge\` that is not a non-negative whole number of seconds. Round any computed value: \`Math.floor(ttl)\`. Return nothing to fall back to the configured options, or \`{ cache: false }\` to skip caching.`);o.edge={maxAge:r.maxAge,staleWhileRevalidate:r.staleWhileRevalidate,staleIfError:r.staleIfError}}if(n.client!==void 0){if(!Pm(n.client))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a \`client\` that is not an object. Return \`{ client: { maxAge: <seconds>, visibility: "public" } }\`.`);let r=n.client;if(r.maxAge!==void 0&&!$s(r.maxAge))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a \`client.maxAge\` that is not a non-negative whole number of seconds.`);if(r.visibility!==void 0&&!vm(r.visibility,Tm))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a \`client.visibility\` of ${JSON.stringify(r.visibility)}. Use one of ${Object.keys(Tm).join(", ")}.`);for(let s of["mustRevalidate","noCache"])if(r[s]!==void 0&&typeof r[s]!="boolean")throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned a \`client.${s}\` that is not a boolean.`);o.client={maxAge:r.maxAge,visibility:r.visibility,mustRevalidate:r.mustRevalidate,noCache:r.noCache}}if(n.tags!==void 0){if(!XP(n.tags))throw new U(`CdnCacheControlOutboundPolicy '${e}' - the cacheConfig function returned \`tags\` that is not an array of strings.`);o.tags=n.tags}return o}i(JU,"validateReturnedConfig");var tA=i(async(t,e,n,o,r)=>{BU(o,r);let s=VU(o,r),a={edge:o.edge,client:o.client,tags:o.tags??[]},c=a;if(s){let d=await s(t,e,n);if(t.bodyUsed||t.body?.locked===!0)throw new U(`CdnCacheControlOutboundPolicy '${r}' - the cacheConfig function consumed the response body, so the response can no longer be sent. Call \`response.clone()\` before reading it, e.g. \`const body = await response.clone().json()\`. Reading a header such as \`x-result-count\` avoids buffering the body at all.`);c=JU(d,r)??a}let u=VP({vendor:o.cdn,strategy:$y(o.cdn,o.strategy),clientMode:o.client?.mode??"strictest",respectUpstream:o.respectUpstream??!0,vary:o.vary??[],config:c,upstream:t.headers});for(let d of u.warnings)n.log.warn(`CdnCacheControlOutboundPolicy '${r}': ${d}`);let l=new Headers(t.headers);for(let d of u.remove)l.delete(d);for(let[d,m]of Object.entries(u.set))l.set(d,m);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:l})},"CdnCacheControlOutboundPolicy");et("cdn-cache-control",tA);var nA=i(async(t,e,n,o)=>{if(!n.method)throw new I(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new Le(t,{method:n.method})},"ChangeMethodInboundPolicy");F("change-method",nA);var oA=i(async(t,e,n)=>{let o=[...n.exclude??[]],r=new Headers;return o.forEach(a=>{let c=t.headers.get(a);c&&r.set(a,c)}),new Le(t,{headers:r})},"ClearHeadersInboundPolicy");F("clear-headers",oA);var rA=i(async(t,e,n,o)=>{let r=[...o.exclude??[]],s=new Headers;return r.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");et("clear-headers",rA);var iA=i(async(t,e,n,o)=>{let r=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",Jt(t,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,oAuthResourceMetadataEnabled:n.oAuthResourceMetadataEnabled},o)},"ClerkJwtInboundPolicy");F("clerk-jwt-auth",iA);var sA=i(async(t,e,n,o)=>{if(!n.userPoolId)throw new I("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new I("region must be set in the options for CognitoJwtInboundPolicy");return Jt(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,oAuthResourceMetadataEnabled:n.oAuthResourceMetadataEnabled},o)},"CognitoJwtInboundPolicy");F("cognito-jwt-auth",sA);var Gt=[];for(let t=0;t<256;++t)Gt.push((t+256).toString(16).slice(1));function aA(t,e=0){return(Gt[t[e+0]]+Gt[t[e+1]]+Gt[t[e+2]]+Gt[t[e+3]]+"-"+Gt[t[e+4]]+Gt[t[e+5]]+"-"+Gt[t[e+6]]+Gt[t[e+7]]+"-"+Gt[t[e+8]]+Gt[t[e+9]]+"-"+Gt[t[e+10]]+Gt[t[e+11]]+Gt[t[e+12]]+Gt[t[e+13]]+Gt[t[e+14]]+Gt[t[e+15]]).toLowerCase()}i(aA,"unsafeStringify");var zy,KU=new Uint8Array(16);function Am(){if(!zy){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");zy=crypto.getRandomValues.bind(crypto)}return zy(KU)}i(Am,"rng");var Dy={};function WU(t,e,n){let o;if(t)o=cA(t.random??t.rng?.()??Am(),t.msecs,t.seq,e,n);else{let r=Date.now(),s=Am();YU(Dy,r,s),o=cA(s,Dy.msecs,Dy.seq,e,n)}return e??aA(o)}i(WU,"v7");function YU(t,e,n){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}i(YU,"updateV7State");function cA(t,e,n,o,r=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!o)o=new Uint8Array(16),r=0;else if(r<0||r+16>o.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);return e??=Date.now(),n??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],o[r++]=e/1099511627776&255,o[r++]=e/4294967296&255,o[r++]=e/16777216&255,o[r++]=e/65536&255,o[r++]=e/256&255,o[r++]=e&255,o[r++]=112|n>>>28&15,o[r++]=n>>>20&255,o[r++]=128|n>>>14&63,o[r++]=n>>>6&255,o[r++]=n<<2&255|t[10]&3,o[r++]=t[11],o[r++]=t[12],o[r++]=t[13],o[r++]=t[14],o[r++]=t[15],o}i(cA,"v7Bytes");var si=WU;function uA(t,e,n,o,r){return r==="anthropic-messages"?pr(async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)}):r==="openai-responses"?Ao(async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)}):Po(t,async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)})}i(uA,"createOpikStreamingAccumulator");var zs=Ye("zuplo:policies:CometOpikTracingPolicy"),dA=Symbol("comet-opik-tracing");function QU(t,e){ce.set(t,dA,e)}i(QU,"setTracingContext");function XU(t){return ce.get(t,dA)}i(XU,"getTracingContext");async function ej(t,e,n){let o=n.baseUrl||"https://www.comet.com/opik/api",r=n.workspace,s=new Date().toISOString(),a=si(),c={id:a,project_name:n.projectName,name:"AI Gateway Request",start_time:s,input:t,metadata:{request_id:e.requestId,route:e.route.path},tags:["zuplo-ai-gateway"]};try{let u={"Content-Type":"application/json","Comet-Workspace":r};n.apiKey&&(u.authorization=n.apiKey);let l=await j.fetch(`${o}/v1/private/traces/batch`,{method:"POST",headers:u,body:JSON.stringify({traces:[c]})});if(!l.ok){let d=await l.text();zs("Failed to create Opik trace:",l.status,d);return}return zs("Created Opik trace with ID:",a),a}catch(u){zs("Error creating Opik trace:",u);return}}i(ej,"createTrace");async function lA(t,e,n,o,r,s){let a=s.baseUrl||"https://www.comet.com/opik/api",c=s.workspace,u=new Date().toISOString(),l=si(),d,m=n;if(m?.usage&&typeof m.usage=="object"){let f=m.usage,R=typeof f.input_tokens=="number"?f.input_tokens:typeof f.prompt_tokens=="number"?f.prompt_tokens:void 0,S=typeof f.output_tokens=="number"?f.output_tokens:typeof f.completion_tokens=="number"?f.completion_tokens:void 0;d={prompt_tokens:R,completion_tokens:S,total_tokens:typeof f.total_tokens=="number"?f.total_tokens:void 0}}let h="";m?.output&&Array.isArray(m.output)?h=m.output.map(f=>{let S=f.content;return S&&Array.isArray(S)?S.map(w=>w.text).filter(w=>typeof w=="string").join(" "):""}).filter(f=>typeof f=="string"&&f.length>0).join(" "):m?.choices&&Array.isArray(m.choices)?h=m.choices.map(f=>f.message?.content).filter(f=>typeof f=="string").join(" "):Array.isArray(m?.content)&&(h=mt(m.content));let g={id:l,trace_id:t,project_name:s.projectName,name:"LLM API Call",type:"llm",start_time:o,end_time:u,model:e?.model,provider:"ai-gateway",usage:d,input:e?.messages?{messages:e.messages}:e?.input?{input:e.input}:{},output:{content:h},metadata:{request_id:r.requestId,temperature:e?.temperature,max_tokens:e?.max_tokens},tags:["llm-call","ai-gateway"]};try{let f={"Content-Type":"application/json","Comet-Workspace":c};s.apiKey&&(f.authorization=s.apiKey);let R={spans:[g]},S=await j.fetch(`${a}/v1/private/spans/batch`,{method:"POST",headers:f,body:JSON.stringify(R)});if(S.ok)zs("Created Opik span for trace:",t);else{let w=await S.text();zs("Failed to create Opik span:",S.status,w)}}catch(f){zs("Error creating Opik span:",f)}}i(lA,"createSpan");async function pA(t,e,n,o){let r=t.user,s=r?.configuration?.policies?.["comet-opik-tracing"];if(!s?.enabled)return t;let a=Ot(t);if(a===null)return t;let c={apiKey:s.apiKey,projectName:s.projectName,workspace:s.workspace,baseUrl:s.baseUrl},l=r?.configuration?.models?.completions?.[0]?.model,d,m,h=!1;try{d=await t.clone().json(),h=d?.stream===!0,a==="openai-responses"&&d?.input?m={input:d.input,model:l||d.model,temperature:d.temperature}:d?.messages&&(m={messages:d.messages.map(f=>({role:f.role,content:mt(f.content)})),model:l||d.model,temperature:d.temperature,max_tokens:d.max_tokens})}catch{e.log.error("Could not parse request body for Opik tracing")}if(m){let g=new Date().toISOString(),f=await ej(m,e,c);f&&(QU(e,{traceId:f,startTime:g,input:m}),e.addResponseSendingFinalHook(async S=>{let w=XU(e);if(w?.traceId)if(h&&S.body)try{let v=S.clone(),T=uA(e,w,c,lA,a);v.body&&e.waitUntil(v.body.pipeThrough(T).pipeTo(new WritableStream({write(){},close(){},abort(P){e.log.error(P,"Opik streaming accumulation aborted")}})).catch(P=>{e.log.error(P,"Error in Opik streaming accumulation")}))}catch(v){e.log.debug(v,"Could not observe streaming response for Opik tracing")}else{let v;try{v=await S.clone().json()}catch{e.log.error("Could not parse response body for Opik tracing")}e.waitUntil(lA(w.traceId,w.input,v,w.startTime,e,c))}}))}return t}i(pA,"CometOpikTracingInboundPolicy");F("comet-opik-tracing",pA);function mA(t,e,n,o,r){return r==="anthropic-messages"?pr(async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)}):r==="openai-responses"?Ao(async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)}):Po(t,async s=>{e.traceId&&await o(e.traceId,e.input,s,e.startTime,t,n)})}i(mA,"createOpikStreamingAccumulator");var Ds=Ye("zuplo:policies:CometOpikTracingPolicy");async function tj(t,e,n){let o=n.baseUrl||"https://www.comet.com/opik/api",r=n.workspace,s=new Date().toISOString(),a=si(),c={id:a,project_name:n.projectName,name:"AI Gateway Request",start_time:s,input:t,metadata:{request_id:e.requestId,route:e.route.path},tags:["zuplo-ai-gateway"]};try{let u={"Content-Type":"application/json","Comet-Workspace":r};n.apiKey&&(u.authorization=n.apiKey);let l=await j.fetch(`${o}/v1/private/traces/batch`,{method:"POST",headers:u,body:JSON.stringify({traces:[c]})});if(!l.ok){let d=await l.text();Ds("Failed to create Opik trace:",l.status,d);return}return Ds("Created Opik trace with ID:",a),a}catch(u){Ds("Error creating Opik trace:",u);return}}i(tj,"createTrace");async function hA(t,e,n,o,r,s){let a=s.baseUrl||"https://www.comet.com/opik/api",c=s.workspace,u=new Date().toISOString(),l=si(),d,m=n;if(m?.usage&&typeof m.usage=="object"){let f=m.usage,R=typeof f.input_tokens=="number"?f.input_tokens:typeof f.prompt_tokens=="number"?f.prompt_tokens:void 0,S=typeof f.output_tokens=="number"?f.output_tokens:typeof f.completion_tokens=="number"?f.completion_tokens:void 0;d={prompt_tokens:R,completion_tokens:S,total_tokens:typeof f.total_tokens=="number"?f.total_tokens:void 0}}let h="";m?.output&&Array.isArray(m.output)?h=m.output.map(f=>{let S=f.content;return S&&Array.isArray(S)?S.map(w=>w.text).filter(w=>typeof w=="string").join(" "):""}).filter(f=>typeof f=="string"&&f.length>0).join(" "):m?.choices&&Array.isArray(m.choices)?h=m.choices.map(f=>f.message?.content).filter(f=>typeof f=="string").join(" "):Array.isArray(m?.content)&&(h=mt(m.content));let g={id:l,trace_id:t,project_name:s.projectName,name:"LLM API Call",type:"llm",start_time:o,end_time:u,model:e?.model,provider:"ai-gateway",usage:d,input:e?.messages?{messages:e.messages}:e?.input?{input:e.input}:{},output:{content:h},metadata:{request_id:r.requestId,temperature:e?.temperature,max_tokens:e?.max_tokens},tags:["llm-call","ai-gateway"]};try{let f={"Content-Type":"application/json","Comet-Workspace":c};s.apiKey&&(f.authorization=s.apiKey);let R={spans:[g]},S=await j.fetch(`${a}/v1/private/spans/batch`,{method:"POST",headers:f,body:JSON.stringify(R)});if(S.ok)Ds("Created Opik span for trace:",t);else{let w=await S.text();Ds("Failed to create Opik span:",S.status,w)}}catch(f){Ds("Error creating Opik span:",f)}}i(hA,"createSpan");async function fA(t,e,n,o){let r=n,s=Ot(t);if(s!==null&&r.endpoints&&!r.endpoints.includes(s))return t;if(s===null)return(r.onUnknownShape??"skip")==="deny"?new Response(JSON.stringify({error:{message:"Tracing policy denied an uninspectable shape."}}),{status:400,headers:{"Content-Type":"application/json"}}):t;let a={apiKey:n.apiKey,projectName:n.projectName,workspace:n.workspace,baseUrl:n.baseUrl},l=Ke.get(e)?.models?.completions?.[0]?.model,d,m,h=!1;try{d=await t.clone().json(),h=d?.stream===!0,d?.messages?m={messages:d.messages.map(f=>({role:f.role,content:mt(f.content)})),model:l||d.model,temperature:d.temperature,max_tokens:d.max_tokens}:d?.input&&(m={input:d.input,model:l||d.model,temperature:d.temperature})}catch{e.log.error("Could not parse request body for Opik tracing")}if(m){let g=new Date().toISOString(),f=await tj(m,e,a);if(f){let R={traceId:f,startTime:g,input:m};e.addResponseSendingFinalHook(async S=>{if(h&&S.body)try{let w=S.clone(),v=mA(e,R,a,hA,s);w.body&&e.waitUntil(w.body.pipeThrough(v).pipeTo(new WritableStream({write(){},close(){},abort(T){e.log.error(T,"Opik streaming accumulation aborted")}})).catch(T=>{e.log.error(T,"Error in Opik streaming accumulation")}))}catch(w){e.log.debug(w,"Could not observe streaming response for Opik tracing")}else{let w;try{w=await S.clone().json()}catch{e.log.error("Could not parse response body for Opik tracing")}e.waitUntil(hA(f,R.input,w,R.startTime,e,a))}})}}return t}i(fA,"CometOpikTracingV2InboundPolicy");F("comet-opik-tracing-v2",fA);var Em=class extends Error{static{i(this,"ValidationError")}},Uy=class extends Em{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},jy=class extends Em{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function nj(t,e){if(bw(t))throw new Uy(e)}i(nj,"throwIfUndefinedOrNull");function gA(t,e){if(nj(t,e),!Qn(t))throw new jy(e,"string")}i(gA,"throwIfNotString");var oj=250,Hy=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,n){let r=Math.floor(n*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let c=this.keyValueStore.get(e);return Promise.resolve({count:c.value,ttlSeconds:Math.round((c.expiresAt-Date.now())/1e3)})}multiIncrement(e,n){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,n){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,n,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,n){throw new Error("In memory quotas are not currently supported.")}},Fy=class{constructor(e,n=O.instance.rateLimitServiceTimeoutMs,o){this.clientUrl=e;this.timeoutMs=n;this.logger=o;this.logger.debug(`Rate limit client timeout set to ${this.timeoutMs}ms`)}clientUrl;timeoutMs;logger;static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:n,method:o,requestId:r}){gA(e,"url");let s=new Headers({"content-type":"application/json"});nt(s,r);let a=new AbortController,c=setTimeout(()=>{a.abort()},this.timeoutMs),u;try{u=await j.fetch(`${this.clientUrl}${e}`,{method:o,body:n,signal:a.signal,headers:s})}catch(d){if(d instanceof Error&&d.name==="AbortError"){let m=this.timeoutMs;throw this.timeoutMs+=oj,this.logger.warn({previousRateLimitClientTimeout:m,newRateLimitClientTimeout:this.timeoutMs,requestId:r},`Rate limit client timed out after ${m}ms. Increasing rate limit client timeout from ${m}ms to ${this.timeoutMs}ms.`),new De("Rate limiting client timed out",{cause:d})}throw new De("Could not fetch rate limiting client",{cause:d})}finally{clearTimeout(c)}let l=u.headers.get("Content-Type")?.includes("application/json")?await u.json():await u.text();if(u.ok)return l;throw u.status===401?new De("Rate limiting service failed with 401: Unauthorized"):new De(`Rate limiting service failed with (${u.status})`)}async multiCount(e,n){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:n})).data}async multiIncrement(e,n){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:n})).data}async getCountAndUpdateExpiry(e,n,o){let r=Math.floor(n*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,n){let o=await Ta(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:n})}async setQuota(e,n,o){let r=await Ta(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(n),requestId:o})}},Us;function mr(t,e,n){let{redisURL:o,authApiJWT:r}=O.instance;if(Us)return Us;if(!r)return e.info("Using in-memory rate limit client for local development."),Us=new Hy,Us;if(!Qn(o))throw new De(`RateLimitClient used in policy '${t}' - rate limit service not configured`);if(!Qn(r))throw new De(`RateLimitClient used in policy '${t}' - rate limit service not configured`);return Us=new Fy(o,n?.timeoutMs,e),Us}i(mr,"getRateLimitClient");var rj=i(t=>t.incomingRequestProperties.ip??"127.0.0.1","getRealIP");function js(t,e){return{function:cj(e,"RateLimitInboundPolicy",t),user:sj,ip:ij,all:aj}[e.rateLimitBy??"ip"]}i(js,"getRateLimitByFunctions");var ij=i(async(t,e)=>({key:`ip-${rj(e)}`}),"getIP"),sj=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),aj=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function cj(t,e,n){let o;if(t.rateLimitBy==="function"){if(!t.identifier)throw new I(`${e} '${n}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module||typeof t.identifier.module!="object")throw new I(`${e} '${n}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new I(`${e} '${n}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=t.identifier.module[t.identifier.export],!o||typeof o!="function")throw new I(`${e} '${n}' - Custom rate limit function must be a valid function`)}return i(async(s,a,c)=>{let u=await o(s,a,c);if(u==null)return null;if(typeof u!="object"){let l=`${e} '${c}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new U(l)}if(!("key"in u)){let l=`${e} '${c}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,u),new U(l)}if(typeof u.key!="string"){let l=`${e} '${c}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof u.key}'`;throw a.log.error(l),new U(l)}return u},"outerFunction")}i(cj,"wrapUserFunction");var Hs="Retry-After";var yA=Ye("zuplo:policies:ComplexRateLimitInboundPolicy"),Gy=Symbol("complex-rate-limit-counters"),Zy=class t extends ue{static{i(this,"ComplexRateLimitInboundPolicy")}static policyType="complex-rate-limit";static setIncrements(e,n){let o=ce.get(e,Gy)??{};Object.assign(o,n),ce.set(e,Gy,o)}static getIncrements(e){return ce.get(e,Gy)??{}}constructor(e,n){super(e,n),$e(e,n).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&$e(e.identifier,n,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new I(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,n){let o=Date.now(),r=W.getLogger(n),s=mr(this.policyName,r),a=i((u,l)=>{if(this.options.throwOnFailure)throw new De(u,{cause:l});r.error(u,l)},"throwOrLog"),c=i((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[Hs]=l.toString()),z.tooManyRequests(e,n,void 0,d)},"rateLimited");try{let l=await js(this.policyName,this.options)(e,n,this.policyName);if(l==null)return e;let d=O.instance.isTestMode||O.instance.isWorkingCopy?O.instance.build.BUILD_ID:"",m=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;n.addResponseSendingFinalHook(async()=>{try{let S=t.getIncrements(n);yA(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let w=Object.entries(m).map(([T])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${T}`,ttlSeconds:h,increment:S[T]??0})),v=s.multiIncrement(w,n.requestId);n.waitUntil(v),await v}catch(S){a(S.message,S)}});let g=Object.entries(m).map(([S,w])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:h,limit:w})),f=await s.multiCount(g,n.requestId);return uj(f,g).length>0?c(this.options.headerMode??"retry-after",h):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-o;yA(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${u}ms`)}}};function uj(t,e){let n=[];for(let o of t){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&n.push(o)}return n}i(uj,"findOverLimits");var bA=i(async(t,e,n,o)=>{if(!n.policies||n.policies.length===0)throw new I(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=Xe.instance,s=ki(n.policies,r?.routeData.policies);return Da(s)(t,e)},"CompositeInboundPolicy");F("composite",bA);var SA=i(async(t,e,n,o,r)=>{if(!o.policies||o.policies.length===0)throw new I(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=Xe.instance,a=za(o.policies,s?.routeData.policies);return Fh(a)(t,e,n)},"CompositeOutboundPolicy");et("composite",SA);var RA=i(async(t,e,n,o)=>{let r=t.headers.get("Authorization");if(!r)return z.unauthorized(t,e,{detail:"No authorization header"});let s=lj(r);if(!s)return z.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Ze(o,n),c=new Ve(a,e),u=await c.get(s);if(!u){let l=await j.fetch(n.introspectionUrl,{headers:{Authorization:`Basic ${btoa(`${n.clientId}:${n.clientSecret}`)}`,Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:`token=${s}&token_type_hint=access_token`}),d=await l.text();if(l.status===200)u=d,c.put(s,u,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),z.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):z.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");function lj(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(lj,"getToken");F("curity-phantom-token-auth",RA);function un(t){return t.replace(/\D/g,"")}i(un,"digitsOf");function Om(t){let e=un(t);if(e.length===0)return!1;let n=0,o=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;if(s<0||s>9)return!1;o&&(s*=2,s>9&&(s-=9)),n+=s,o=!o}return n%10===0}i(Om,"luhnDigits");function km(t){let e=un(t);return e.length<13||e.length>19?!1:Om(e)}i(km,"luhn");function By(t){let e=un(t);if(e.length!==9||/^(\d)\1{8}$/.test(e))return!1;let n=e.slice(0,3),o=e.slice(3,5),r=e.slice(5);return!(n==="000"||n==="666"||n.startsWith("9")||o==="00"||r==="0000")}i(By,"usSsnStructure");var dj={AD:24,AE:23,AL:28,AT:20,AZ:28,BA:20,BE:16,BG:22,BH:22,BI:27,BR:29,BY:28,CH:21,CR:22,CY:28,CZ:24,DE:22,DJ:27,DK:18,DO:28,EE:20,EG:29,ES:24,FI:18,FK:18,FO:18,FR:27,GB:22,GE:22,GI:23,GL:18,GR:27,GT:28,HR:21,HU:28,IE:22,IL:23,IQ:23,IS:26,IT:27,JO:30,KW:30,KZ:20,LB:28,LC:32,LI:21,LT:20,LU:20,LV:21,LY:25,MC:27,MD:24,ME:22,MK:19,MN:20,MR:27,MT:31,MU:30,NI:28,NL:18,NO:15,OM:23,PK:24,PL:28,PS:29,PT:25,QA:29,RO:24,RS:22,RU:33,SA:24,SC:31,SD:18,SE:24,SI:19,SK:24,SM:27,SO:23,ST:25,SV:28,TL:23,TN:24,TR:26,UA:29,VA:22,VG:24,XK:20};function Vy(t){let e=t.replace(/[\s-]/g,"").toUpperCase(),n=e.slice(0,2),o=dj[n];if(!o||e.length!==o||!/^[A-Z]{2}\d{2}[A-Z0-9]+$/.test(e))return!1;let r=e.slice(4)+e.slice(0,4),s=0;for(let a of r){let c=a.charCodeAt(0),u=c>=65?String(c-55):a;for(let l of u)s=(s*10+(l.charCodeAt(0)-48))%97}return s===1}i(Vy,"ibanChecksum");function Jy(t){let e=un(t);if(e.length!==9)return!1;let n=[3,7,1,3,7,1,3,7,1],o=0;for(let r=0;r<9;r++)o+=(e.charCodeAt(r)-48)*n[r];return o%10===0}i(Jy,"abaChecksum");function Ky(t){let e=un(t);if(e.length!==10)return!1;let n=0;for(let o=0;o<10;o++)n+=(e.charCodeAt(o)-48)*(10-o);return n%11===0}i(Ky,"nhsChecksum");function Wy(t){let e=un(t);if(e.length!==9)return!1;let n=[1,4,3,7,5,8,6,9,10],o=0;for(let r=0;r<9;r++)o+=(e.charCodeAt(r)-48)*n[r];return o%11===0}i(Wy,"tfnChecksum");function Yy(t){let e=un(t);if(e.length!==11||e.startsWith("0"))return!1;let n=[10,1,3,5,7,9,11,13,15,17,19],o=0;for(let r=0;r<11;r++){let s=e.charCodeAt(r)-48;r===0&&(s-=1),o+=s*n[r]}return o%89===0}i(Yy,"abnChecksum");function Qy(t){let e=un(t);if(e.length!==9)return!1;let n=0;for(let o=0;o<8;o++)n+=(e.charCodeAt(o)-48)*(8-o);return(10-n%10)%10===e.charCodeAt(8)-48}i(Qy,"acnChecksum");function Xy(t){let e=un(t);if(e.length<10||e.length>11)return!1;let n=e.charCodeAt(0)-48;if(n<2||n>6)return!1;let o=[1,3,7,9,1,3,7,9],r=0;for(let s=0;s<8;s++)r+=(e.charCodeAt(s)-48)*o[s];return r%10===e.charCodeAt(8)-48}i(Xy,"medicareChecksum");var pj=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],mj=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]];function wA(t){let e=un(t);if(e.length===0)return!1;let n=0;for(let o=0;o<e.length;o++){let r=e.charCodeAt(e.length-1-o)-48;n=pj[n][mj[o%8][r]]}return n===0}i(wA,"verhoeffChecksum");function eb(t){let e=un(t);return e.length!==12||e.charCodeAt(0)-48<2||e===e.split("").reverse().join("")?!1:wA(e)}i(eb,"aadhaarChecksum");var hj="JZIHGFEDCBA",fj="XWUTRQPNMLK",gj="XWUTRQPNJLK";function tb(t){let e=t.toUpperCase();if(!/^[STFGM]\d{7}[A-Z]$/.test(e))return!1;let n=e[0],o=[2,7,6,5,4,3,2],r=0;for(let c=0;c<7;c++)r+=(e.charCodeAt(c+1)-48)*o[c];n==="T"||n==="G"?r+=4:n==="M"&&(r+=3);let s=r%11,a=n==="M"?gj:n==="F"||n==="G"?fj:hj;return e[8]===a[s]}i(tb,"nricChecksum");function nb(t){let e=t.replace(/-/g,"").toUpperCase();if(!/^\d{7,8}[A-Z]$/.test(e))return!1;let n=Number.parseInt(e.slice(0,-1),10);return e.slice(-1)==="TRWAGMYFPDXBNJZSQVHLCKE"[n%23]}i(nb,"nifChecksum");var yj={0:1,1:0,2:5,3:7,4:9,5:13,6:15,7:17,8:19,9:21,A:1,B:0,C:5,D:7,E:9,F:13,G:15,H:17,I:19,J:21,K:2,L:4,M:18,N:20,O:11,P:3,Q:6,R:8,S:12,T:14,U:16,V:10,W:22,X:25,Y:24,Z:23};function ob(t){let e=t.toUpperCase();if(!/^[A-Z0-9]{16}$/.test(e))return!1;let n=0;for(let o=0;o<15;o++){let r=e[o];if(o%2===0){let s=yj[r];if(s===void 0)return!1;n+=s}else n+=/\d/.test(r)?r.charCodeAt(0)-48:r.charCodeAt(0)-65}return e[15]===String.fromCharCode(65+n%26)}i(ob,"fiscalCodeChecksum");function rb(t){let e=un(t);if(e.length!==11)return!1;let n=[1,3,7,9,1,3,7,9,1,3],o=0;for(let r=0;r<10;r++)o+=(e.charCodeAt(r)-48)*n[r];return(10-o%10)%10===e.charCodeAt(10)-48}i(rb,"peselChecksum");function ib(t){let e=un(t);if(e.length!==9)return!1;let n=0;for(let o=0;o<8;o++)n+=(e.charCodeAt(o)-48)*(9-o);return n-=e.charCodeAt(8)-48,n!==0&&n%11===0}i(ib,"bsnChecksum");function sb(t){let e=un(t);if(e.length!==11||/^(\d)\1{10}$/.test(e))return!1;for(let n of[9,10]){let o=0;for(let s=0;s<n;s++)o+=(e.charCodeAt(s)-48)*(n+1-s);if(o*10%11%10!==e.charCodeAt(n)-48)return!1}return!0}i(sb,"cpfChecksum");function ab(t){let e=t.replace(/[\s.-]/g,"").toUpperCase();if(!/^[12]\d{4}(\d{2}|2[AB])\d{6}\d{2}$/.test(e))return!1;let n=e.slice(0,13).replace("2A","19").replace("2B","18");if(!/^\d{13}$/.test(n))return!1;let o=Number.parseInt(e.slice(13),10),r=0;for(let s of n)r=(r*10+(s.charCodeAt(0)-48))%97;return 97-r===o}i(ab,"nirChecksum");var bj=new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW".split(" "));function cb(t){return bj.has(t.slice(4,6).toUpperCase())}i(cb,"bicStructure");function jo(t){let e=t.slice(-20);return new Set(e).size>=5}i(jo,"tokenVariety");function ub(t){let e=t.replace(/[^0-9A-Fa-f]/g,"");return!(/^0+$/.test(e)||t.includes(".")&&!/[A-Fa-f]/.test(t))}i(ub,"macStructure");var Sj=[/^application\/json/i,/^application\/.*\+json/i,/^application\/x-www-form-urlencoded/i,/^application\/xml/i,/^application\/.*\+xml/i,/^text\//i];function ll(t,e){if(!t)return!1;if(e&&e.length>0){let n=t.toLowerCase();return e.some(o=>n.startsWith(o.toLowerCase()))}return Sj.some(n=>n.test(t))}i(ll,"isScannableContentType");var CA=[{id:"finance-us-aba-routing",patterns:[/\b[0123678]\d{8}\b/g,/\b[0123678]\d{3}-\d{4}-\d\b/g],validate:Jy,confidence:.4,context:["aba","routing","rtn","bank"]},{id:"finance-swift-bic",patterns:[/\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g],validate:cb,confidence:.3,context:["swift","bic"]},{id:"finance-us-bank-account",patterns:[/\b\d{8,17}\b/g],confidence:.15,context:["bank account","account number","acct","checking","savings"]},{id:"finance-cvv",patterns:[/\b\d{3,4}\b/g],confidence:.1,context:["cvv","cvc","cvv2","cvc2","security code","card code"]}],IA=[{id:"id-us-itin",patterns:[/\b9\d{2}-(?:5\d|6[0-5]|7\d|8[0-8]|9[0-2]|9[4-9])-\d{4}\b/g],confidence:.6,context:["itin","taxpayer","tax","tin"]},{id:"id-us-passport",patterns:[/\b[A-Z]\d{8}\b/g,/\b\d{9}\b/g],confidence:.2,context:["passport","travel document"]},{id:"id-uk-nino",patterns:[/\b(?!BG|GB|NK|KN|NT|TN|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z](?: ?\d{2}){3} ?[A-D]\b/gi],confidence:.45,context:["national insurance","ni number","nino"]},{id:"id-uk-nhs",patterns:[/\b\d{3}[- ]?\d{3}[- ]?\d{4}\b/g],validate:Ky,confidence:.4,context:["nhs","national health","health service"]},{id:"id-ca-sin",patterns:[/\b[1-79]\d{2}[- ]?\d{3}[- ]?\d{3}\b/g],validate:Om,confidence:.4,context:["sin","social insurance","assurance sociale","nas"]},{id:"id-au-abn",patterns:[/\b\d{2} ?\d{3} ?\d{3} ?\d{3}\b/g],validate:Yy,confidence:.4,context:["abn","australian business number"]},{id:"id-au-acn",patterns:[/\b\d{3} ?\d{3} ?\d{3}\b/g],validate:Qy,confidence:.4,context:["acn","australian company number"]},{id:"id-au-tfn",patterns:[/\b\d{3} ?\d{3} ?\d{3}\b/g],validate:Wy,confidence:.4,context:["tfn","tax file"]},{id:"id-au-medicare",patterns:[/\b[2-6]\d{3} ?\d{5} ?\d{1,2}\b/g],validate:Xy,confidence:.4,context:["medicare"]},{id:"id-in-aadhaar",patterns:[/\b[2-9]\d{3}[- ]?\d{4}[- ]?\d{4}\b/g],validate:eb,confidence:.4,context:["aadhaar","aadhar","uidai"]},{id:"id-in-pan",patterns:[/\b[A-Z]{3}[ABCFGHLJPT][A-Z]\d{4}[A-Z]\b/g],confidence:.4,context:["pan","permanent account"]},{id:"id-sg-nric",patterns:[/\b[STFGM]\d{7}[A-Z]\b/g],validate:tb,confidence:.8,context:["nric","fin"]},{id:"id-es-nif",patterns:[/\b\d{8}-?[A-Z]\b/g],validate:nb,confidence:.4,context:["nif","dni","documento nacional de identidad"]},{id:"id-it-fiscal-code",patterns:[/\b[A-Z]{6}[0-9LMNP-V]{2}[A-EHLMPR-T][0-9LMNP-V]{2}[A-Z][0-9LMNP-V]{3}[A-Z]\b/gi],validate:ob,confidence:.8,context:["codice fiscale","fiscal code"]},{id:"id-pl-pesel",patterns:[/\b\d{2}(?:[02468][1-9]|[13579][012])(?:0[1-9]|[12]\d|3[01])\d{5}\b/g],validate:rb,confidence:.4,context:["pesel"]},{id:"id-nl-bsn",patterns:[/\b\d{9}\b/g],validate:ib,confidence:.4,context:["bsn","burgerservicenummer","sofinummer"]},{id:"id-br-cpf",patterns:[/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g],validate:sb,confidence:.4,context:["cpf","cadastro de pessoas"]},{id:"id-fr-nir",patterns:[/\b[12]\d{4}(?:\d{2}|2[AB])\d{6}\d{2}\b/g],validate:ab,confidence:.6,context:["insee","s\xE9curit\xE9 sociale","securite sociale","nir"]}],vA=[{id:"network-ipv6",patterns:[/(?<![\w:])(?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,5}(?::[0-9A-Fa-f]{1,4}){1,2}|(?:[0-9A-Fa-f]{1,4}:){1,4}(?::[0-9A-Fa-f]{1,4}){1,3}|(?:[0-9A-Fa-f]{1,4}:){1,3}(?::[0-9A-Fa-f]{1,4}){1,4}|(?:[0-9A-Fa-f]{1,4}:){1,2}(?::[0-9A-Fa-f]{1,4}){1,5}|[0-9A-Fa-f]{1,4}:(?::[0-9A-Fa-f]{1,4}){1,6}|:(?::[0-9A-Fa-f]{1,4}){1,6})(?:%[0-9A-Za-z]+)?(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?(?![\w:]|\.\d)/g]},{id:"network-mac",patterns:[/\b[0-9A-Fa-f]{2}([:-])(?:[0-9A-Fa-f]{2}\1){4}[0-9A-Fa-f]{2}\b/g,/\b[0-9A-Fa-f]{4}\.[0-9A-Fa-f]{4}\.[0-9A-Fa-f]{4}\b/g],validate:ub}];var TA=[{id:"secret-private-key",patterns:[/-----BEGIN (?:[^-]+ )?PRIVATE KEY-----[^-]+-----END (?:[^-]+ )?PRIVATE KEY-----/gs]},{id:"secret-jwt",patterns:[/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g]},{id:"secret-aws-access-key",patterns:[/\b(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}\b/g]},{id:"secret-aws-bedrock",patterns:[/\bABSK[A-Za-z0-9+/]{109,269}={0,2}/g]},{id:"secret-github",patterns:[/gh[opsru]_[A-Za-z0-9]{36,}/g,/github_pat_[A-Za-z0-9_]{20,}/g],validate:jo},{id:"secret-gitlab",patterns:[/\bgl(?:pat|dt|rt|ft|soat|imt)-[A-Za-z0-9_=-]{20,}/g],validate:jo},{id:"secret-zuplo",patterns:[/zpka_[A-Za-z0-9_]{42,}/g]},{id:"secret-openai",patterns:[/\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{16,}T3BlbkFJ[A-Za-z0-9_-]{16,}\b/g]},{id:"secret-anthropic",patterns:[/\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,120}\b/g]},{id:"secret-google-api-key",patterns:[/\bAIza[A-Za-z0-9_-]{35}\b/g],validate:jo},{id:"secret-stripe",patterns:[/\b(?:sk|rk)_(?:test|live|prod)_[A-Za-z0-9]{10,99}\b/g]},{id:"secret-slack",patterns:[/\bxox[baprs]-\d{8,13}-[0-9A-Za-z-]{8,250}\b/g,/\bxoxe(?:\.xoxp)?-1-[A-Za-z0-9]{64,}\b/g,/\bxapp-\d-[A-Z0-9]+-\d+-[a-z0-9]+\b/gi,/https?:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9+/]{40,60}/g],validate:jo},{id:"secret-discord-webhook",patterns:[/https?:\/\/(?:[a-z0-9]+\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_-]{60,}/g]},{id:"secret-npm",patterns:[/\bnpm_[A-Za-z0-9]{36}\b/g],validate:jo},{id:"secret-pypi",patterns:[/\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000}/g]},{id:"secret-sendgrid",patterns:[/\bSG\.[A-Za-z0-9_-]{16,32}\.[A-Za-z0-9_-]{16,64}\b/g]},{id:"secret-twilio",patterns:[/\bSK[0-9a-fA-F]{32}\b/g]},{id:"secret-hugging-face",patterns:[/\bhf_[A-Za-z]{34,40}\b/g],validate:jo},{id:"secret-databricks",patterns:[/\bdapi[a-f0-9]{32}(?:-\d)?\b/g]},{id:"secret-shopify",patterns:[/\bshp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}\b/g]},{id:"secret-square",patterns:[/\b(?:EAAA|sq0(?:atp|csp)-)[A-Za-z0-9_-]{22,60}\b/g]},{id:"secret-mailchimp",patterns:[/\b[a-f0-9]{32}-us\d{1,2}\b/g]},{id:"secret-mailgun",patterns:[/\bkey-[a-f0-9]{32}\b/g],confidence:.4,context:["mailgun"]},{id:"secret-postman",patterns:[/\bPMAK-[a-f0-9]{24}-[a-f0-9]{34}\b/gi]},{id:"secret-terraform",patterns:[/\b[a-z0-9]{14}\.atlasv1\.[a-z0-9_=-]{60,70}\b/gi]},{id:"secret-sentry",patterns:[/\bsntry[su]_[A-Za-z0-9+/=_.-]{40,300}/g]},{id:"secret-digitalocean",patterns:[/\bdo[por]_v1_[a-f0-9]{64}\b/g]},{id:"secret-heroku",patterns:[/\bHRKU-AA[A-Za-z0-9_-]{58}\b/g]},{id:"secret-perplexity",patterns:[/\bpplx-[A-Za-z0-9]{48}\b/g],validate:jo},{id:"secret-azure-client",patterns:[/\b[A-Za-z0-9_~.]{3}\dQ~[A-Za-z0-9_~.-]{31,34}\b/g],confidence:.7},{id:"secret-telegram-bot",patterns:[/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/g]}];var Rj=[{id:"contact-email",patterns:[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g]},{id:"finance-credit-card",patterns:[/\b\d(?:[ -]?\d){12,18}\b/g],validate:km},{id:"id-us-ssn",patterns:[/\b\d{3}-\d{2}-\d{4}\b/g],validate:By},{id:"finance-iban",patterns:[/\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]){11,30}\b/g],validate:Vy},{id:"finance-crypto-wallet",patterns:[/\b(?:bc1[ac-hj-np-z02-9]{11,71}|[13][a-km-zA-HJ-NP-Z1-9]{25,34}|0x[a-fA-F0-9]{40})\b/g]},{id:"network-ipv4",patterns:[/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g]},{id:"contact-phone",patterns:[/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g]}],dl=[...TA,...Rj,...CA,...IA,...vA],pl=dl.map(t=>t.id);var lb={pii:pl.filter(t=>t.startsWith("contact-")||t.startsWith("id-")),"region-eu":["id-es-nif","id-it-fiscal-code","id-pl-pesel","id-nl-bsn","id-fr-nir","finance-iban"]},db=(()=>{let t=new Set,e=new Map;for(let o of pl){let r=o.split("-");if(t.add(r[0]),r.length>2){let s=`${r[0]}-${r[1]}`;e.set(s,(e.get(s)??0)+1)}}let n=[...e.entries()].filter(([o,r])=>o.startsWith("id-")||r>1).map(([o])=>o);return[...t,...n,...Object.keys(lb)].sort()})();function pb(t){let e=new Set,n=[];for(let o of t){let r=lb[o];if(r){for(let a of r)e.add(a);continue}let s=pl.filter(a=>a===o||a.startsWith(`${o}-`));if(s.length>0)for(let a of s)e.add(a);else n.push(o)}return{ids:e,unknown:n}}i(pb,"resolveEntitySelection");var wj=.85,Cj=.45,AA=.5,Ij=60,vj=25;function EA(t,e){let n=t.entities,o;if(n){let{ids:r,unknown:s}=pb(n);s.length>0&&e?.warn({unknown:s,groups:db},"DataLossPrevention: ignoring unknown entities (not a recognizer id or group)"),o=dl.filter(a=>r.has(a.id))}else o=[...dl];if(t.customPatterns)for(let r of t.customPatterns)try{o.push({id:r.name,patterns:[new RegExp(r.pattern,"g")],confidence:r.confidence,context:r.context})}catch(s){e?.warn({name:r.name,cause:s},"DataLossPrevention: skipping invalid custom pattern regex")}return o}i(EA,"resolveRecognizers");function Tj(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_\-.]/g," ").toLowerCase()}i(Tj,"normalizeWindow");function Pj(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Pj,"escapeRegExp");var PA=[",",";","&",`
336
336
  `];function Aj(t,e,n,o){let r=t.slice(Math.max(0,e-Ij),e),s=Math.max(...PA.map(l=>r.lastIndexOf(l)));s>=0&&(r=r.slice(s+1));let a=t.slice(n,n+vj),c=PA.map(l=>a.indexOf(l)).filter(l=>l>=0);c.length>0&&(a=a.slice(0,Math.min(...c)));let u=Tj(`${r} ${a}`);return o.some(l=>new RegExp(`\\b${Pj(l.toLowerCase())}\\b`).test(u))}i(Aj,"hasNearbyContext");function Ej(t,e){let n=[];if(e.patterns)for(let o of e.patterns)for(let r of t.matchAll(o))n.push({start:r.index,end:r.index+r[0].length,text:r[0]});return e.match&&n.push(...e.match(t)),n}i(Ej,"collectSpans");function OA(t,e,n=AA){let o=[],r=new Map;for(let a of e)for(let c of Ej(t,a)){if(a.validate&&!a.validate(c.text))continue;let u=a.confidence??wj;u<1&&a.context&&a.context.length>0&&Aj(t,c.start,c.end,a.context)&&(u=Math.min(1,u+(a.contextBoost??Cj))),!(u<n)&&(o.push({entity:a.id,start:c.start,end:c.end,confidence:u}),r.set(a.id,(r.get(a.id)??0)+1))}let s=[...r.entries()].map(([a,c])=>({entity:a,count:c}));return{findings:s,matches:o,hasMatch:s.length>0}}i(OA,"scan");function kA(t,e,n){if(e.length===0)return t;let o=[...e].sort((c,u)=>c.start-u.start),r=[];for(let c of o){let u=r[r.length-1];u&&c.start<=u.end?u.end=Math.max(u.end,c.end):r.push({start:c.start,end:c.end})}let s="",a=0;for(let c of r)s+=t.slice(a,c.start)+n,a=c.end;return s+=t.slice(a),s}i(kA,"applyMask");function ml(t,e,n){let o=e.engine??"builtin";switch(o){case"builtin":{let r=EA(e,n),{findings:s,matches:a,hasMatch:c}=OA(t,r,e.minConfidence??AA);return{findings:s,hasMatch:c,applyMask:i(u=>kA(t,a,u),"applyMask")}}case"presidio-service":throw new I("The Data Loss Prevention engine 'presidio-service' is not implemented yet. Set the 'engine' option to 'builtin' (or remove it to use the default) in the policy options in policies.json.");default:throw new I(`The Data Loss Prevention engine '${o}' is not supported. Set the 'engine' option to 'builtin' (or remove it to use the default) in the policy options in policies.json.`)}}i(ml,"detect");var _A=i(async(t,e,n,o)=>{let r=t.headers.get("content-type");if(!ll(r,n?.contentTypes))return t;let s=await t.clone().text();if(!s)return t;let a=ml(s,n??{},e.log);if(!a.hasMatch)return t;switch(n?.action??"mask"){case"log":return e.log.warn({findings:a.findings,policyName:o},"DLP detected sensitive data in request body"),t;case"block":{let u=a.findings.map(l=>l.entity);return z.unprocessableContent(t,e,{detail:`Request blocked by Data Loss Prevention. Detected sensitive data: ${u.join(", ")}.`})}case"mask":{let u=a.applyMask(n?.mask??"[REDACTED]"),l=new Headers(t.headers);return l.delete("content-length"),new Le(t,{body:u,headers:l})}}return t},"DataLossPreventionInboundPolicy");F("data-loss-prevention",_A);var xA=i(async(t,e,n,o,r)=>{let s=t.headers.get("content-type");if(!ll(s,o?.contentTypes))return t;let a=await t.clone().text();if(!a)return t;let c=ml(a,o??{},n.log);if(!c.hasMatch)return t;switch(o?.action??"mask"){case"log":return n.log.warn({findings:c.findings,policyName:r},"DLP detected sensitive data in response body"),t;case"block":{await t.body?.cancel();let l=c.findings.map(d=>d.entity);return z.unprocessableContent(e,n,{detail:`Response blocked by Data Loss Prevention. Detected sensitive data: ${l.join(", ")}.`})}case"mask":{let l=c.applyMask(o?.mask??"[REDACTED]");await t.body?.cancel();let d=new Headers(t.headers);return d.delete("content-length"),new Response(l,{headers:d,status:t.status,statusText:t.statusText})}}return t},"DataLossPreventionOutboundPolicy");et("data-loss-prevention",xA);var MA=i(async(t,e,n,o)=>($e(n,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Jt(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,oAuthResourceMetadataEnabled:n.oAuthResourceMetadataEnabled},o)),"FirebaseJwtInboundPolicy");F("firebase-jwt-auth",MA);var LA=i(async(t,e,n)=>{let o="application/x-www-form-urlencoded",r="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![r,o].some(d=>s.startsWith(d)))return n?.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n?.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,m]of a)c[d]=m.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new Le(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");F("form-data-to-json",LA);function NA(t,e,n,o,r){return r==="anthropic-messages"?pr(async s=>{await o(e.input,s,e.traceStartTime,t,n)}):r==="openai-responses"?Ao(async s=>{await o(e.input,s,e.traceStartTime,t,n)}):Po(t,async s=>{await o(e.input,s,e.traceStartTime,t,n)})}i(NA,"createGalileoStreamingAccumulator");var mb=Ye("zuplo:policies:GalileoTracingPolicy"),zA=Symbol("galileo-tracing");function Oj(t,e){ce.set(t,zA,e)}i(Oj,"setTracingContext");function kj(t){return ce.get(t,zA)}i(kj,"getTracingContext");function qA(t){let e=new Date(t).getTime();return(Date.now()-e)*1e6}i(qA,"getDurationNs");async function $A(t,e,n,o,r){let s=r.baseUrl||"https://api.galileo.ai",a=new Date().toISOString(),c,u=e;if(u?.usage&&typeof u.usage=="object"){let w=u.usage,v=typeof w.input_tokens=="number"?w.input_tokens:typeof w.prompt_tokens=="number"?w.prompt_tokens:void 0,T=typeof w.output_tokens=="number"?w.output_tokens:typeof w.completion_tokens=="number"?w.completion_tokens:void 0;c={num_input_tokens:v,num_output_tokens:T,num_total_tokens:typeof w.total_tokens=="number"?w.total_tokens:void 0,duration_ns:qA(n)}}let l="",d;u?.output&&Array.isArray(u.output)?l=u.output.map(w=>{let T=w.content;return T&&Array.isArray(T)?T.map(P=>P.text).filter(P=>typeof P=="string").join(" "):""}).filter(w=>typeof w=="string"&&w.length>0).join(" "):u?.choices&&Array.isArray(u.choices)?l=u.choices.map(w=>{let v=w,T=v.message;return v.finish_reason&&(d=String(v.finish_reason)),T?.content}).filter(w=>typeof w=="string").join(" "):Array.isArray(u?.content)&&(l=mt(u.content),typeof u.stop_reason=="string"&&(d=u.stop_reason));let m=[],h="";t?.messages?(m=t.messages.map(w=>({role:w.role,content:mt(w.content)})),h=m.map(w=>`${w.role}: ${w.content}`).join(`
@@ -368,5 +368,5 @@ Signature verification is impossible without access to the original signed mater
368
368
  `);let C=new f("!xml"),E=C,_="",x="";this.entityExpansionCount=0,this.currentExpandedLength=0;let M=new R(this.options.processEntities);for(let B=0;B<b.length;B++)if(b[B]==="<")if(b[B+1]==="/"){let Y=pt(b,">",B,"Closing Tag is not closed."),J=b.substring(B+2,Y).trim();if(this.options.removeNSPrefix){let Rt=J.indexOf(":");Rt!==-1&&(J=J.substr(Rt+1))}this.options.transformTagName&&(J=this.options.transformTagName(J)),E&&(_=this.saveTextToParentTag(_,E,x));let Fe=x.substring(x.lastIndexOf(".")+1);if(J&&this.options.unpairedTags.indexOf(J)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${J}>`);let Te=0;Fe&&this.options.unpairedTags.indexOf(Fe)!==-1?(Te=x.lastIndexOf(".",x.lastIndexOf(".")-1),this.tagsNodeStack.pop()):Te=x.lastIndexOf("."),x=x.substring(0,Te),E=this.tagsNodeStack.pop(),_="",B=Y}else if(b[B+1]==="?"){let Y=it(b,B,!1,"?>");if(!Y)throw new Error("Pi Tag is not closed.");if(_=this.saveTextToParentTag(_,E,x),!(this.options.ignoreDeclaration&&Y.tagName==="?xml"||this.options.ignorePiTags)){let J=new f(Y.tagName);J.add(this.options.textNodeName,""),Y.tagName!==Y.tagExp&&Y.attrExpPresent&&(J[":@"]=this.buildAttributesMap(Y.tagExp,x,Y.tagName)),this.addChild(E,J,x,B)}B=Y.closeIndex+1}else if(b.substr(B+1,3)==="!--"){let Y=pt(b,"-->",B+4,"Comment is not closed.");if(this.options.commentPropName){let J=b.substring(B+4,Y-2);_=this.saveTextToParentTag(_,E,x),E.add(this.options.commentPropName,[{[this.options.textNodeName]:J}])}B=Y}else if(b.substr(B+1,2)==="!D"){let Y=M.readDocType(b,B);this.docTypeEntities=Y.entities,B=Y.i}else if(b.substr(B+1,2)==="!["){let Y=pt(b,"]]>",B,"CDATA is not closed.")-2,J=b.substring(B+9,Y);_=this.saveTextToParentTag(_,E,x);let Fe=this.parseTextData(J,E.tagname,x,!0,!1,!0,!0);Fe==null&&(Fe=""),this.options.cdataPropName?E.add(this.options.cdataPropName,[{[this.options.textNodeName]:J}]):E.add(this.options.textNodeName,Fe),B=Y+2}else{let Y=it(b,B,this.options.removeNSPrefix),J=Y.tagName,Fe=Y.rawTagName,Te=Y.tagExp,Rt=Y.attrExpPresent,go=Y.closeIndex;if(this.options.transformTagName){let Et=this.options.transformTagName(J);Te===J&&(Te=Et),J=Et}E&&_&&E.tagname!=="!xml"&&(_=this.saveTextToParentTag(_,E,x,!1));let Lt=E;Lt&&this.options.unpairedTags.indexOf(Lt.tagname)!==-1&&(E=this.tagsNodeStack.pop(),x=x.substring(0,x.lastIndexOf("."))),J!==C.tagname&&(x+=x?"."+J:J);let yo=B;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,x,J)){let Et="";if(Te.length>0&&Te.lastIndexOf("/")===Te.length-1)J[J.length-1]==="/"?(J=J.substr(0,J.length-1),x=x.substr(0,x.length-1),Te=J):Te=Te.substr(0,Te.length-1),B=Y.closeIndex;else if(this.options.unpairedTags.indexOf(J)!==-1)B=Y.closeIndex;else{let bo=this.readStopNodeData(b,Fe,go+1);if(!bo)throw new Error(`Unexpected end of ${Fe}`);B=bo.i,Et=bo.tagContent}let pn=new f(J);J!==Te&&Rt&&(pn[":@"]=this.buildAttributesMap(Te,x,J)),Et&&(Et=this.parseTextData(Et,J,x,!0,Rt,!0,!0)),x=x.substr(0,x.lastIndexOf(".")),pn.add(this.options.textNodeName,Et),this.addChild(E,pn,x,yo)}else{if(Te.length>0&&Te.lastIndexOf("/")===Te.length-1){if(J[J.length-1]==="/"?(J=J.substr(0,J.length-1),x=x.substr(0,x.length-1),Te=J):Te=Te.substr(0,Te.length-1),this.options.transformTagName){let pn=this.options.transformTagName(J);Te===J&&(Te=pn),J=pn}let Et=new f(J);J!==Te&&Rt&&(Et[":@"]=this.buildAttributesMap(Te,x,J)),this.addChild(E,Et,x,yo),x=x.substr(0,x.lastIndexOf("."))}else{let Et=new f(J);this.tagsNodeStack.push(E),J!==Te&&Rt&&(Et[":@"]=this.buildAttributesMap(Te,x,J)),this.addChild(E,Et,x,yo),E=Et}_="",B=go}}else _+=b[B];return C.child},"parseXml");function ke(b,C,E,_){this.options.captureMetaData||(_=void 0);let x=this.options.updateTag(C.tagname,E,C[":@"]);x===!1||(typeof x=="string"&&(C.tagname=x),b.addChild(C,_))}i(ke,"addChild"),n(ke,"addChild");var Me=n(function(b,C,E){if(b.indexOf("&")===-1)return b;let _=this.options.processEntities;if(!_.enabled||_.allowedTags&&!_.allowedTags.includes(C)||_.tagFilter&&!_.tagFilter(C,E))return b;for(let x in this.docTypeEntities){let M=this.docTypeEntities[x],B=b.match(M.regx);if(B){if(this.entityExpansionCount+=B.length,_.maxTotalExpansions&&this.entityExpansionCount>_.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${_.maxTotalExpansions}`);let pe=b.length;if(b=b.replace(M.regx,M.val),_.maxExpandedLength&&(this.currentExpandedLength+=b.length-pe,this.currentExpandedLength>_.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${_.maxExpandedLength}`)}}if(b.indexOf("&")===-1)return b;for(let x in this.lastEntities){let M=this.lastEntities[x];b=b.replace(M.regex,M.val)}if(b.indexOf("&")===-1)return b;if(this.options.htmlEntities)for(let x in this.htmlEntities){let M=this.htmlEntities[x];b=b.replace(M.regex,M.val)}return b=b.replace(this.ampEntity.regex,this.ampEntity.val),b},"replaceEntitiesValue");function ve(b,C,E,_){return b&&(_===void 0&&(_=C.child.length===0),b=this.parseTextData(b,C.tagname,E,!1,C[":@"]?Object.keys(C[":@"]).length!==0:!1,_),b!==void 0&&b!==""&&C.add(this.options.textNodeName,b),b=""),b}i(ve,"saveTextToParentTag"),n(ve,"saveTextToParentTag");function ot(b,C,E,_){return!!(C&&C.has(_)||b&&b.has(E))}i(ot,"isItStopNode"),n(ot,"isItStopNode");function Pt(b,C,E=">"){let _,x="";for(let M=C;M<b.length;M++){let B=b[M];if(_)B===_&&(_="");else if(B==='"'||B==="'")_=B;else if(B===E[0])if(E[1]){if(b[M+1]===E[1])return{data:x,index:M}}else return{data:x,index:M};else B===" "&&(B=" ");x+=B}}i(Pt,"tagExpWithClosingIndex"),n(Pt,"tagExpWithClosingIndex");function pt(b,C,E,_){let x=b.indexOf(C,E);if(x===-1)throw new Error(_);return x+C.length-1}i(pt,"findClosingIndex"),n(pt,"findClosingIndex");function it(b,C,E,_=">"){let x=Pt(b,C+1,_);if(!x)return;let M=x.data,B=x.index,pe=M.search(/\s/),Y=M,J=!0;pe!==-1&&(Y=M.substring(0,pe),M=M.substring(pe+1).trimStart());let Fe=Y;if(E){let Te=Y.indexOf(":");Te!==-1&&(Y=Y.substr(Te+1),J=Y!==x.data.substr(Te+1))}return{tagName:Y,tagExp:M,closeIndex:B,attrExpPresent:J,rawTagName:Fe}}i(it,"readTagExp"),n(it,"readTagExp");function St(b,C,E){let _=E,x=1;for(;E<b.length;E++)if(b[E]==="<")if(b[E+1]==="/"){let M=pt(b,">",E,`${C} is not closed`);if(b.substring(E+2,M).trim()===C&&(x--,x===0))return{tagContent:b.substring(_,E),i:M};E=M}else if(b[E+1]==="?")E=pt(b,"?>",E+1,"StopNode is not closed.");else if(b.substr(E+1,3)==="!--")E=pt(b,"-->",E+3,"StopNode is not closed.");else if(b.substr(E+1,2)==="![")E=pt(b,"]]>",E,"StopNode is not closed.")-2;else{let M=it(b,E,">");M&&((M&&M.tagName)===C&&M.tagExp[M.tagExp.length-1]!=="/"&&x++,E=M.closeIndex)}}i(St,"readStopNodeData"),n(St,"readStopNodeData");function At(b,C,E){if(C&&typeof b=="string"){let _=b.trim();return _==="true"?!0:_==="false"?!1:L(b,E)}else return h(b)?b:""}i(At,"parseValue"),n(At,"parseValue");function Wt(b,C,E){let _=Number.parseInt(b,C);return _>=0&&_<=1114111?String.fromCodePoint(_):E+b+";"}i(Wt,"fromCodePoint"),n(Wt,"fromCodePoint");var Dn=f.getMetaDataSymbol();function Zt(b,C){return Dt(b,C)}i(Zt,"prettify"),n(Zt,"prettify");function Dt(b,C,E){let _,x={};for(let M=0;M<b.length;M++){let B=b[M],pe=Ut(B),Y="";if(E===void 0?Y=pe:Y=E+"."+pe,pe===C.textNodeName)_===void 0?_=B[pe]:_+=""+B[pe];else{if(pe===void 0)continue;if(B[pe]){let J=Dt(B[pe],C,Y),Fe=Qt(J,C);B[Dn]!==void 0&&(J[Dn]=B[Dn]),B[":@"]?Yt(J,B[":@"],Y,C):Object.keys(J).length===1&&J[C.textNodeName]!==void 0&&!C.alwaysCreateTextNode?J=J[C.textNodeName]:Object.keys(J).length===0&&(C.alwaysCreateTextNode?J[C.textNodeName]="":J=""),x[pe]!==void 0&&x.hasOwnProperty(pe)?(Array.isArray(x[pe])||(x[pe]=[x[pe]]),x[pe].push(J)):C.isArray(pe,Y,Fe)?x[pe]=[J]:x[pe]=J}}}return typeof _=="string"?_.length>0&&(x[C.textNodeName]=_):_!==void 0&&(x[C.textNodeName]=_),x}i(Dt,"compress"),n(Dt,"compress");function Ut(b){let C=Object.keys(b);for(let E=0;E<C.length;E++){let _=C[E];if(_!==":@")return _}}i(Ut,"propName"),n(Ut,"propName");function Yt(b,C,E,_){if(C){let x=Object.keys(C),M=x.length;for(let B=0;B<M;B++){let pe=x[B];_.isArray(pe,E+"."+pe,!0,!0)?b[pe]=[C[pe]]:b[pe]=C[pe]}}}i(Yt,"assignAttributes"),n(Yt,"assignAttributes");function Qt(b,C){let{textNodeName:E}=C,_=Object.keys(b).length;return!!(_===0||_===1&&(b[E]||typeof b[E]=="boolean"||b[E]===0))}i(Qt,"isLeafTag"),n(Qt,"isLeafTag");var An={allowBooleanAttributes:!1,unpairedTags:[]};function dn(b,C){C=Object.assign({},An,C);let E=[],_=!1,x=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let M=0;M<b.length;M++)if(b[M]==="<"&&b[M+1]==="?"){if(M+=2,M=tn(b,M),M.err)return M}else if(b[M]==="<"){let B=M;if(M++,b[M]==="!"){M=Un(b,M);continue}else{let pe=!1;b[M]==="/"&&(pe=!0,M++);let Y="";for(;M<b.length&&b[M]!==">"&&b[M]!==" "&&b[M]!==" "&&b[M]!==`
369
369
  `&&b[M]!=="\r";M++)Y+=b[M];if(Y=Y.trim(),Y[Y.length-1]==="/"&&(Y=Y.substring(0,Y.length-1),M--),!q(Y)){let Te;return Y.trim().length===0?Te="Invalid space after '<'.":Te="Tag '"+Y+"' is an invalid name.",ae("InvalidTag",Te,ut(b,M))}let J=Ie(b,M);if(J===!1)return ae("InvalidAttr","Attributes for '"+Y+"' have open quote.",ut(b,M));let Fe=J.value;if(M=J.index,Fe[Fe.length-1]==="/"){let Te=M-Fe.length;Fe=Fe.substring(0,Fe.length-1);let Rt=_e(Fe,C);if(Rt===!0)_=!0;else return ae(Rt.err.code,Rt.err.msg,ut(b,Te+Rt.err.line))}else if(pe)if(J.tagClosed){if(Fe.trim().length>0)return ae("InvalidTag","Closing tag '"+Y+"' can't have attributes or invalid starting.",ut(b,B));if(E.length===0)return ae("InvalidTag","Closing tag '"+Y+"' has not been opened.",ut(b,B));{let Te=E.pop();if(Y!==Te.tagName){let Rt=ut(b,Te.tagStartPos);return ae("InvalidTag","Expected closing tag '"+Te.tagName+"' (opened in line "+Rt.line+", col "+Rt.col+") instead of closing tag '"+Y+"'.",ut(b,B))}E.length==0&&(x=!0)}}else return ae("InvalidTag","Closing tag '"+Y+"' doesn't have proper closing.",ut(b,M));else{let Te=_e(Fe,C);if(Te!==!0)return ae(Te.err.code,Te.err.msg,ut(b,M-Fe.length+Te.err.line));if(x===!0)return ae("InvalidXml","Multiple possible root nodes found.",ut(b,M));C.unpairedTags.indexOf(Y)!==-1||E.push({tagName:Y,tagStartPos:B}),_=!0}for(M++;M<b.length;M++)if(b[M]==="<")if(b[M+1]==="!"){M++,M=Un(b,M);continue}else if(b[M+1]==="?"){if(M=tn(b,++M),M.err)return M}else break;else if(b[M]==="&"){let Te=re(b,M);if(Te==-1)return ae("InvalidChar","char '&' is not expected.",ut(b,M));M=Te}else if(x===!0&&!En(b[M]))return ae("InvalidXml","Extra text at the end",ut(b,M));b[M]==="<"&&M--}}else{if(En(b[M]))continue;return ae("InvalidChar","char '"+b[M]+"' is not expected.",ut(b,M))}if(_){if(E.length==1)return ae("InvalidTag","Unclosed tag '"+E[0].tagName+"'.",ut(b,E[0].tagStartPos));if(E.length>0)return ae("InvalidXml","Invalid '"+JSON.stringify(E.map(M=>M.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return ae("InvalidXml","Start tag expected.",1);return!0}i(dn,"validate"),n(dn,"validate");function En(b){return b===" "||b===" "||b===`
370
370
  `||b==="\r"}i(En,"isWhiteSpace"),n(En,"isWhiteSpace");function tn(b,C){let E=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let _=b.substr(E,C-E);if(C>5&&_==="xml")return ae("InvalidXml","XML declaration allowed only at the start of the document.",ut(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}i(tn,"readPI"),n(tn,"readPI");function Un(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let E=1;for(C+=8;C<b.length;C++)if(b[C]==="<")E++;else if(b[C]===">"&&(E--,E===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}i(Un,"readCommentAndCDATA"),n(Un,"readCommentAndCDATA");var se='"',On="'";function Ie(b,C){let E="",_="",x=!1;for(;C<b.length;C++){if(b[C]===se||b[C]===On)_===""?_=b[C]:_!==b[C]||(_="");else if(b[C]===">"&&_===""){x=!0;break}E+=b[C]}return _!==""?!1:{value:E,index:C,tagClosed:x}}i(Ie,"readAttributeStr"),n(Ie,"readAttributeStr");var be=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function _e(b,C){let E=d(b,be),_={};for(let x=0;x<E.length;x++){if(E[x][1].length===0)return ae("InvalidAttr","Attribute '"+E[x][2]+"' has no space in starting.",jt(E[x]));if(E[x][3]!==void 0&&E[x][4]===void 0)return ae("InvalidAttr","Attribute '"+E[x][2]+"' is without value.",jt(E[x]));if(E[x][3]===void 0&&!C.allowBooleanAttributes)return ae("InvalidAttr","boolean attribute '"+E[x][2]+"' is not allowed.",jt(E[x]));let M=E[x][2];if(!Ae(M))return ae("InvalidAttr","Attribute '"+M+"' is an invalid name.",jt(E[x]));if(!_.hasOwnProperty(M))_[M]=1;else return ae("InvalidAttr","Attribute '"+M+"' is repeated.",jt(E[x]))}return!0}i(_e,"validateAttributeString"),n(_e,"validateAttributeString");function le(b,C){let E=/\d/;for(b[C]==="x"&&(C++,E=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(E))break}return-1}i(le,"validateNumberAmpersand"),n(le,"validateNumberAmpersand");function re(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,le(b,C);let E=0;for(;C<b.length;C++,E++)if(!(b[C].match(/\w/)&&E<20)){if(b[C]===";")break;return-1}return C}i(re,"validateAmpersand"),n(re,"validateAmpersand");function ae(b,C,E){return{err:{code:b,msg:C,line:E.line||E,col:E.col}}}i(ae,"getErrorObject"),n(ae,"getErrorObject");function Ae(b){return m(b)}i(Ae,"validateAttrName"),n(Ae,"validateAttrName");function q(b){return m(b)}i(q,"validateTagName"),n(q,"validateTagName");function ut(b,C){let E=b.substring(0,C).split(/\r?\n/);return{line:E.length,col:E[E.length-1].length+1}}i(ut,"getLineNumberForPosition"),n(ut,"getLineNumberForPosition");function jt(b){return b.startIndex+b[1].length}i(jt,"getPositionFromMatch"),n(jt,"getPositionFromMatch");var fo=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(b){this.externalEntities={},this.options=s(b)}parse(b,C){if(typeof b!="string"&&b.toString)b=b.toString();else if(typeof b!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(C){C===!0&&(C={});let x=dn(b,C);if(x!==!0)throw Error(`${x.err.msg}:${x.err.line}:${x.err.col}`)}let E=new ze(this.options);E.addExternalEntities(this.externalEntities);let _=E.parseXml(b);return this.options.preserveOrder||_===void 0?_:Zt(_,this.options)}addEntity(b,C){if(C.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(b.indexOf("&")!==-1||b.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(C==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[b]=C}static getMetaDataSymbol(){return f.getMetaDataSymbol()}};return new fo(t)},"getXmlParser");var sR=class extends So{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){super(e,n),$e(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?eo(e.parseOnStatusCodes):void 0,this.parser=gx({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new U(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var aR=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new De(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var cR=class{static{i(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Ze("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){Q("utility.get-consumer");let n=Lr(),o=this.bucketId??Je.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new I("ApiKeyConsumerClient - no bucketId provided and no default bucket is configured for this environment. Pass `bucketId` explicitly (find it in the Zuplo portal under Settings > API Key Buckets).");if(!o.startsWith("bckt_"))throw new I(`ApiKeyConsumerClient - bucketId "${o}" is not a valid bucket id. Bucket ids start with "bckt_" (e.g. "bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL"); a bucket name (e.g. "zprj-...-working-copy") is not accepted here. Find the bucket id in the Zuplo portal under Settings > API Key Buckets.`);if(!e||e.trim()==="")throw new I("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let r=await this.getCacheName(o),s=new Ve(r,n);if(this.cacheDurationSeconds>0){let l=await s.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await lh(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&s.put(e,u,this.cacheDurationSeconds),u}};var yx=10,bx=3e4,el=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#r=bx,this.#n=yx}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:bx,this.#n=yx}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let n=this.#i[e];return!(n===void 0||n===0)}#u(e){let n=this.#e.get(e);if(n&&!this.#s(n))return n.data}async get(e){let n=this.#u(e);if(n)return this.#l(e),n;if(this.#a(e))try{await NZ(()=>this.#u(e)!==void 0||!this.#a(e),this.#r+this.#n+1,this.#n);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let n=this.#c(e);tr().waitUntil(n)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let n=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(n===void 0)throw new I(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#i[e]--}}};async function NZ(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new I(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(NZ,"waitUntilTrue");import{SpanStatusCode as Rx,trace as qZ}from"@opentelemetry/api";var Sx,wx=i(()=>(Sx??=qZ.getTracer("pipeline"),Sx),"tracer"),Cx=i(async(t,e,n)=>{let o=Xe.instance.routeData.policies,r=ki([t],o);if(r.length===0)throw new U(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0];return await wx().startActiveSpan(`policy:${s.policyName}`,async c=>{try{Oi(c,s);let u=await s.handler(e,n);if(u instanceof Request||u instanceof Le||u instanceof Response)return u instanceof Response||u instanceof Le?u:new Le(u);{let l=new I(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:Rx.ERROR}),c.recordException(l),l}}finally{c.end()}})},"invokeInboundPolicy"),Ix=i(async(t,e,n,o)=>{let r=Xe.instance.routeData.policies,s=za([t],r);if(s.length===0)throw new U(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await wx().startActiveSpan(`policy:${a.policyName}`,async u=>{try{Oi(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;{let d=new I(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw u.setStatus({code:Rx.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeOutboundPolicy");var $Z="127.0.0.1";function vx(t){let e=O.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?$Z:void 0)}i(vx,"resolveClientIp");function zZ(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[s,a]=r.split("=");s&&a&&(o[s.trim()]=a.trim())}),o.asnum&&(e[Vl]=o.asnum),o.zip&&(e[Jl]=o.zip.split("+")[0]),o.dma&&(e[Kl]=o.dma),o.region_code&&(e[Wl]=o.region_code),o.timezone&&(e[Yl]=o.timezone),o.city&&(e[Hl]=o.city),o.continent&&(e[Fl]=o.continent),o.country_code&&(e[Gl]=o.country_code),o.long&&(e[Zl]=o.long),o.lat&&(e[Bl]=o.lat),e}catch{return{}}}i(zZ,"parseEdgeScapeHeader");function Tx(t,e){let n=zZ(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(Tx,"setZpHeadersFromAkamaiEdgeScapeHeader");var jd=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(DR);if(n){let o=new Headers(e);Tx(o,n),this.#e=o}}get ip(){return vx(this.#e)}get asn(){try{let e=this.#e.get(Vl);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(LR)??void 0}get city(){return this.#e.get(fR)??this.#e.get(Hl)??void 0}get continent(){return this.#e.get(gR)??this.#e.get(Fl)??void 0}get country(){return this.#e.get(yR)??this.#e.get(Gl)??void 0}get latitude(){return this.#e.get(SR)??this.#e.get(Bl)??void 0}get longitude(){return this.#e.get(bR)??this.#e.get(Zl)??void 0}get colo(){return this.#e.get(NR)??void 0}get postalCode(){return this.#e.get(IR)??this.#e.get(Jl)??void 0}get metroCode(){return this.#e.get(CR)??this.#e.get(Kl)??void 0}get region(){return this.#e.get(RR)??this.#e.get(qR)??void 0}get regionCode(){return this.#e.get(wR)??this.#e.get(Wl)??void 0}get timezone(){return this.#e.get(vR)??this.#e.get(Yl)??void 0}get httpProtocol(){return this.#e.get($R)??void 0}get clientCert(){return this.#e.get(PR)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(AR)??void 0}get clientMtlsVerificationReason(){return this.#e.get(ER)??void 0}get clientCertFingerprintSha256(){return this.#e.get(OR)??void 0}get clientCertNotBefore(){return this.#e.get(kR)??void 0}get clientCertNotAfter(){return this.#e.get(_R)??void 0}get clientCertIssuerDn(){return this.#e.get(xR)??void 0}get clientCertSubjectDn(){return this.#e.get(MR)??void 0}toJSON(){return{ip:this.ip,asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function ks(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(ks,"createRewriteContext");var Na=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},qa=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},lt=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let o=new t(n);return t.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new U(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;auditLogEventId="";#t;#o;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#o=[],this.#n=[]}addResponseSendingHook(e){this.#o.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#n.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#t)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=O.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#o)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#n)await r(e,n,o)},"onHandlerResponse")},Hd=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:s,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,l)=>Cx(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>Ix(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let m=new Le(d,l);return Xe.instance.handleRequest(m,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{lt.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{lt.getContextExtensions(this).addResponseSendingFinalHook(u)},this.analyticsContext=new GR(o),Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,o){Q("context.addEventListener");let r=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}removeEventListener(e,n,o){Q("context.removeEventListener"),super.removeEventListener(e,n,o)}};export{wi as a,Yn as b,Ot as c,zx as d,Dx as e,ch as f,mt as g,vr as h,Ux as i,Tr as j,Q as k,lh as l,ph as m,gn as n,Jo as o,Oa as p,Pr as q,z as r,wt as s,Ar as t,hh as u,fh as v,rd as w,Ne as x,sn as y,Wo as z,ue as A,So as B,Ch as C,Ah as D,d0 as E,Ti as F,Na as G,qa as H,rf as I,at as J,RI as K,wI as L,DL as M,AI as N,Sf as O,JL as P,$r as Q,Qa as R,zr as S,Bi as T,Oo as U,ko as V,ir as W,Dr as X,Eo as Y,ft as Z,dp as _,Vi as $,Ji as aa,ec as ba,tc as ca,Ki as da,zt as ea,sr as fa,gt as ga,Vt as ha,Ft as ia,Wi as ja,yt as ka,_o as la,Yi as ma,Qi as na,Ur as oa,jr as pa,Hr as qa,pp as ra,Xi as sa,nc as ta,es as ua,oc as va,xo as wa,ro as xa,Gn as ya,mp as za,hp as Aa,rc as Ba,ic as Ca,ts as Da,ns as Ea,sc as Fa,ac as Ga,cc as Ha,uc as Ia,os as Ja,lc as Ka,dc as La,rs as Ma,pc as Na,Mo as Oa,Lo as Pa,is as Qa,ss as Ra,as as Sa,No as Ta,io as Ua,cs as Va,mc as Wa,hc as Xa,fc as Ya,gc as Za,yc as _a,Fr as $a,bc as ab,Sc as bb,Rc as cb,wc as db,Cc as eb,Ic as fb,vc as gb,Tc as hb,us as ib,Pc as jb,Ac as kb,Ec as lb,Oc as mb,kc as nb,_c as ob,xc as pb,Mc as qb,Lc as rb,Nc as sb,qc as tb,$c as ub,zc as vb,Dc as wb,Gr as xb,Zr as yb,Br as zb,Uc as Ab,jc as Bb,Hc as Cb,Vr as Db,Fc as Eb,Gc as Fb,Zc as Gb,Bc as Hb,Vc as Ib,ls as Jb,Jc as Kb,Kc as Lb,ds as Mb,fp as Nb,Wc as Ob,Yc as Pb,Qc as Qb,Cf as Rb,qo as Sb,Xc as Tb,eu as Ub,tu as Vb,nu as Wb,ou as Xb,ru as Yb,iu as Zb,su as _b,au as $b,rr as ac,cu as bc,uu as cc,lu as dc,du as ec,pu as fc,ps as gc,Jr as hc,Kr as ic,ms as jc,hs as kc,fs as lc,mu as mc,gs as nc,ys as oc,hu as pc,fu as qc,bs as rc,Wr as sc,gu as tc,yu as uc,bu as vc,Su as wc,Ru as xc,wu as yc,Cu as zc,Iu as Ac,vu as Bc,Tu as Cc,Pu as Dc,Au as Ec,Eu as Fc,Ou as Gc,ku as Hc,gp as Ic,_u as Jc,$o as Kc,yp as Lc,xu as Mc,bp as Nc,Sp as Oc,Rp as Pc,wp as Qc,Cp as Rc,Ip as Sc,vp as Tc,Tp as Uc,Pp as Vc,Ap as Wc,Ep as Xc,Op as Yc,kp as Zc,_p as _c,xp as $c,Mp as ad,Mu as bd,Lu as cd,Lp as dd,Np as ed,qp as fd,$p as gd,Nu as hd,qu as id,zp as jd,Dp as kd,Up as ld,hT as md,fT as nd,gT as od,yT as pd,bT as qd,ST as rd,ag as sd,mz as td,cg as ud,lg as vd,pg as wd,fg as xd,yg as yd,Sg as zd,wg as Ad,Ig as Bd,Pg as Cd,Og as Dd,xg as Ed,Ng as Fd,$g as Gd,zg as Hd,Wu as Id,Yu as Jd,Qu as Kd,Fg as Ld,tl as Md,Bg as Nd,Vg as Od,Jz as Pd,Jg as Qd,Kg as Rd,qT as Sd,$T as Td,DT as Ud,ty as Vd,ry as Wd,uy as Xd,dy as Yd,aP as Zd,dP as _d,pP as $d,wP as ae,CP as be,IP as ce,vP as de,OP as ee,kP as fe,Py as ge,MP as he,bm as ie,uU as je,Ay as ke,Jt as le,jP as me,xy as ne,My as oe,GP as pe,qy as qe,BP as re,tA as se,nA as te,oA as ue,rA as ve,iA as we,sA as xe,pA as ye,fA as ze,Zy as Ae,bA as Be,SA as Ce,RA as De,_A as Ee,xA as Fe,MA as Ge,LA as He,DA as Ie,FA as Je,GA as Ke,_m as Le,Nj as Me,JA as Ne,WA as Oe,Ib as Pe,sE as Qe,hr as Re,Bs as Se,tt as Te,dt as Ue,uo as Ve,Tge as We,hl as Xe,Oge as Ye,kge as Ze,Tn as _e,Mge as $e,Lge as af,Nge as bf,qge as cf,fl as df,$ge as ef,ai as ff,Hge as gf,Nm as hf,ci as if,Js as jf,Ab as kf,eye as lf,Eb as mf,Ob as nf,kb as of,_b as pf,xb as qf,Mb as rf,Lb as sf,Nb as tf,qb as uf,$b as vf,zb as wf,eSe as xf,$n as yf,Pn as zf,It as Af,QE as Bf,KH as Cf,WH as Df,Db as Ef,SSe as Ff,RSe as Gf,wSe as Hf,pO as If,mO as Jf,FSe as Kf,GSe as Lf,Ub as Mf,yl as Nf,jm as Of,ZSe as Pf,gO as Qf,KSe as Rf,bl as Sf,g1 as Tf,y1 as Uf,Hb as Vf,rRe as Wf,RO as Xf,wO as Yf,cRe as Zf,uRe as _f,lRe as $f,dRe as ag,CO as bg,IO as cg,TO as dg,lo as eg,Fo as fg,R1 as gg,w1 as hg,SRe as ig,RRe as jg,wRe as kg,CRe as lg,po as mg,T1 as ng,LRe as og,EO as pg,GRe as qg,Bb as rg,A1 as sg,N1 as tg,$1 as ug,_O as vg,iwe as wg,swe as xg,awe as yg,NO as zg,dwe as Ag,pwe as Bg,mwe as Cg,Qb as Dg,Zm as Eg,Xb as Fg,zO as Gg,Cwe as Hg,Iwe as Ig,vwe as Jg,Twe as Kg,Lk as Lg,zn as Mg,fS as Ng,oCe as Og,Nk as Pg,rCe as Qg,SS as Rg,RS as Sg,Uk as Tg,wG as Ug,Zk as Vg,PS as Wg,t_ as Xg,ES as Yg,l_ as Zg,OS as _g,_S as $g,p_ as ah,m_ as bh,h_ as ch,LS as dh,qS as eh,w_ as fh,C_ as gh,I_ as hh,v_ as ih,T_ as jh,A_ as kh,DS as lh,HG as mh,x_ as nh,FS as oh,z_ as ph,D_ as qh,U_ as rh,tZ as sh,j_ as th,H_ as uh,F_ as vh,G_ as wh,Z_ as xh,VS as yh,V_ as zh,J_ as Ah,JS as Bh,KS as Ch,Y_ as Dh,X_ as Eh,ex as Fh,QS as Gh,nx as Hh,cx as Ih,oR as Jh,rR as Kh,ux as Lh,fx as Mh,sR as Nh,aR as Oh,cR as Ph,el as Qh};
371
- /*! For license information please see chunk-VVVYHDCV.js.LEGAL.txt */
372
- //# sourceMappingURL=chunk-VVVYHDCV.js.map
371
+ /*! For license information please see chunk-YFAVPQDX.js.LEGAL.txt */
372
+ //# sourceMappingURL=chunk-YFAVPQDX.js.map