@trayai/helix-sdk 0.111.0 → 0.112.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,19 @@ general availability, minor versions may include breaking changes.
9
9
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
10
10
  released together and share a version — install matching versions.
11
11
 
12
+ ## 0.112.0
13
+
14
+ ### Added
15
+
16
+ - **Async function calls.** `ctx.callFunctionAsync(functionPath, input?)` queues a
17
+ fire-and-forget call to another route in your project, which runs as a new, independent
18
+ execution — use it to kick off work without making the caller wait for it, or to hand off to a
19
+ fresh execution instead of doing everything in one handler. See the README's "Async function
20
+ calls" section for the full behavior, including the two-hop chaining cap, at-least-once
21
+ delivery, and the `POST`-only target requirement.
22
+ - **`ctx.parentExecutionId`.** On the context of a function invoked via `ctx.callFunctionAsync`,
23
+ this is the calling execution's id (`null` otherwise, and always `null` in `helix dev`).
24
+
12
25
  ## 0.107.0
13
26
 
14
27
  ### Changed
package/README.md CHANGED
@@ -13,6 +13,7 @@ The runtime SDK for **Helix** — a TypeScript-first platform for building integ
13
13
  - [Authenticated HTTP](#authenticated-http)
14
14
  - [Capability modules](#capability-modules)
15
15
  - [Scheduled functions](#scheduled-functions)
16
+ - [Async function calls](#async-function-calls)
16
17
  - [Authentication](#authentication)
17
18
  - [Configuration](#configuration)
18
19
  - [Logging](#logging)
@@ -226,6 +227,55 @@ Limits — schedules run in the same deployed runtime as HTTP functions and shar
226
227
  - **Memory is managed by the platform** and is not configurable per function.
227
228
  - Fires are scheduled for the exact cron minute, but execution can start late under load or on a cold start — compare `ctx.trigger.scheduledAt` (intended) with `ctx.trigger.firedAt` (actual) when lateness matters.
228
229
 
230
+ ## Async function calls
231
+
232
+ `ctx.callFunctionAsync(functionPath, input?)` queues a fire-and-forget call to another route in
233
+ your project, which runs as a brand-new, independent execution. Use it to kick off work without
234
+ making the caller wait for it, or to hand off to a fresh execution instead of doing everything in
235
+ one long-lived handler:
236
+
237
+ ```typescript
238
+ // functions/leads/webhook.post.ts → POST /leads/webhook
239
+ import { defineFunction } from '@trayai/helix-sdk';
240
+
241
+ export default defineFunction(async (ctx) => {
242
+ await ctx.callFunctionAsync('leads/enrich', { leadId: ctx.input.leadId });
243
+ return { received: true }; // returns immediately; enrichment runs separately
244
+ });
245
+ ```
246
+
247
+ The target is an ordinary route — no special export or file location required — and can read
248
+ `ctx.parentExecutionId` to see which execution called it (`null` if it wasn't started this way):
249
+
250
+ ```typescript
251
+ // functions/leads/enrich.post.ts → POST /leads/enrich
252
+ import { defineFunction } from '@trayai/helix-sdk';
253
+
254
+ export default defineFunction(async (ctx) => {
255
+ ctx.log.info('Enriching lead', { leadId: ctx.input.leadId, calledBy: ctx.parentExecutionId });
256
+ });
257
+ ```
258
+
259
+ Things to know:
260
+
261
+ - **Fire-and-forget only.** `callFunctionAsync` resolves once the call is accepted, not once the
262
+ target runs — there is no result, status, or execution id to get back.
263
+ - **Chaining is capped at two hops.** A normal (HTTP or scheduled) execution can call once; the
264
+ execution it starts can call once more; a third hop is refused.
265
+ - **The target must accept `POST`.** The call always dispatches as `POST`, regardless of the
266
+ caller's own method.
267
+ - **Delivery is at-least-once, with no idempotency key.** A transient failure can cause the
268
+ target to run again for the same call — write target handlers to be safe to run more than
269
+ once, the same idempotency concern as scheduled functions.
270
+ - **A mistyped target path can fail silently.** The path isn't validated against your project's
271
+ real routes at call time. With no matching route and no catch-all, the call is dropped without
272
+ an error the caller ever sees; with a catch-all route, a typo'd path is silently absorbed by it
273
+ instead.
274
+ - **Deployed semantics differ from `helix dev`.** Locally there is no separate execution — the
275
+ call fires directly at the target route on the same dev server and returns immediately.
276
+ `ctx.parentExecutionId` is always `null` in dev, since there's no real calling execution to
277
+ report.
278
+
229
279
  ## Authentication
230
280
 
231
281
  Authenticated features (`ctx.http.authed`, `ctx.kv`, `ctx.files`) require you to be logged in during local development:
@@ -1 +1 @@
1
- import{p as n,q as o,r as i,s,t as d,u,v as l}from"../chunk-D5GPRK2D.js";async function a(e){let r=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),t=await s({proxyUrl:n(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:r,timeoutMs:e.timeoutMs??i});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"upstream",upstream:t.response}}async function k(e){d(e.url);let r=await l({signUrl:u(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"signed",signed:r.result}}export{a as callBrokerDev,k as callS3SignDev};
1
+ import{p as n,q as o,r as i,s,t as d,u,v as l}from"../chunk-KUXDW5ED.js";async function a(e){let r=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),t=await s({proxyUrl:n(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:r,timeoutMs:e.timeoutMs??i});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"upstream",upstream:t.response}}async function k(e){d(e.url);let r=await l({signUrl:u(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"signed",signed:r.result}}export{a as callBrokerDev,k as callS3SignDev};
@@ -0,0 +1 @@
1
+ var P=new Set(["production"]),a=new Map,g={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};a.set(g.name,g);var E=["api","broker","ingest","weaver","app","projectHost","dashboard"],x=["auth"],b=["storePrefix","appUrl","cookieName","cookieDomain"];function R(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let n of E)if(typeof e.hosts[n]!="string"||!e.hosts[n])throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string`);for(let n of x){let r=e.hosts[n];if(r!==void 0&&(typeof r!="string"||!r))throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string when set`)}for(let n of b)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function I(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&E.every(r=>e.hosts[r]===n.hosts[r])&&x.every(r=>e.hosts[r]===n.hosts[r])&&b.every(r=>e.login[r]===n.login[r])}function V(e){R(e);let n=a.get(e.name);if(n){if(I(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of a.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);a.set(e.name,e)}function N(e){return a.has(e)}function J(e){return a.get(e)}function y(e){let n=a.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function G(){return[...a.keys()]}function Y(){return[...a.values()].map(e=>e.exposedName)}function T(e){for(let n of a.values())if(n.exposedName===e)return n.name}var m=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function D(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[m];return}let r=e.trim(),t=T(r);if(t){n[m]=t;return}if(N(r)){n[m]=r;return}throw new Error(`Unknown environment: ${r}`)}function z(){return globalThis[m]}function W(){return[...a.values()].filter(e=>!P.has(e.name))}function X(){D(void 0),a.clear(),a.set(g.name,{...g,hosts:{...g.hosts},login:{...g.login}})}var u=class e extends Error{detail;constructor(n){super(U(n)),this.name="SdkError",this.detail=n}get kind(){return this.detail.kind}static unknownAlias(n,r){return new e({kind:"unknown_alias",alias:n,available:r})}static inputValidationFailed(n){return new e({kind:"input_validation_failed",fields:n})}static outputValidationFailed(n){return new e({kind:"output_validation_failed",fields:n})}static configLoadFailed(n){return new e({kind:"config_load_failed",cause:n})}static brokerError(n,r,t,i){return new e({kind:"broker_error",status:n,message:r,body:t,code:i})}static unsupportedBodyType(n){return new e({kind:"unsupported_body_type",actualType:n})}static unsupportedScheme(n){return new e({kind:"unsupported_scheme",scheme:n})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(n,r){return new e({kind:"db_call_failed",message:n,cause:r})}static dbQueryFailed(n){return new e({kind:"db_query_failed",message:n})}static dbInvalidParameters(n){return new e({kind:"db_invalid_parameters",message:n})}static kvKeyInvalid(n){return new e({kind:"kv_key_invalid",message:n})}static kvValueInvalid(n){return new e({kind:"kv_value_invalid",message:n})}static kvValueTooLarge(n,r){return new e({kind:"kv_value_too_large",message:n,maxBytes:r})}static kvTtlInvalid(n){return new e({kind:"kv_ttl_invalid",message:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(n,r,t){return new e({kind:"kv_call_failed",status:n,message:r,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(n){return new e({kind:"files_path_invalid",message:n})}static filesValueInvalid(n){return new e({kind:"files_value_invalid",message:n})}static filesValueTooLarge(n,r){return new e({kind:"files_value_too_large",message:n,maxBytes:r})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(n,r,t){return new e({kind:"files_call_failed",status:n,message:r,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(n){return new e({kind:"call_function_path_invalid",message:n})}static callFunctionCallFailed(n,r,t){return new e({kind:"call_function_call_failed",status:n,message:r,body:t})}static callFunctionRequiresProvisioning(){return new e({kind:"call_function_requires_provisioning"})}static callFunctionNotAvailable(){return new e({kind:"call_function_not_available"})}static callFunctionMissingExecutionJwt(){return new e({kind:"call_function_missing_execution_jwt"})}};function Z(e){return e instanceof u}function U(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)";case"call_function_path_invalid":return`Invalid function path: ${e.message}`;case"call_function_call_failed":return`Async function call failed: ${e.status} ${e.message}`;case"call_function_requires_provisioning":return"callFunctionAsync requires a provisioned project (run helix project set)";case"call_function_not_available":return"callFunctionAsync is not available: no running dev server was found";case"call_function_missing_execution_jwt":return"ctx.callFunctionAsync requires a helix project-execution JWT \u2014 a legacy internalJwt-only execution cannot call it"}}import{z as f}from"zod";var w="x-helix-destination-url",S="x-helix-authentication-id",A="x-helix-deployment-id",v="x-execution-id",q="x-helix-broker-error",ie="route_not_found",O=new Set([w,S,A,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",v]);function $(e){let n=e.toLowerCase();return O.has(n)||n.startsWith("x-tray-internal-")}var k=f.object({error:f.object({code:f.string(),message:f.string(),issues:f.array(f.unknown()).optional()})});function oe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/http/raw`;return n==="dev"?`${r}/dev`:r}function F(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function se(e){let n=new URL(e.url);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[s,o]of e.query.entries())n.searchParams.append(s,o);else for(let[s,o]of Object.entries(e.query))for(let p of Array.isArray(o)?o:[o])n.searchParams.append(s,p);let r;e.headers===void 0?r=[]:e.headers instanceof Headers?r=Array.from(e.headers.entries()):Array.isArray(e.headers)?r=e.headers:r=Object.entries(e.headers);let t=r.filter(([s])=>!$(s)),i=e.body!==void 0&&e.body!==null,d,l,c=!1;return i&&(F(e.body)?(d=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([o])=>o.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:n.toString(),headers:t,body:d,isStreamBody:c,defaultContentType:l}}var j=6e4;function H(e){return e.includes("json")}function C(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function B(e,n){if(e.byteLength===0)return;let r=n.toLowerCase();if(H(r)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return C(r)?new TextDecoder("utf-8").decode(e):e}function L(e){let n={};for(let[r,t]of e.entries())n[r.toLowerCase()]=t;return n}async function ae(e){let{request:n}=e,r=new Headers;for(let[s,o]of n.headers)r.append(s,o);n.defaultContentType&&!r.has("content-type")&&r.set("content-type",n.defaultContentType),r.set(w,n.destinationUrl),r.set(S,n.authenticationId);for(let[s,o]of Object.entries(e.credentialHeaders))r.set(s,o);e.executionId&&r.set(v,e.executionId);let t={method:n.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??j)};n.body!==void 0&&(t.body=n.body,n.isStreamBody&&(t.duplex="half"));let i=await fetch(e.proxyUrl,t),d=i.headers.get(q);if(d!==null){let s=await i.text(),o=s,p=s||d;try{o=JSON.parse(s);let h=k.safeParse(o);h.success&&(p=h.data.error.message)}catch{}return{kind:"brokerError",status:i.status,code:d,message:p,body:o}}let l=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:L(i.headers),body:B(l,c)}}}import{z as _}from"zod";var M=3e4;function fe(e){let n=new URL(e);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""))}function pe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/s3/sign`;return n==="dev"?`${r}/dev`:r}var K=_.object({url:_.string(),method:_.string(),expiresAt:_.string()});async function me(e){let n=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))n.set(l,c);e.executionId&&n.set(v,e.executionId);let r=await fetch(e.signUrl,{method:"POST",headers:n,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??M)}),t=await r.text(),i=t;try{i=JSON.parse(t)}catch{}if(r.ok){let l=K.safeParse(i);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:r.status,message:"malformed s3-sign response from credential broker",body:i}}let d=k.safeParse(i);return d.success?{kind:"brokerError",status:r.status,code:d.data.error.code,message:d.data.error.message,body:i}:{kind:"brokerError",status:r.status,message:t||`s3-sign request failed with status ${r.status}`,body:i}}export{V as a,N as b,J as c,y as d,G as e,Y as f,T as g,D as h,z as i,W as j,X as k,u as l,Z as m,A as n,ie as o,oe as p,se as q,j as r,ae as s,fe as t,pe as u,me as v};
@@ -0,0 +1,7 @@
1
+ import{d as T,l as c,n as rt,o as se,p as Ae,q as J,s as nt,t as ot,u as ke,v as it}from"./chunk-KUXDW5ED.js";var S="X-Helix-Project-Execution-Token",P="X-Tray-Token",Ar={mode:"dev",deploymentId:null},De={...Ar},N={};function Oo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(N.internalJwt=t),"helixExecutionJwt"in e&&(N.helixExecutionJwt=r),"devToken"in e&&(N.devToken=n),De={...De,...o}}function y(){return De}function I(){return N.internalJwt}function E(){return N.helixExecutionJwt}function ae(){return N.devToken}var Lo="tray-config-bridge",Mo="tray-dev-token-bridge",ce=null;function Uo(e){ce=e}function h(){if(!ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ce}function Bo(){ce=null}import{AsyncLocalStorage as Ct}from"async_hooks";import{trace as Hr,SpanKind as Jr,SpanStatusCode as Oe}from"@opentelemetry/api";import{ExportResultCode as Vr,W3CTraceContextPropagator as zr}from"@opentelemetry/core";import{NodeTracerProvider as qr,SimpleSpanProcessor as Yr,BatchSpanProcessor as Xr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as kr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Dr}from"@opentelemetry/exporter-logs-otlp-proto";function Fe(e){return T(e).hosts.ingest}function Fr(){return E()??""}function st(){return{[S]:Fr()}}function at(){let e=Fe(h().env);return new kr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(st())})}function ct(){let e=Fe(h().env);return new Dr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(st())})}import{logs as dt,SeverityNumber as le}from"@opentelemetry/api-logs";import{LoggerProvider as Nr,BatchLogRecordProcessor as Lr}from"@opentelemetry/sdk-logs";function V(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function _r(e){return new TextEncoder().encode(e).length}var lt="\u2026[truncated]",Or=_r(lt),z=4096;function _(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Or);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+lt}function g(e,t=z){return _(V(e),t)}var Mr="@trayai/helix-sdk",q,ut={debug:{number:le.DEBUG,text:"DEBUG"},info:{number:le.INFO,text:"INFO"},warn:{number:le.WARN,text:"WARN"},error:{number:le.ERROR,text:"ERROR"}};function Ur(){return y().mode==="lambda"?[new Lr({exporter:ct()})]:[]}function ft(){if(q!==void 0)return;let e=Ur();e.length!==0&&(q=new Nr({processors:e}),dt.setGlobalLoggerProvider(q))}function Br(e,t,r){let n=ut[e]??ut.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function mt(e,t,r){dt.getLogger(Mr).emit(Br(e,t,r))}async function pt(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
+ `)}finally{t!==void 0&&clearTimeout(t)}}function _e(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function jr(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function R(e,t){return jr()?`\x1B[${e}m${t}\x1B[0m`:t}var Kr=5,$r={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},gt="32",yt="31",ue="2",ht="1";function de(e){return R($r[e]??"0",e.padEnd(Kr))}function wt(e,t){return`${de("FN")} ${R(ht,`${e} ${t}`.trim())}`}function bt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${R(ue,n)} `:""}${de(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${R(ue,V(r))}`),i}function St(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Et(e){return`${de("AUTH")} ${e}`}function xt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=R(o==="error"?yt:gt,s);return`${de("API")} ${e} ${t} \u2192 ${i} ${R(ue,`${n}ms`)}`}function vt(e,t,r){let n=t?yt:gt,o=R(n,"\u25CF"),s=R(n,t?"error":"success");return`${o} ${R(ht,e)} ${s} ${R(ue,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var Tt=new Ct,Gr=new Ct;function x(e){let t=Gr.getStore();t&&(t[e]=!0)}var Wr=/^[0-9a-f]{32}$/;function Qr(e){let t=e.replace(/-/g,"").toLowerCase();return Wr.test(t)?t:null}var Zr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},M=new Map;function Pt(e,t,r){let n=M.get(e);n?n[t]=r:M.set(e,{[t]:r})}function C(e,t,r){e.setAttribute(t,g(r))}var Y;function Rt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function en(e){return Math.round(e[0]*1e3+e[1]/1e6)}function It(e){try{process.stdout.write(V(e)+`
4
+ `)}catch{}}var Ne=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=M.get(o),i={...n.attributes};if(s!==void 0){for(let[u,d]of Object.entries(s))typeof d=="string"?i[u]=_(d):typeof d=="object"&&d!==null?i[u]=g(d):i[u]=d;M.delete(o)}let a=Tt.getStore(),l=a?Qr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Rt(n.startTime),endTimeUnixNano:Rt(n.endTime),attributes:i,status:{code:Zr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:Vr.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t,r){}onEnd(t){M.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Me=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
+ `+wt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=M.get(n)?.properties;L(bt(String(r.level??"info"),String(r.message??""),o,St(t.startTime)));break}case"auth":L(Et(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(xt(String(r.method??""),String(r.host??""),n,en(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ue=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function tn(){let t=[_e()?new Me:new Yr(new Ne)];return y().mode==="lambda"&&t.push(new Ue(new Xr(at()))),t.push(new Le),t}function rn(){Y===void 0&&(Y=new qr({spanProcessors:tn()}),Y.register({propagator:new zr}),ft())}async function nn(e=2e3){let t=[pt(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
+ `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var v=Hr.getTracer("@trayai/helix-sdk");function on({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-s;if(_e()){L(`
7
+ `+vt(n,i,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:i?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:i||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:i&&a!==null?_(a):null})}async function mi(e,t){let r=e.startMs??Date.now();rn();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>v.startActiveSpan("App",{kind:Jr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return n=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",n?"error":"success"),s.setStatus({code:n?Oe.ERROR:Oe.OK}),i}catch(i){throw n=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Oe.ERROR,message:o}),i}finally{s.end()}}))}finally{on({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await nn()}}var Dt=1024,A=100*1024*1024,At=250,sn=3600,an=sn*1e3,kt=new TextEncoder,cn=/(^|\/)\.\.(\/|$)/,ln=/[?#]/;function un(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=Dt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Be(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=Dt){if(e.length===0)return;if(cn.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(ln.test(e)||un(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let s=kt.encode(o).length;if(s>At)throw c.filesPathInvalid(`Path segment exceeds ${At} UTF-8 bytes (got ${s})`)}let n=kt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Ft(e){if(e>A)throw c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got ${e})`,A)}function U(e){let t=e!==void 0?e*1e3:an;return new Date(Date.now()+t)}import{join as G}from"path";var dn="files",fn="files-meta",mn=1023,pn=1,gn=5;function _t(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,mn-t-pn-gn)}function me(e){return G(e,".helix",dn)}function X(e){return G(e,".helix",fn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function Ot(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Nt="helix-schedule",k=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function bi(e){if(typeof e!="object"||e===null)throw new k("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new k("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new k(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof r!="string"||!yn(r))throw new k(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new k("`concurrent` must be a boolean");if(typeof o!="function")throw new k("`handler` must be a function");return Object.freeze({kind:Nt,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function Si(e){return typeof e=="object"&&e!==null&&e.kind===Nt&&typeof e.handler=="function"}function yn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as hn}from"@opentelemetry/api";function ye(e,t,r){let n=v.startSpan("log",{kind:hn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),mt(e,t,r)}function Lt(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function Pi(){try{return h().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import wn from"ky";import{context as je,trace as bn,SpanKind as Z,SpanStatusCode as Ut}from"@opentelemetry/api";async function he(e,t={}){let r=y(),{env:n}=h(),o,s={};if(r.mode==="lambda"){let a=I(),l=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(s[P]=a),d&&(s[S]=l),r.deploymentId&&(s[rt]=r.deploymentId),o=Ae(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();s.Authorization=`Bearer ${a}`,o=Ae(n,"dev")}let i;try{i=await nt({proxyUrl:o,credentialHeaders:s,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(i.kind==="brokerError"){let a=i.code===se?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.response}async function Mt(e){ot(e.url);let t=y(),{env:r}=h(),n,o={},s={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[S]=l),t.deploymentId&&(s.deploymentId=t.deploymentId),n=ke(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=ke(r,"dev")}let i;try{i=await it({signUrl:n,credentialHeaders:o,body:s,timeoutMs:e.timeout,executionId:t.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(i.kind==="brokerError"){let a=i.code===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.result}var Sn=["get","post","put","patch","delete","head","options"],jt="[stream body omitted]";function Kt(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?jt:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Ke(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n,o){let s=Ke(t),i="externalApi",a={kind:Z.CLIENT};return v.startActiveSpan(i,a,async l=>(l.setAttributes({method:e,host:s,"peer.service":n}),C(l,"request",{url:t,method:e,...r!==void 0?{body:Kt(r)}:{}}),o(l)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ut.OK}:{code:Ut.ERROR,message:r}),e.end()}var En=16;async function xn(e,t){let r=e.clone().body;return r?$t(r,t):new Uint8Array(0)}async function $t(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(s+=1,s>=En)break;continue}s=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let l of n)i.set(l,a),a+=l.byteLength;return i}async function Ht(e,t,r){if("kyResponse"in r)try{let n=await xn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}C(e,"response",s)}catch{C(e,"response",{status:t})}else C(e,"response",Kt(r.bodyValue))}async function vn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),s=new Request(e,{body:n,duplex:"half"}),i=await $t(o,z);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:jt}}}return typeof t=="string"?{body:t}:{}}function Qi(){let e=wn.create({});function t(n){return(o,s)=>{let i=je.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await vn(f,m.body),ie=p.body;if(a||(a=v.startSpan("externalApi",{kind:Z.CLIENT},i)),a.setAttributes({method:f.method.toUpperCase(),host:Ke(f.url)}),C(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Ht(a,p.status,{kyResponse:p}),p.ok?u("success"):s?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(x("hasError"),u("error",f.message),f)]}});return a=v.startSpan("externalApi",{kind:Z.CLIENT},i),a.setAttributes({method:n.toUpperCase(),host:Ke(String(o))}),je.with(bn.setSpan(je.active(),a),()=>{let f=n==="options"?d(o,{...s,method:"OPTIONS"}):d[n](o,s);return f.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(Sn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Rn(n)}}}function Rn(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(a,l={})=>{let u=i.toUpperCase();return Bt(u,a,l.body,e,async d=>{x("hasAuth");let f=v.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=J({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Ht(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw x("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function s(i,a={}){let l=a.method??"GET";return Bt(l,i,void 0,e,async u=>{x("hasAuth");let d=v.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Mt({authenticationId:n,url:i,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw x("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:s}}import{SpanKind as _n,SpanStatusCode as qt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Cn=18e4,Jt=Cn-1e4,Tn=2e3;async function Vt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<Jt;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let l=Math.min(Tn,200*2**s),u=l/2+Math.random()*(l/2),d=Jt-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),s++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Pn=new Set(["SELECT","WITH","SHOW"]),In=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function An(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function kn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):g(t);return c.dbCallFailed(s)}function Dn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Fn(e,t){return typeof t!="number"||t<0?{}:Pn.has(e)?{rowsRead:t}:In.has(e)?{rowsWritten:t}:{}}function zt(e){async function t(r,n,o){let s=J({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:i,body:a}=await he(s);if(i>=400)throw kn(i,a);return Dn(a)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:An,async execute(r,n){let o=ee(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(i);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Vt(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Fn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var $e=64*1024;function On(e){return e.length>$e?`${e.slice(0,$e)}...[truncated]`:e}function Nn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Ln(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>$e?C(e,"result",{truncated:!0,size:n.length}):C(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Mn(e,t,r){let n=ee(r),o=On(r);return v.startActiveSpan("database",{kind:_n.CLIENT},async s=>{Nn(s,e,t,n,o);try{x("hasDb");let{result:i,metadata:a}=await e.execute(t,r),l=Ln(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:qt.OK}),l}catch(i){x("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:qt.ERROR,message:a}),i}finally{s.end()}})}function Un(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=zt(n);function s(i,a){return o.validate(i),Mn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as Hn}from"unstorage";var Yt=1024,He=250*1024,Bn=new TextEncoder,jn=/(^|\/)\.\.(\/|$)/,Kn=/[?#]/,$n=/[\u0000-\u001F\u007F]/;function Xt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(jn.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(Kn.test(e)||$n.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Bn.encode(e).length;if(t<1||t>Yt)throw c.kvKeyInvalid(`Key must be between 1 and ${Yt} UTF-8 bytes (got ${t})`)}function Gt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Wt(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>He)throw c.kvValueTooLarge(`Value exceeds maximum size of ${He} bytes (got ${r})`,He)}function te(e){Xt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Qt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return te(i),t(i,a)},setItem(i,a,l){return te(i),r(i,a,l)},removeItem(i,a){return te(i),n(i,a)},hasItem(i,a){return te(i),o(i,a)},getKeys(i,a){return i.length>0&&te(i),s(i,a)}}}function be(e){return Hn({driver:Qt(e)})}import{defineDriver as Jn}from"unstorage";function Vn(e){try{return JSON.parse(e)}catch{return e}}var zn=Jn(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let s=o?.ttl,i=Vn(n);s!==void 0?await t.set(r,i,{ttl:s}):await t.set(r,i)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Zt(e){return zn({client:e})}import Xn from"ky";import{z as b}from"zod";async function D(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function er(e){return T(e).hosts.api}function qn(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Yn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${qn(t)}/${Yn(r)}`}var Gn=6e4,Je=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(Je),b.record(Je)])),Wn=b.object({projectId:b.string(),key:b.string(),value:Je,type:b.enum(["string","number","boolean","null","array","object"]),organizationId:b.string(),scope:b.string(),createdBy:b.string(),createdAt:b.number(),updatedBy:b.string(),updatedAt:b.number()});function Qn(){let e=I(),t=E(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[S]=t),o}function Zn(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,Zn(t),g(t))}async function Ee(e,t,r={}){try{let n=await Xn(t,{method:e,headers:Qn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Gn}),o=e==="head"?void 0:await D(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function tr(e){let t=er(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,s);let i=Wn.safeParse(s);if(!i.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(s));return i.data.value},async set(n,o,s){let{status:i,body:a}=await Ee("put",re(t,r,n),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&Se(i,a)},async delete(n){let{status:o,body:s}=await Ee("delete",re(t,r,n));o!==204&&Se(o,s)},async has(n){let{status:o,body:s}=await Ee("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,s)}}}function xe(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Wt(r),typeof o=="number"&&Gt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function eo(){let e=h();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function rr(e){let t=eo(),r=e??tr(t),n=be(Zt(r));return xe(n)}import{defineDriver as to}from"unstorage";var ro=to(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,s){let i=s?.ttl,a=r(n),l=typeof i=="number"?Date.now()+i*1e3:i===null?void 0:a?.expiresAt;t.set(n,{value:o,expiresAt:l})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function nr(){return ro({})}var Ve;function no(){return Ve||(Ve=be(nr())),Ve}function or(){return xe(no())}function oo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function na(){return oo()?rr():or()}import{createHash as ao}from"crypto";import{mkdir as co,readFile as lr,readdir as ur,rm as sr,unlink as lo,writeFile as ar}from"fs/promises";import{dirname as uo}from"path";async function io(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>A)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got more than ${A})`,A);r.push(s)}}return Buffer.concat(r)}async function B(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?io(e):Buffer.from(e)}var so={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},ir="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return ir;let r=e.slice(t+1).toLowerCase();return so[r]??ir}function K(){let e=y().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function ze(e){try{let t=await lr(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function cr(e){await co(uo(e),{recursive:!0})}async function fo(e,t){let r=ge(e,t),n;try{n=await ur(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function dr(e,t){let r=ge(e,t),n;try{n=await ur(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of n){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await dr(e,i)):s.isFile()&&o.push(i)}return o}function fr(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await B(t),s=r?.contentType??ve(e),i=ao("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await cr(l),await ar(l,o);let u={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},d=pe(n,e);return await cr(d),await ar(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await ze(e);return t?{data:await lr(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await ze(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await lo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await dr(t,e);return await Promise.all([sr(ge(t,e),{recursive:!0,force:!0}),sr(Ot(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,s=(await fo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let l=await ze(a);return l?Re(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}}}}import{createHash as bo}from"crypto";function Ce(e){return T(e).hosts.api}function mo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${mo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Te(e,t,r){return`${$(e,t,r)}/upload`}function mr(e,t,r){return`${$(e,t,r)}/download`}function pr(e,t,r){return`${$(e,t,r)}/signed-url`}function gr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function yr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import Ye from"ky";import{z as w}from"zod";var Xe=6e4,hr=w.object({id:w.string(),workspaceId:w.string(),projectId:w.string(),parentFolder:w.string().nullable().optional(),name:w.string(),size:w.number().nullable().optional(),objectType:w.enum(["Folder","File"]),contentType:w.string().nullable().optional(),createdAt:w.string(),updatedAt:w.string()}),po=w.object({signedURL:w.string()}),go=w.object({path:w.array(w.object({id:w.string(),name:w.string()})),elements:w.array(hr)});function Ge(){let e=I(),t=E(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[S]=t),o}function wr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function F(e,t){throw c.filesCallFailed(e,wr(t),g(t))}function yo(e,t){return e===400&&wr(t).toLowerCase()==="resource not found"}async function ho(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await Ye(t,{method:e,headers:Ge(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Xe}),o=await D(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function qe(e,t){let r=hr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function br(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&F(o,s),qe(o,s)},async getByName(n,o){let{status:s,body:i}=await H("get",gr(t,r,n,o));return s===404||yo(s,i)?null:((s<200||s>=300)&&F(s,i),qe(s,i))},async getById(n){let{status:o,body:s}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&F(o,s),qe(o,s))},async listChildren(n,o){let{status:s,body:i}=await H("get",yr(t,r,n,o));(s<200||s>=300)&&F(s,i);let a=go.safeParse(i);if(!a.success)throw c.filesCallFailed(s,"platform returned malformed listing",g(i));return a.data},async uploadContent(n,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:l,contentType:u}=await ho(a),d;try{d=await Ye(Te(t,r,n),{method:"post",headers:{...Ge(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Xe})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await D(d);(d.status<200||d.status>=300)&&F(d.status,f)},async downloadContent(n){let o;try{o=await Ye(mr(t,r,n),{method:"get",headers:Ge(),throwHttpErrors:!1,timeout:Xe})}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message:String(i);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await D(o);F(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await H("get",pr(t,r,n));(o<200||o>=300)&&F(o,s);let i=po.safeParse(s);if(!i.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&F(o,s)}}}function We(e){return e.split("/").filter(t=>t.length>0)}function Qe(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function wo(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Ze(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await wo(e,o,s)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:n}}async function et(e,t){if(t.length===0)return;let r=We(t),n;for(let o of r){let s=await e.getByName(n,o);if(!s||s.objectType!=="Folder")return null;n=s.id}return n}var So=500,Eo=8;async function xo(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;n[i]=await r(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}function vo(){let e=h();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Ro(e){return bo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Pe(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Ro(t)}}async function Sr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Er(e,t){let{elements:r}=await e.listChildren(t,So);return(await xo(r,Eo,async o=>{let s=o.objectType==="Folder"?await Er(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function xr(e){let t=vo(),r=e??br(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:l,name:u}=await Ze(r,s),d=await B(i),f=a?.contentType??ve(s),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${s}"`);let p=m??await Sr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Pe(s,ie??p,f)},async get(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Pe(s,a)}},async head(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Pe(s,a)},async delete(s){let i=await oe(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await et(r,s);if(i===null)return{deleted:0};let a=await Er(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await et(r,s??"");if(a===null)return{files:[],cursor:null};let l=i?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Pe(s?`${s}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:l}=await Ze(r,s),d=await r.getByName(a,l)??await Sr(r,a,l,i?.contentType);return{url:Te(n,o,d.id),expiresAt:U(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await oe(r,s),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:U(i?.expiresIn)}}}}function tt(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){O(n,r);let i=await B(o);return Ft(i.byteLength),e.put(n,i,s)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Be(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let s=Be(n??"");return fe(s,r),e.list(s,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function Co(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Xa(){if(Co())return tt(xr());let e=y().projectRoot;return tt(fr(),{maxPathBytes:e?_t(e):void 0})}import Po from"ky";function vr(e){return T(e).hosts.api}function To(){return"/private/v1/helix/function-calls"}function Rr(e){return`${e}${To()}`}var Io=5e3;function Ao(){let e=E();if(!!!(e&&e.trim().length>0))throw c.callFunctionMissingExecutionJwt();return{Accept:"application/json",[S]:e}}function ko(e,t){throw c.callFunctionCallFailed(e,Do(t),g(t))}function Do(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Cr(e){let t=vr(e.env);return{async callAsync(r,n){let o,s;try{let i=await Po(Rr(t),{method:"post",headers:Ao(),json:{functionPath:r,input:n},throwHttpErrors:!1,timeout:Io});o=i.status,s=await D(i)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.callFunctionCallFailed(0,a)}(o<200||o>=300)&&ko(o,s)}}}var Tr=1024;function Ie(e){if(typeof e!="string"||e.trim().length===0)throw c.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>Tr)throw c.callFunctionPathInvalid(`functionPath must be at most ${Tr} characters`)}function Fo(){let e=h();if(e.kind!=="provisioned")throw c.callFunctionRequiresProvisioning();return{env:e.env}}function Pr(e){return async function(r,n){Ie(r),await(e??Cr(Fo())).callAsync(r,n)}}function Ir(){return async function(t,r){Ie(t);let n=y().devServerUrl;if(!n)throw c.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Lt();fetch(`${n}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function _o(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ec(){return _o()?Pr():Ir()}export{Oo as a,y as b,Lo as c,Mo as d,Uo as e,h as f,Bo as g,Tt as h,Gr as i,x as j,C as k,rn as l,nn as m,v as n,on as o,mi as p,Lt as q,Pi as r,Qi as s,Un as t,na as u,O as v,W as w,pe as x,Xa as y,Ec as z,Nt as A,k as B,bi as C,Si as D};
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
- import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DqH1HJU0.js';
4
- export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DqH1HJU0.js';
5
- import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-vY_-Reh3.js';
6
- export { C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, e as resolveConfigOverride, w as workspaceIdSchema } from './sdk-config-vY_-Reh3.js';
3
+ import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DoNQWbb9.js';
4
+ export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, C as CallFunctionAsync, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DoNQWbb9.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-DU6cWbLW.js';
6
+ export { C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, e as resolveConfigOverride, w as workspaceIdSchema } from './sdk-config-DU6cWbLW.js';
7
7
  export { a as ENVIRONMENT_VALUES, E as Environment, e as environmentSchema } from './env-schema-DkgTG5b0.js';
8
8
  import 'ky';
9
9
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{A as we,B as ke,C as Se,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ce,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as Ee}from"./chunk-X4MA45FS.js";import{a as G,b as ve}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-D5GPRK2D.js";import{randomUUID as Le}from"crypto";import{SpanStatusCode as ae,SpanKind as Oe}from"@opentelemetry/api";import{defineEventHandler as je,getMethod as De,getRequestURL as He,getHeaders as ce,getHeader as de}from"h3";import{readBody as xe,getQuery as Ie,getRouterParams as _e}from"h3";async function ne(e,t){let r=await be(e),n=Ie(e),o=_e(e)??{},i={...n,...r,...o};return t?Te(i,t):i}async function be(e){try{let t=await xe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Te(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function oe(e){return t=>{e.node.res.statusCode=t}}function ie(){return(e,t)=>{throw new w(e,t)}}function se(e,t){let{statusCode:r,message:n}=Re(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Re(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Fe=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Pe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Fe.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Pe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ae(e,t){let{inputSchema:r,outputSchema:n}=Me(t),o=e;return je(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ze(d,i),p=Date.now(),v=new Date().toISOString(),h=De(i),l=He(i).pathname,u=Q(),y=J(),S=`${h} ${l}`;B();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return We(()=>F.run(N,()=>M.run(s,async()=>{let x=await Ne(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ye=Ke(i,x.input,u,y,h,l,s,f,a);return Ue(o,ye,n,i,y,s,f,{method:h,path:l,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:S,startedAt:v,startMs:p,userId:a,flags:N})})}async function We(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await K()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Be(e,r);if(n)return{ok:!1,response:n};throw r}}async function Ue(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:Oe.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ce(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let p=!1,v=null,h,l;try{let u=await G.run(t,()=>e(t));if(h=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let y=r.safeParse(u);if(!y.success){let S=Object.keys(y.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:S,executionId:i}),g.outputValidationFailed(S)}l=y.data}else l=u}catch(u){p=!0,v=u instanceof Error?u.message:String(u),Z("hasError"),l=$e(u,n,o,i)}finally{qe(a,n,{errored:p,errorMessage:v,handlerResult:h,response:l})}return{response:l,errored:p,errorMessage:v}})}function $e(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return se(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function qe(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=F.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ae.ERROR:ae.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Me(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:de(t,"x-tray-execution-id"))??Le(),o=(r?e.userId:de(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Be(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Ke(e,t,r,n,o,i,d,s,a){return{input:t,method:o,path:i,headers:P(ce(e)),http:Y(),db:f=>ee(f),kv:()=>te(),files:()=>re(),log:n,config:r,status:oe(e),error:ie(),state:{},request:e,executionId:d,deploymentId:s,userId:a,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ve(e){return e}import{resolve as m}from"path";import{existsSync as _,realpathSync as ue}from"fs";import{loadConfig as Je}from"c12";import{z as c}from"zod";import{z as ze}from"zod";var Ge=["production"],I=ze.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Qe=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:I.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),fe=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:I,authentications:c.record(c.string()),config:c.record(c.unknown())}),Xe=c.discriminatedUnion("kind",[fe.extend({kind:c.literal("provisioned"),projectId:L}),fe.extend({kind:c.literal("unprovisioned")})]),le=["helix","tray"],pe=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function C(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=C(t?.configFile);if(r!==void 0){let n=m(e,r);return _(n)?n:void 0}for(let n of le)for(let o of pe){let i=m(e,`${n}.config.${o}`);if(_(i))return i}}function Ye(e){for(let t of le)if(pe.some(r=>_(m(e,`${t}.config.${r}`))))return t;return"helix"}function et(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=C(t?.configFile);return{name:Ye(e),cwd:e,...r!==void 0?{configFile:et(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function H(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Qe.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=C(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!_(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Je(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=ue(o);if(ue(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return H(i.config,d)}var ge="WORKSPACE_ID_REQUIRED";function tt(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ge});return e.workspaceId}import{existsSync as rt,watch as nt,writeSync as ot}from"fs";import{basename as it,dirname as st,join as at,resolve as T}from"path";import{watchConfig as dt}from"c12";function ct(e,t){let r=e instanceof Error?e.message:String(e);ot(2,`[helix-watch] ${t.phase} error: ${r}
2
- `)}function A(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ut=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,me=new Set;function he(e,t){return b(e,{configFile:t})!==void 0}async function ft(e,t,r){if(he(e.cwd,t))try{return{current:await k(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:A(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?T(e.cwd,t):T(e.cwd);me.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${T(e.cwd,t)} not found; tray running with default config
1
+ import{A as ke,B as Se,C as xe,D as _e,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ee,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as ne}from"./chunk-QWCCRTLO.js";import{a as G,b as we}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-KUXDW5ED.js";import{randomUUID as je}from"crypto";import{SpanStatusCode as de,SpanKind as De}from"@opentelemetry/api";import{defineEventHandler as Ae,getMethod as He,getRequestURL as We,getHeaders as ue,getHeader as ce}from"h3";import{readBody as Ie,getQuery as be,getRouterParams as Te}from"h3";async function oe(e,t){let r=await Re(e),n=be(e),o=Te(e)??{},i={...n,...r,...o};return t?Fe(i,t):i}async function Re(e){try{let t=await Ie(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Fe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function ie(e){return t=>{e.node.res.statusCode=t}}function se(){return(e,t)=>{throw new w(e,t)}}function ae(e,t){let{statusCode:r,message:n}=Pe(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Pe(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Le=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Oe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Le.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Oe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ne(e,t){let{inputSchema:r,outputSchema:n}=Be(t),o=e;return Ae(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ke(d,i),l=d.mode==="lambda"?d.parentExecutionId??null:null,y=Date.now(),S=new Date().toISOString(),p=He(i),u=We(i).pathname,C=Q(),v=J(),Ce=`${p} ${u}`;B();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Ue(()=>F.run(N,()=>M.run(s,async()=>{let x=await $e(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ve=ze(i,x.input,C,v,p,u,s,f,a,l);return qe(o,ve,n,i,v,s,f,{method:p,path:u,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:Ce,startedAt:S,startMs:y,userId:a,flags:N})})}async function Ue(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await K()}}async function $e(e,t){try{return{ok:!0,input:await oe(e,t)}}catch(r){let n=Ve(e,r);if(n)return{ok:!1,response:n};throw r}}async function qe(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:De.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ue(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let l=!1,y=null,S,p;try{let u=await G.run(t,()=>e(t));if(S=u,u==null)n.node.res.statusCode=204,p="";else if(u instanceof Response)p=u;else if(r){let C=r.safeParse(u);if(!C.success){let v=Object.keys(C.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:v,executionId:i}),g.outputValidationFailed(v)}p=C.data}else p=u}catch(u){l=!0,y=u instanceof Error?u.message:String(u),Z("hasError"),p=Me(u,n,o,i)}finally{Ze(a,n,{errored:l,errorMessage:y,handlerResult:S,response:p})}return{response:p,errored:l,errorMessage:y}})}function Me(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return ae(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ze(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=F.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?de.ERROR:de.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Be(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ke(e,t){let r=e.mode==="lambda",n=(r?e.executionId:ce(t,"x-tray-execution-id"))??je(),o=(r?e.userId:ce(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Ve(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function ze(e,t,r,n,o,i,d,s,a,f){return{input:t,method:o,path:i,headers:P(ue(e)),http:Y(),db:l=>ee(l),kv:()=>te(),files:()=>re(),callFunctionAsync:ne(),log:n,config:r,status:ie(e),error:se(),state:{},request:e,executionId:d,deploymentId:s,userId:a,parentExecutionId:f,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ge(e){return e}import{resolve as m}from"path";import{existsSync as I,realpathSync as fe}from"fs";import{loadConfig as Xe}from"c12";import{z as c}from"zod";import{z as Je}from"zod";var Qe=["production"],_=Je.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Ye=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:_.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),le=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:_,authentications:c.record(c.string()),config:c.record(c.unknown())}),et=c.discriminatedUnion("kind",[le.extend({kind:c.literal("provisioned"),projectId:L}),le.extend({kind:c.literal("unprovisioned")})]),pe=["helix","tray"],ge=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function h(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=h(t?.configFile);if(r!==void 0){let n=m(e,r);return I(n)?n:void 0}for(let n of pe)for(let o of ge){let i=m(e,`${n}.config.${o}`);if(I(i))return i}}function tt(e){for(let t of pe)if(ge.some(r=>I(m(e,`${t}.config.${r}`))))return t;return"helix"}function rt(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=h(t?.configFile);return{name:tt(e),cwd:e,...r!==void 0?{configFile:rt(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function A(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Ye.safeParse(e);if(!r.success){let f=r.error.issues.map(l=>l.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=h(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!I(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Xe(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=fe(o);if(fe(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return A(i.config,d)}var me="WORKSPACE_ID_REQUIRED";function nt(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:me});return e.workspaceId}import{existsSync as ot,watch as it,writeSync as st}from"fs";import{basename as at,dirname as dt,join as ct,resolve as T}from"path";import{watchConfig as ut}from"c12";function ft(e,t){let r=e instanceof Error?e.message:String(e);st(2,`[helix-watch] ${t.phase} error: ${r}
2
+ `)}function H(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var lt=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,he=new Set;function ye(e,t){return b(e,{configFile:t})!==void 0}async function pt(e,t,r){if(ye(e.cwd,t))try{return{current:await k(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:H(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?T(e.cwd,t):T(e.cwd);he.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${T(e.cwd,t)} not found; tray running with default config
3
3
  `:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
4
- `),me.add(n))}return{current:A(),initialLoadSucceeded:!1}}var W=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=dt({...D(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=H(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,i)=>{n.once("ready",o),n.once("error",i)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?T(this.cwd,this.configFile):void 0,r=t!==void 0?st(t):this.cwd;try{this.directoryWatcher=nt(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let i=o.toString();if(t!==void 0){if(i!==it(t))return}else if(!ut.test(i))return;rt(at(r,i))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await k(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function lt(e){let t=e.onError??ct,r=new Set,n=C(e.configFile),o=await ft(e,n,t),i=o.current;function d(a){i=a;for(let f of[...r])try{f(a)}catch(p){t(p,{phase:"reload"})}}let s=new W(e.cwd,n,t,d);return e.watch&&s.start(o.initialLoadSucceeded),{get(){return i},async reload(){if(!he(e.cwd,n)){let a=A();return d(a),a}try{let a=await k(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),i}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await s.stop()},ready(){return s.watcherReady()}}}export{Ge as ENVIRONMENT_VALUES,j as HELIX_CONFIG_ENV,Ee as SCHEDULE_DEFINITION_KIND,we as ScheduleConfigError,ge as WORKSPACE_ID_REQUIRED_CODE,lt as createConfigService,Ve as defineConfig,Ae as defineFunction,ke as defineSchedule,I as environmentSchema,ve as getContext,R as getSdkConfig,Se as isScheduleDefinition,k as loadConfig,Xe as loadedTrayConfigSchema,L as projectIdSchema,tt as requireWorkspaceId,b as resolveConfigFile,C as resolveConfigOverride,Ce as runWithinAppSpan,O as workspaceIdSchema};
4
+ `),he.add(n))}return{current:H(),initialLoadSucceeded:!1}}var W=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=ut({...D(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=A(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,i)=>{n.once("ready",o),n.once("error",i)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?T(this.cwd,this.configFile):void 0,r=t!==void 0?dt(t):this.cwd;try{this.directoryWatcher=it(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let i=o.toString();if(t!==void 0){if(i!==at(t))return}else if(!lt.test(i))return;ot(ct(r,i))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await k(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function gt(e){let t=e.onError??ft,r=new Set,n=h(e.configFile),o=await pt(e,n,t),i=o.current;function d(a){i=a;for(let f of[...r])try{f(a)}catch(l){t(l,{phase:"reload"})}}let s=new W(e.cwd,n,t,d);return e.watch&&s.start(o.initialLoadSucceeded),{get(){return i},async reload(){if(!ye(e.cwd,n)){let a=H();return d(a),a}try{let a=await k(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),i}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await s.stop()},ready(){return s.watcherReady()}}}export{Qe as ENVIRONMENT_VALUES,j as HELIX_CONFIG_ENV,ke as SCHEDULE_DEFINITION_KIND,Se as ScheduleConfigError,me as WORKSPACE_ID_REQUIRED_CODE,gt as createConfigService,Ge as defineConfig,Ne as defineFunction,xe as defineSchedule,_ as environmentSchema,we as getContext,R as getSdkConfig,_e as isScheduleDefinition,k as loadConfig,et as loadedTrayConfigSchema,L as projectIdSchema,nt as requireWorkspaceId,b as resolveConfigFile,h as resolveConfigOverride,Ee as runWithinAppSpan,O as workspaceIdSchema};
@@ -1,5 +1,5 @@
1
- import { L as LoadedTrayConfig } from '../sdk-config-vY_-Reh3.js';
2
- export { f as SdkConfigInput, s as setSdkConfig } from '../sdk-config-vY_-Reh3.js';
1
+ import { L as LoadedTrayConfig } from '../sdk-config-DU6cWbLW.js';
2
+ export { f as SdkConfigInput, s as setSdkConfig } from '../sdk-config-DU6cWbLW.js';
3
3
  import 'zod';
4
4
 
5
5
  /** BroadcastChannel name for parent→worker config updates. */
@@ -126,6 +126,20 @@ type SdkErrorDetail = {
126
126
  body?: string;
127
127
  } | {
128
128
  readonly kind: "files_requires_provisioning";
129
+ } | {
130
+ readonly kind: "call_function_path_invalid";
131
+ message: string;
132
+ } | {
133
+ readonly kind: "call_function_call_failed";
134
+ status: number;
135
+ message: string;
136
+ body?: string;
137
+ } | {
138
+ readonly kind: "call_function_requires_provisioning";
139
+ } | {
140
+ readonly kind: "call_function_not_available";
141
+ } | {
142
+ readonly kind: "call_function_missing_execution_jwt";
129
143
  };
130
144
  declare class SdkError extends Error {
131
145
  readonly detail: SdkErrorDetail;
@@ -156,6 +170,11 @@ declare class SdkError extends Error {
156
170
  static filesNotAvailable(): SdkError;
157
171
  static filesCallFailed(status: number, message: string, body?: string): SdkError;
158
172
  static filesRequiresProvisioning(): SdkError;
173
+ static callFunctionPathInvalid(message: string): SdkError;
174
+ static callFunctionCallFailed(status: number, message: string, body?: string): SdkError;
175
+ static callFunctionRequiresProvisioning(): SdkError;
176
+ static callFunctionNotAvailable(): SdkError;
177
+ static callFunctionMissingExecutionJwt(): SdkError;
159
178
  }
160
179
  declare function isSdkError(err: unknown): err is SdkError;
161
180
 
@@ -1 +1 @@
1
- import{C as N,a as H,b as m,c as L,d as T,e as G,f as J,g as U,h,i as p,j as g,k as E,l as S,m as x,n as y,o as A,q as w,r as I,s as C,t as v,u as D,v as oe,w as ne,x as se,y as F}from"../chunk-X4MA45FS.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as B,c as q,d as z,e as Q,f as W,g as X,h as Y,i as Z,j as ee,k as te,m as re}from"../chunk-D5GPRK2D.js";import{randomUUID as ie}from"crypto";import{SpanStatusCode as P,SpanKind as ae}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function le(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new t("`isManual` must be a boolean");if(!N(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let k=O("scheduledAt",e.scheduledAt),M=O("firedAt",e.firedAt),d=m(),a=d.executionId??ie(),l=d.deploymentId??null,R=Date.now(),j=new Date().toISOString(),$=I(),K=w();S();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ae.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let _={type:"schedule",scheduledAt:k,firedAt:M,isManual:e.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:_};E(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?P.ERROR:P.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:j,startMs:R,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function O(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{L as CONFIG_BRIDGE_CHANNEL,T as DEV_TOKEN_BRIDGE_CHANNEL,t as ScheduleInvocationError,oe as assertValidPath,U as clearActiveConfig,ne as contentFilePath,J as getActiveConfig,ee as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,B as isKnownEnvironment,re as isSdkError,Q as listEnvironmentNames,W as listExposedEnvNames,se as metaFilePath,X as parseExposedEnvironment,V as registerEnvironmentProfile,z as requireEnvironmentProfile,te as resetEnvironmentRegistryForTests,Z as resolveForcedEnvironment,le as runScheduledFunction,G as setActiveConfig,Y as setForcedEnvironment,H as setSdkConfig};
1
+ import{D as P,a as L,b as m,c as T,d as G,e as J,f as U,g as V,h,i as p,j as g,k as E,l as S,m as y,n as x,o as A,q as I,r as w,s as C,t as v,u as D,v as nt,w as st,x as it,y as F,z as N}from"../chunk-QWCCRTLO.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as B,b as q,c as z,d as Q,e as W,f as X,g as Y,h as Z,i as tt,j as et,k as rt,m as ot}from"../chunk-KUXDW5ED.js";import{randomUUID as at}from"crypto";import{SpanStatusCode as O,SpanKind as lt}from"@opentelemetry/api";var e=class extends Error{constructor(t){super(`runScheduledFunction: ${t}`),this.name="ScheduleInvocationError"}};async function ct(s,t){if(typeof t!="object"||t===null)throw new e("`invocation` must be an object");let{schedulePath:r}=t;if(typeof r!="string"||r.length===0)throw new e("`schedulePath` must be a non-empty string");if(typeof t.isManual!="boolean")throw new e("`isManual` must be a boolean");if(!P(s))throw new e(`default export of "${r}" is not a defineSchedule definition`);let M=k("scheduledAt",t.scheduledAt),R=k("firedAt",t.firedAt),d=m(),a=d.executionId??at(),l=d.deploymentId??null,j=Date.now(),$=new Date().toISOString(),K=w(),_=I();S();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>x.startActiveSpan("schedule",{root:!0,kind:lt.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let H={type:"schedule",scheduledAt:M,firedAt:R,isManual:t.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),callFunctionAsync:N(),log:_,config:K,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,parentExecutionId:null,trigger:H};E(o,"input",{scheduledAt:t.scheduledAt,firedAt:t.firedAt,isManual:t.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?O.ERROR:O.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:$,startMs:j,errored:c,errorMessage:u,userId:null,flags:i}),await y()}}function k(s,t){if(typeof t!="string"||t.length===0)throw new e(`\`${s}\` must be a timestamp string; got ${JSON.stringify(t)}`);let r=new Date(t);if(Number.isNaN(r.getTime()))throw new e(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(t)}`);return r}export{T as CONFIG_BRIDGE_CHANNEL,G as DEV_TOKEN_BRIDGE_CHANNEL,e as ScheduleInvocationError,nt as assertValidPath,V as clearActiveConfig,st as contentFilePath,U as getActiveConfig,et as getAdditionalEnvironmentProfiles,z as getEnvironmentProfile,q as isKnownEnvironment,ot as isSdkError,W as listEnvironmentNames,X as listExposedEnvNames,it as metaFilePath,Y as parseExposedEnvironment,B as registerEnvironmentProfile,Q as requireEnvironmentProfile,rt as resetEnvironmentRegistryForTests,tt as resolveForcedEnvironment,ct as runScheduledFunction,J as setActiveConfig,Z as setForcedEnvironment,L as setSdkConfig};
@@ -196,6 +196,13 @@ interface SdkRuntimeConfig {
196
196
  * resolve `.helix/files/` on disk. Absent in `lambda` mode.
197
197
  */
198
198
  projectRoot?: string;
199
+ /**
200
+ * The calling execution's id, set via `setSdkConfig(...)` only for a
201
+ * function-call-triggered invocation (`ctx.callFunctionAsync`, SUR-929).
202
+ * The shim explicitly clears this (passes `undefined`) on every other
203
+ * invocation kind so a warm container never leaks a prior call's parentage.
204
+ */
205
+ parentExecutionId?: string | null;
199
206
  }
200
207
  interface BrokerSecrets {
201
208
  internalJwt?: string;
@@ -1,4 +1,4 @@
1
- import { P as PlatformContext } from '../types-DqH1HJU0.js';
1
+ import { P as PlatformContext } from '../types-DoNQWbb9.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
@@ -1 +1 @@
1
- import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,i){let u=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(u,i)}export{l as runWithContext};
1
+ import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,callFunctionAsync:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0,parentExecutionId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,u){let i=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(i,u)}export{l as runWithContext};
@@ -111,6 +111,13 @@ interface FileSystemClient {
111
111
  head(path: string): Promise<FileMetadata | null>;
112
112
  }
113
113
 
114
+ /**
115
+ * Fire-and-forget: queues `functionPath` for a new, independent project
116
+ * execution and resolves once the queueing call is accepted — it never waits
117
+ * for the target function to run or reports its outcome back.
118
+ */
119
+ type CallFunctionAsync = (functionPath: string, input?: unknown) => Promise<void>;
120
+
114
121
  interface Logger {
115
122
  info(message: string, data?: Record<string, unknown>): void;
116
123
  warn(message: string, data?: Record<string, unknown>): void;
@@ -190,12 +197,24 @@ interface ContextCore {
190
197
  db(alias: string): DbClient;
191
198
  kv(): KeyValueStore;
192
199
  files(): FileSystemClient;
200
+ /**
201
+ * Fire-and-forget: queues `functionPath` to run as a new, independent
202
+ * project execution and resolves once it's queued — never waits for (or
203
+ * reports) that execution's outcome.
204
+ */
205
+ callFunctionAsync: CallFunctionAsync;
193
206
  log: Logger;
194
207
  config: Record<string, unknown>;
195
208
  state: Record<string, unknown>;
196
209
  executionId: string;
197
210
  deploymentId: string | null;
198
211
  traceId: string;
212
+ /**
213
+ * The calling execution's id, for a run started via `ctx.callFunctionAsync`
214
+ * (the target's audit/trace link back to its caller). Null for every other
215
+ * execution kind (HTTP request, schedule fire) — nothing "called" them.
216
+ */
217
+ parentExecutionId: string | null;
199
218
  }
200
219
  interface TrayContext<T = Record<string, unknown>> extends ContextCore {
201
220
  input: T;
@@ -302,4 +321,4 @@ interface ScheduleDefinition {
302
321
  handler: ScheduleHandler;
303
322
  }
304
323
 
305
- export type { BrokerAuthedClient as B, DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, BrokerCallOptions as b, BrokerCallResult as c, DbCallParameters as d, DbClient as e, FileSystemClient as f, S3SignOptions as g, S3SignResult as h, ScheduleContext as i, ScheduleHandler as j, ScheduleTrigger as k, SqlBuilder as l };
324
+ export type { BrokerAuthedClient as B, CallFunctionAsync as C, DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, BrokerCallOptions as b, BrokerCallResult as c, DbCallParameters as d, DbClient as e, FileSystemClient as f, S3SignOptions as g, S3SignResult as h, ScheduleContext as i, ScheduleHandler as j, ScheduleTrigger as k, SqlBuilder as l };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.111.0",
3
+ "version": "0.112.1",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -46,10 +46,10 @@
46
46
  "@opentelemetry/core": ">=2.8.0 <3",
47
47
  "@opentelemetry/exporter-logs-otlp-proto": "0.220.0",
48
48
  "@opentelemetry/exporter-trace-otlp-proto": "0.220.0",
49
- "@opentelemetry/resources": "^2.10.0",
49
+ "@opentelemetry/resources": "^2.11.0",
50
50
  "@opentelemetry/sdk-logs": "0.220.0",
51
- "@opentelemetry/sdk-trace-base": "^2.10.0",
52
- "@opentelemetry/sdk-trace-node": "^2.10.0",
51
+ "@opentelemetry/sdk-trace-base": "^2.11.0",
52
+ "@opentelemetry/sdk-trace-node": "^2.11.0",
53
53
  "c12": "^3.3.4",
54
54
  "chokidar": "^5.0.0",
55
55
  "h3": "^1.15.11",
@@ -62,8 +62,8 @@
62
62
  "eslint": "^9.39.5",
63
63
  "tsup": "^8.5.1",
64
64
  "typescript": "^5.9.3",
65
- "typescript-eslint": "^8.65.0",
66
- "vitest": "^4.1.10"
65
+ "typescript-eslint": "^8.69.0",
66
+ "vitest": "^4.1.11"
67
67
  },
68
68
  "scripts": {
69
69
  "build": "tsup",
@@ -1 +0,0 @@
1
- var R=new Set(["production"]),a=new Map,g={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};a.set(g.name,g);var E=["api","broker","ingest","weaver","app","projectHost","dashboard"],x=["auth"],b=["storePrefix","appUrl","cookieName","cookieDomain"];function P(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let r of E)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string`);for(let r of x){let n=e.hosts[r];if(n!==void 0&&(typeof n!="string"||!n))throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string when set`)}for(let r of b)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`EnvironmentProfile.login.${r} must be a non-empty string`)}function I(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&E.every(n=>e.hosts[n]===r.hosts[n])&&x.every(n=>e.hosts[n]===r.hosts[n])&&b.every(n=>e.login[n]===r.login[n])}function V(e){P(e);let r=a.get(e.name);if(r){if(I(r,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let n of a.values())if(n.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${n.name}"`);a.set(e.name,e)}function N(e){return a.has(e)}function G(e){return a.get(e)}function y(e){let r=a.get(e);if(!r)throw new Error(`Unknown environment: ${e}`);return r}function J(){return[...a.keys()]}function Y(){return[...a.values()].map(e=>e.exposedName)}function T(e){for(let r of a.values())if(r.exposedName===e)return r.name}var p=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function D(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[p];return}let n=e.trim(),t=T(n);if(t){r[p]=t;return}if(N(n)){r[p]=n;return}throw new Error(`Unknown environment: ${n}`)}function z(){return globalThis[p]}function X(){return[...a.values()].filter(e=>!R.has(e.name))}function Q(){D(void 0),a.clear(),a.set(g.name,{...g,hosts:{...g.hosts},login:{...g.login}})}var u=class e extends Error{detail;constructor(r){super(U(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,t,o){return new e({kind:"broker_error",status:r,message:n,body:t,code:o})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvTtlInvalid(r){return new e({kind:"kv_ttl_invalid",message:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,t){return new e({kind:"kv_call_failed",status:r,message:n,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,t){return new e({kind:"files_call_failed",status:r,message:n,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function Z(e){return e instanceof u}function U(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}import{z as f}from"zod";var w="x-helix-destination-url",S="x-helix-authentication-id",O="x-helix-deployment-id",v="x-execution-id",A="x-helix-broker-error",oe="route_not_found",$=new Set([w,S,O,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",v]);function q(e){let r=e.toLowerCase();return $.has(r)||r.startsWith("x-tray-internal-")}var _=f.object({error:f.object({code:f.string(),message:f.string(),issues:f.array(f.unknown()).optional()})});function ie(e,r){let n=`${y(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${n}/dev`:n}function H(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function se(e){let r=new URL(e.url);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[s,i]of e.query.entries())r.searchParams.append(s,i);else for(let[s,i]of Object.entries(e.query))for(let m of Array.isArray(i)?i:[i])r.searchParams.append(s,m);let n;e.headers===void 0?n=[]:e.headers instanceof Headers?n=Array.from(e.headers.entries()):Array.isArray(e.headers)?n=e.headers:n=Object.entries(e.headers);let t=n.filter(([s])=>!q(s)),o=e.body!==void 0&&e.body!==null,d,l,c=!1;return o&&(H(e.body)?(d=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([i])=>i.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:t,body:d,isStreamBody:c,defaultContentType:l}}var B=6e4;function C(e){return e.includes("json")}function j(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function L(e,r){if(e.byteLength===0)return;let n=r.toLowerCase();if(C(n)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return j(n)?new TextDecoder("utf-8").decode(e):e}function F(e){let r={};for(let[n,t]of e.entries())r[n.toLowerCase()]=t;return r}async function ae(e){let{request:r}=e,n=new Headers;for(let[s,i]of r.headers)n.append(s,i);r.defaultContentType&&!n.has("content-type")&&n.set("content-type",r.defaultContentType),n.set(w,r.destinationUrl),n.set(S,r.authenticationId);for(let[s,i]of Object.entries(e.credentialHeaders))n.set(s,i);e.executionId&&n.set(v,e.executionId);let t={method:r.method,headers:n,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??B)};r.body!==void 0&&(t.body=r.body,r.isStreamBody&&(t.duplex="half"));let o=await fetch(e.proxyUrl,t),d=o.headers.get(A);if(d!==null){let s=await o.text(),i=s,m=s||d;try{i=JSON.parse(s);let h=_.safeParse(i);h.success&&(m=h.data.error.message)}catch{}return{kind:"brokerError",status:o.status,code:d,message:m,body:i}}let l=new Uint8Array(await o.arrayBuffer()),c=o.headers.get("content-type")??"";return{kind:"upstream",response:{status:o.status,headers:F(o.headers),body:L(l,c)}}}import{z as k}from"zod";var M=3e4;function fe(e){let r=new URL(e);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""))}function me(e,r){let n=`${y(e).hosts.api}/private/v1/helix/broker/s3/sign`;return r==="dev"?`${n}/dev`:n}var K=k.object({url:k.string(),method:k.string(),expiresAt:k.string()});async function pe(e){let r=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))r.set(l,c);e.executionId&&r.set(v,e.executionId);let n=await fetch(e.signUrl,{method:"POST",headers:r,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??M)}),t=await n.text(),o=t;try{o=JSON.parse(t)}catch{}if(n.ok){let l=K.safeParse(o);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:n.status,message:"malformed s3-sign response from credential broker",body:o}}let d=_.safeParse(o);return d.success?{kind:"brokerError",status:n.status,code:d.data.error.code,message:d.data.error.message,body:o}:{kind:"brokerError",status:n.status,message:t||`s3-sign request failed with status ${n.status}`,body:o}}export{V as a,N as b,G as c,y as d,J as e,Y as f,T as g,D as h,z as i,X as j,Q as k,u as l,Z as m,O as n,oe as o,ie as p,se as q,B as r,ae as s,fe as t,me as u,pe as v};
@@ -1,7 +0,0 @@
1
- import{d as _,l as c,n as tt,o as se,p as Ce,q as V,s as rt,t as nt,u as Ae,v as ot}from"./chunk-D5GPRK2D.js";var E="X-Helix-Project-Execution-Token",P="X-Tray-Token",xr={mode:"dev",deploymentId:null},ke={...xr},F={};function wo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(F.internalJwt=t),"helixExecutionJwt"in e&&(F.helixExecutionJwt=r),"devToken"in e&&(F.devToken=n),ke={...ke,...o}}function w(){return ke}function I(){return F.internalJwt}function v(){return F.helixExecutionJwt}function ae(){return F.devToken}var So="tray-config-bridge",xo="tray-dev-token-bridge",ce=null;function Eo(e){ce=e}function b(){if(!ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ce}function vo(){ce=null}import{AsyncLocalStorage as Rt}from"async_hooks";import{trace as Nr,SpanKind as Lr,SpanStatusCode as _e}from"@opentelemetry/api";import{ExportResultCode as Br,W3CTraceContextPropagator as Mr}from"@opentelemetry/core";import{NodeTracerProvider as Ur,SimpleSpanProcessor as jr,BatchSpanProcessor as Kr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Er}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as vr}from"@opentelemetry/exporter-logs-otlp-proto";function De(e){return _(e).hosts.ingest}function Rr(){return v()??""}function it(){return{[E]:Rr()}}function st(){let e=De(b().env);return new Er({url:`${e}/v1/traces`,headers:()=>Promise.resolve(it())})}function at(){let e=De(b().env);return new vr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(it())})}import{logs as ut,SeverityNumber as le}from"@opentelemetry/api-logs";import{LoggerProvider as Ir,BatchLogRecordProcessor as Cr}from"@opentelemetry/sdk-logs";function J(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Tr(e){return new TextEncoder().encode(e).length}var ct="\u2026[truncated]",Pr=Tr(ct),z=4096;function D(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Pr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+ct}function g(e,t=z){return D(J(e),t)}var Ar="@trayai/helix-sdk",q,lt={debug:{number:le.DEBUG,text:"DEBUG"},info:{number:le.INFO,text:"INFO"},warn:{number:le.WARN,text:"WARN"},error:{number:le.ERROR,text:"ERROR"}};function kr(){return w().mode==="lambda"?[new Cr({exporter:at()})]:[]}function dt(){if(q!==void 0)return;let e=kr();e.length!==0&&(q=new Ir({processors:e}),ut.setGlobalLoggerProvider(q))}function Dr(e,t,r){let n=lt[e]??lt.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function ft(e,t,r){ut.getLogger(Ar).emit(Dr(e,t,r))}async function mt(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
- `)}finally{t!==void 0&&clearTimeout(t)}}function Oe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Or(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function R(e,t){return Or()?`\x1B[${e}m${t}\x1B[0m`:t}var _r=5,Fr={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},pt="32",gt="31",ue="2",yt="1";function de(e){return R(Fr[e]??"0",e.padEnd(_r))}function ht(e,t){return`${de("FN")} ${R(yt,`${e} ${t}`.trim())}`}function wt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${R(ue,n)} `:""}${de(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${R(ue,J(r))}`),s}function bt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function St(e){return`${de("AUTH")} ${e}`}function xt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=R(o==="error"?gt:pt,i);return`${de("API")} ${e} ${t} \u2192 ${s} ${R(ue,`${n}ms`)}`}function Et(e,t,r){let n=t?gt:pt,o=R(n,"\u25CF"),i=R(n,t?"error":"success");return`${o} ${R(yt,e)} ${i} ${R(ue,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Tt=new Rt,$r=new Rt;function S(e){let t=$r.getStore();t&&(t[e]=!0)}var Hr=/^[0-9a-f]{32}$/;function Vr(e){let t=e.replace(/-/g,"").toLowerCase();return Hr.test(t)?t:null}var Jr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},L=new Map;function Pt(e,t,r){let n=L.get(e);n?n[t]=r:L.set(e,{[t]:r})}function T(e,t,r){e.setAttribute(t,g(r))}var Y;function vt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function zr(e){return Math.round(e[0]*1e3+e[1]/1e6)}function It(e){try{process.stdout.write(J(e)+`
4
- `)}catch{}}var Fe=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=L.get(o),s={...n.attributes};if(i!==void 0){for(let[u,d]of Object.entries(i))typeof d=="string"?s[u]=D(d):typeof d=="object"&&d!==null?s[u]=g(d):s[u]=d;L.delete(o)}let a=Tt.getStore(),l=a?Vr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:vt(n.startTime),endTimeUnixNano:vt(n.endTime),attributes:s,status:{code:Jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:D(n.status.message)}:{}}})}r({code:Br.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t,r){}onEnd(t){L.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
- `+ht(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=L.get(n)?.properties;N(wt(String(r.level??"info"),String(r.message??""),o,bt(t.startTime)));break}case"auth":N(St(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(xt(String(r.method??""),String(r.host??""),n,zr(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Be=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function qr(){let t=[Oe()?new Le:new jr(new Fe)];return w().mode==="lambda"&&t.push(new Be(new Kr(st()))),t.push(new Ne),t}function Yr(){Y===void 0&&(Y=new Ur({spanProcessors:qr()}),Y.register({propagator:new Mr}),dt())}async function Xr(e=2e3){let t=[mt(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
- `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var x=Nr.getTracer("@trayai/helix-sdk");function Gr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-i;if(Oe()){N(`
7
- `+Et(n,s,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?D(a):null})}async function Wo(e,t){let r=e.startMs??Date.now();Yr();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>x.startActiveSpan("App",{kind:Lr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?_e.ERROR:_e.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:_e.ERROR,message:o}),s}finally{i.end()}}))}finally{Gr({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await Xr()}}var kt=1024,C=100*1024*1024,Ct=250,Wr=3600,Qr=Wr*1e3,At=new TextEncoder,Zr=/(^|\/)\.\.(\/|$)/,en=/[?#]/;function tn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=kt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Me(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=kt){if(e.length===0)return;if(Zr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(en.test(e)||tn(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=At.encode(o).length;if(i>Ct)throw c.filesPathInvalid(`Path segment exceeds ${Ct} UTF-8 bytes (got ${i})`)}let n=At.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Dt(e){if(e>C)throw c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got ${e})`,C)}function B(e){let t=e!==void 0?e*1e3:Qr;return new Date(Date.now()+t)}import{join as G}from"path";var rn="files",nn="files-meta",on=1023,sn=1,an=5;function Ot(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,on-t-sn-an)}function me(e){return G(e,".helix",rn)}function X(e){return G(e,".helix",nn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function _t(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Ft="helix-schedule",A=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ni(e){if(typeof e!="object"||e===null)throw new A("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new A("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new A(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!cn(r))throw new A(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new A("`concurrent` must be a boolean");if(typeof o!="function")throw new A("`handler` must be a function");return Object.freeze({kind:Ft,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function oi(e){return typeof e=="object"&&e!==null&&e.kind===Ft&&typeof e.handler=="function"}function cn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as ln}from"@opentelemetry/api";function ye(e,t,r){let n=x.startSpan("log",{kind:ln.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),ft(e,t,r)}function li(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function fi(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import un from"ky";import{context as Ue,trace as dn,SpanKind as Z,SpanStatusCode as Lt}from"@opentelemetry/api";async function he(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(i[P]=a),d&&(i[E]=l),r.deploymentId&&(i[tt]=r.deploymentId),o=Ce(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Ce(n,"dev")}let s;try{s=await rt({proxyUrl:o,credentialHeaders:i,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===se?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.response}async function Nt(e){nt(e.url);let t=w(),{env:r}=b(),n,o={},i={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[E]=l),t.deploymentId&&(i.deploymentId=t.deploymentId),n=Ae(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=Ae(r,"dev")}let s;try{s=await ot({signUrl:n,credentialHeaders:o,body:i,timeoutMs:e.timeout,executionId:t.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.result}var fn=["get","post","put","patch","delete","head","options"],Mt="[stream body omitted]";function Ut(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Mt:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function je(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n,o){let i=je(t),s="externalApi",a={kind:Z.CLIENT};return x.startActiveSpan(s,a,async l=>(l.setAttributes({method:e,host:i,"peer.service":n}),T(l,"request",{url:t,method:e,...r!==void 0?{body:Ut(r)}:{}}),o(l)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Lt.OK}:{code:Lt.ERROR,message:r}),e.end()}var mn=16;async function pn(e,t){let r=e.clone().body;return r?jt(r,t):new Uint8Array(0)}async function jt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=mn)break;continue}i=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Kt(e,t,r){if("kyResponse"in r)try{let n=await pn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",Ut(r.bodyValue))}async function gn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await jt(o,z);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Mt}}}return typeof t=="string"?{body:t}:{}}function Bi(){let e=un.create({});function t(n){return(o,i)=>{let s=Ue.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await gn(f,m.body),ie=p.body;if(a||(a=x.startSpan("externalApi",{kind:Z.CLIENT},s)),a.setAttributes({method:f.method.toUpperCase(),host:je(f.url)}),T(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,S("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Kt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(S("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(S("hasError"),u("error",f.message),f)]}});return a=x.startSpan("externalApi",{kind:Z.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:je(String(o))}),Ue.with(dn.setSpan(Ue.active(),a),()=>{let f=n==="options"?d(o,{...i,method:"OPTIONS"}):d[n](o,i);return f.catch(m=>{S("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(fn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return yn(n)}}}function yn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return Bt(u,a,l.body,e,async d=>{S("hasAuth");let f=x.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=V({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Kt(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw S("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function i(s,a={}){let l=a.method??"GET";return Bt(l,s,void 0,e,async u=>{S("hasAuth");let d=x.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Nt({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw S("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as Tn,SpanStatusCode as Jt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var hn=18e4,$t=hn-1e4,wn=2e3;async function Ht(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<$t;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(wn,200*2**i),u=l/2+Math.random()*(l/2),d=$t-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var bn=new Set(["SELECT","WITH","SHOW"]),Sn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function xn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function En(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?D(t):g(t);return c.dbCallFailed(i)}function vn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Rn(e,t){return typeof t!="number"||t<0?{}:bn.has(e)?{rowsRead:t}:Sn.has(e)?{rowsWritten:t}:{}}function Vt(e){async function t(r,n,o){let i=V({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await he(i);if(s>=400)throw En(s,a);return vn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:xn,async execute(r,n){let o=ee(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Ht(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Rn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var Ke=64*1024;function Pn(e){return e.length>Ke?`${e.slice(0,Ke)}...[truncated]`:e}function In(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Cn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Ke?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function An(e,t,r){let n=ee(r),o=Pn(r);return x.startActiveSpan("database",{kind:Tn.CLIENT},async i=>{In(i,e,t,n,o);try{S("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Cn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Jt.OK}),l}catch(s){S("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:Jt.ERROR,message:a}),s}finally{i.end()}})}function kn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Vt(n);function i(s,a){return o.validate(s),An(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Nn}from"unstorage";var zt=1024,$e=250*1024,Dn=new TextEncoder,On=/(^|\/)\.\.(\/|$)/,_n=/[?#]/,Fn=/[\u0000-\u001F\u007F]/;function qt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(On.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(_n.test(e)||Fn.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Dn.encode(e).length;if(t<1||t>zt)throw c.kvKeyInvalid(`Key must be between 1 and ${zt} UTF-8 bytes (got ${t})`)}function Yt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Xt(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>$e)throw c.kvValueTooLarge(`Value exceeds maximum size of ${$e} bytes (got ${r})`,$e)}function te(e){qt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Gt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return te(s),t(s,a)},setItem(s,a,l){return te(s),r(s,a,l)},removeItem(s,a){return te(s),n(s,a)},hasItem(s,a){return te(s),o(s,a)},getKeys(s,a){return s.length>0&&te(s),i(s,a)}}}function be(e){return Nn({driver:Gt(e)})}import{defineDriver as Ln}from"unstorage";function Bn(e){try{return JSON.parse(e)}catch{return e}}var Mn=Ln(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Bn(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Wt(e){return Mn({client:e})}import Kn from"ky";import{z as h}from"zod";async function M(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function Qt(e){return _(e).hosts.api}function Un(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function jn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${Un(t)}/${jn(r)}`}var $n=6e4,He=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(He),h.record(He)])),Hn=h.object({projectId:h.string(),key:h.string(),value:He,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function Vn(){let e=I(),t=v(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[E]=t),o}function Jn(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,Jn(t),g(t))}async function xe(e,t,r={}){try{let n=await Kn(t,{method:e,headers:Vn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:$n}),o=e==="head"?void 0:await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function Zt(e){let t=Qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await xe("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,i);let s=Hn.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await xe("put",re(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&Se(s,a)},async delete(n){let{status:o,body:i}=await xe("delete",re(t,r,n));o!==204&&Se(o,i)},async has(n){let{status:o,body:i}=await xe("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,i)}}}function Ee(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Xt(r),typeof o=="number"&&Yt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function zn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function er(e){let t=zn(),r=e??Zt(t),n=be(Wt(r));return Ee(n)}import{defineDriver as qn}from"unstorage";var Yn=qn(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl,a=r(n),l=typeof s=="number"?Date.now()+s*1e3:s===null?void 0:a?.expiresAt;t.set(n,{value:o,expiresAt:l})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function tr(){return Yn({})}var Ve;function Xn(){return Ve||(Ve=be(tr())),Ve}function rr(){return Ee(Xn())}function Gn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function $s(){return Gn()?er():rr()}import{createHash as Zn}from"crypto";import{mkdir as eo,readFile as ar,readdir as cr,rm as or,unlink as to,writeFile as ir}from"fs/promises";import{dirname as ro}from"path";async function Wn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>C)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got more than ${C})`,C);r.push(i)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Wn(e):Buffer.from(e)}var Qn={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},nr="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return nr;let r=e.slice(t+1).toLowerCase();return Qn[r]??nr}function K(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Je(e){try{let t=await ar(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function sr(e){await eo(ro(e),{recursive:!0})}async function no(e,t){let r=ge(e,t),n;try{n=await cr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function lr(e,t){let r=ge(e,t),n;try{n=await cr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await lr(e,s)):i.isFile()&&o.push(s)}return o}function ur(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await U(t),i=r?.contentType??ve(e),s=Zn("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await sr(l),await ir(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},d=pe(n,e);return await sr(d),await ir(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await Je(e);return t?{data:await ar(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await Je(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await to(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await lr(t,e);return await Promise.all([or(ge(t,e),{recursive:!0,force:!0}),or(_t(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,i=(await no(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Je(a);return l?Re(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}}}}import{createHash as uo}from"crypto";function Te(e){return _(e).hosts.api}function oo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${oo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Pe(e,t,r){return`${$(e,t,r)}/upload`}function dr(e,t,r){return`${$(e,t,r)}/download`}function fr(e,t,r){return`${$(e,t,r)}/signed-url`}function mr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function pr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import qe from"ky";import{z as y}from"zod";var Ye=6e4,gr=y.object({id:y.string(),workspaceId:y.string(),projectId:y.string(),parentFolder:y.string().nullable().optional(),name:y.string(),size:y.number().nullable().optional(),objectType:y.enum(["Folder","File"]),contentType:y.string().nullable().optional(),createdAt:y.string(),updatedAt:y.string()}),io=y.object({signedURL:y.string()}),so=y.object({path:y.array(y.object({id:y.string(),name:y.string()})),elements:y.array(gr)});function Xe(){let e=I(),t=v(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[E]=t),o}function yr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function k(e,t){throw c.filesCallFailed(e,yr(t),g(t))}function ao(e,t){return e===400&&yr(t).toLowerCase()==="resource not found"}async function co(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await qe(t,{method:e,headers:Xe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ye}),o=await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function ze(e,t){let r=gr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function hr(e){let t=Te(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&k(o,i),ze(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",mr(t,r,n,o));return i===404||ao(i,s)?null:((i<200||i>=300)&&k(i,s),ze(i,s))},async getById(n){let{status:o,body:i}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&k(o,i),ze(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",pr(t,r,n,o));(i<200||i>=300)&&k(i,s);let a=so.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",g(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await co(a),d;try{d=await qe(Pe(t,r,n),{method:"post",headers:{...Xe(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Ye})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await M(d);(d.status<200||d.status>=300)&&k(d.status,f)},async downloadContent(n){let o;try{o=await qe(dr(t,r,n),{method:"get",headers:Xe(),throwHttpErrors:!1,timeout:Ye})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await M(o);k(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",fr(t,r,n));(o<200||o>=300)&&k(o,i);let s=io.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&k(o,i)}}}function Ge(e){return e.split("/").filter(t=>t.length>0)}function We(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function lo(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Qe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await lo(e,o,i)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function Ze(e,t){if(t.length===0)return;let r=Ge(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var fo=500,mo=8;async function po(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function go(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function yo(e){return uo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Ie(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:yo(t)}}async function wr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function br(e,t){let{elements:r}=await e.listChildren(t,fo);return(await po(r,mo,async o=>{let i=o.objectType==="Folder"?await br(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function Sr(e){let t=go(),r=e??hr(t),n=Te(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Qe(r,i),d=await U(s),f=a?.contentType??ve(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await wr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Ie(i,ie??p,f)},async get(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Ie(i,a)}},async head(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Ie(i,a)},async delete(i){let s=await oe(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await Ze(r,i);if(s===null)return{deleted:0};let a=await br(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Ze(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Ie(i?`${i}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Qe(r,i),d=await r.getByName(a,l)??await wr(r,a,l,s?.contentType);return{url:Pe(n,o,d.id),expiresAt:B(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await oe(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:B(s?.expiresIn)}}}}function et(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){O(n,r);let s=await U(o);return Dt(s.byteLength),e.put(n,s,i)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Me(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let i=Me(n??"");return fe(i,r),e.list(i,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function ho(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Fa(){if(ho())return et(Sr());let e=w().projectRoot;return et(ur(),{maxPathBytes:e?Ot(e):void 0})}export{wo as a,w as b,So as c,xo as d,Eo as e,b as f,vo as g,Tt as h,$r as i,S as j,T as k,Yr as l,Xr as m,x as n,Gr as o,Wo as p,li as q,fi as r,Bi as s,kn as t,$s as u,O as v,W as w,pe as x,Fa as y,Ft as z,A,ni as B,oi as C};