@trayai/helix-sdk 0.66.0 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- declare const BROKER_BASE_URLS: {
2
- readonly production: "https://api.tray.io/private/v1/code";
3
- };
4
- type BrokerEnvironment = keyof typeof BROKER_BASE_URLS;
1
+ import { a as Environment } from '../env-schema-CMAM3FrY.js';
2
+ import 'zod';
3
+
4
+ type BrokerEnvironment = Environment;
5
5
 
6
6
  interface BrokerDevCallParams {
7
7
  /** Target Tray environment — selects the broker base URL. */
@@ -1 +1 @@
1
- import{a as n,b as s,c as i,d as a}from"../chunk-V63DM4MB.js";import"../chunk-W5TFZBQD.js";import p from"ky";var d=6e4;async function l(e){let u=n({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),k=s(e.env),r=await p.post(`${k}/broker/http/dev`,{json:u,headers:{Authorization:`Bearer ${e.devToken}`,Accept:"application/json"},throwHttpErrors:!1,timeout:e.timeoutMs??d}),t;if((r.headers.get("content-type")??"").includes("application/json")?t=await r.json():t=await r.text(),r.status<200||r.status>=300)return{kind:"brokerError",brokerStatus:r.status,body:t};let o=i.safeParse(t);return o.success?{kind:"upstream",upstream:a(o.data)}:{kind:"brokerError",brokerStatus:r.status,body:t}}export{l as callBrokerDev};
1
+ import{a as n,b as s,c as i,d as a}from"../chunk-5XNPF4RA.js";import"../chunk-ATJUJXR7.js";import p from"ky";var d=6e4;async function l(e){let u=n({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),k=s(e.env),r=await p.post(`${k}/broker/http/dev`,{json:u,headers:{Authorization:`Bearer ${e.devToken}`,Accept:"application/json"},throwHttpErrors:!1,timeout:e.timeoutMs??d}),t;if((r.headers.get("content-type")??"").includes("application/json")?t=await r.json():t=await r.text(),r.status<200||r.status>=300)return{kind:"brokerError",brokerStatus:r.status,body:t};let o=i.safeParse(t);return o.success?{kind:"upstream",upstream:a(o.data)}:{kind:"brokerError",brokerStatus:r.status,body:t}}export{l as callBrokerDev};
@@ -0,0 +1 @@
1
+ import{d as m,l as p}from"./chunk-ATJUJXR7.js";var l=new Set(["proxy-authorization","x-tray-token"]);function k(e){let t=e.toLowerCase();return l.has(t)||t.startsWith("x-tray-internal-")}function g(e){let t;return e instanceof Headers?t=Array.from(e.entries()):Array.isArray(e)?t=e:t=Object.entries(e),t.filter(([o])=>!k(o)).map(([o,i])=>({name:o,value:i}))}function B(e){return typeof e=="string"?"string":e instanceof Blob?"Blob":e instanceof FormData?"FormData":e instanceof ArrayBuffer?"ArrayBuffer":e instanceof Uint8Array?"Uint8Array":typeof ReadableStream<"u"&&e instanceof ReadableStream?"ReadableStream":null}function q(e){let t=new URL(e.url);if(t.protocol!=="https:")throw p.unsupportedScheme(t.protocol.replace(/:$/,""));let o=e.body!==void 0&&e.body!==null?B(e.body):null;if(o!==null)throw p.unsupportedBodyType(o);let i=t.host,s=t.pathname,n=[];for(let[d,a]of t.searchParams.entries())n.push({name:d,value:a});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[d,a]of e.query.entries())n.push({name:d,value:a});else for(let[d,a]of Object.entries(e.query))if(Array.isArray(a))for(let h of a)n.push({name:d,value:h});else n.push({name:d,value:a});let u=e.headers!==void 0?g(e.headers):[],c=e.body!==void 0&&e.body!==null?{host:i,method:e.method,path:s,body:e.body,headers:u,queryParams:n}:{host:i,method:e.method,path:s,headers:u,queryParams:n};return{authenticationId:e.authenticationId,httpRequest:c}}function A(e){return m(e).hosts.broker}import{z as r}from"zod";var y=r.object({name:r.string(),value:r.string()}),R=r.object({host:r.string(),method:r.string(),path:r.string().startsWith("/"),body:r.record(r.unknown()).optional(),headers:r.array(y),queryParams:r.array(y)}),w=r.object({authenticationId:r.string().uuid(),httpRequest:R}),j=r.object({httpResponse:r.object({status:r.number(),body:r.unknown().optional(),headers:r.array(y)})});function D(e){let{status:t,body:o,headers:i}=e.httpResponse,s={};for(let{name:n,value:u}of i){let f=n.toLowerCase(),c=s[f];c===void 0?s[f]=u:Array.isArray(c)?c.push(u):s[f]=[c,u]}return{status:t,body:o,headers:s}}export{q as a,A as b,j as c,D as d};
@@ -0,0 +1 @@
1
+ var u=new Set(["production"]),i=new Map,o={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://helix.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};i.set(o.name,o);var l=["api","broker","ingest","weaver","app","projectHost","dashboard"],d=["storePrefix","appUrl","cookieName","cookieDomain"];function g(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 l)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 d)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function m(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&l.every(r=>e.hosts[r]===n.hosts[r])&&d.every(r=>e.login[r]===n.login[r])}function k(e){g(e);let n=i.get(e.name);if(n){if(m(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of i.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);i.set(e.name,e)}function v(e){return i.has(e)}function _(e){return i.get(e)}function y(e){let n=i.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function E(){return[...i.keys()]}function b(){return[...i.values()].map(e=>e.exposedName)}function c(e){for(let n of i.values())if(n.exposedName===e)return n.name}var s=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function f(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[s];return}let r=e.trim(),t=c(r);if(t){n[s]=t;return}if(v(r)){n[s]=r;return}throw new Error(`Unknown environment: ${r}`)}function h(){return globalThis[s]}function w(){return[...i.values()].filter(e=>!u.has(e.name))}function x(){f(void 0),i.clear(),i.set(o.name,{...o,hosts:{...o.hosts},login:{...o.login}})}var a=class e extends Error{detail;constructor(n){super(p(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){return new e({kind:"broker_error",status:n,message:r,body:t})}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 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"})}};function N(e){return e instanceof a}function p(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`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_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)"}}export{k as a,v as b,_ as c,y as d,E as e,b as f,c as g,f as h,h as i,w as j,x as k,a as l,N as m};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-W5TFZBQD.js";var R="X-Helix-Project-Execution-Token",b="X-Tray-Token",h={mode:"dev",deploymentId:null},u={...h},i={};function B(t){let{internalJwt:e,helixExecutionJwt:r,devToken:o,...s}=t;"internalJwt"in t&&(i.internalJwt=e),"helixExecutionJwt"in t&&(i.helixExecutionJwt=r),"devToken"in t&&(i.devToken=o),u={...u,...s}}function D(){return u}function L(){return i.internalJwt}function F(){return i.helixExecutionJwt}function N(){return i.devToken}var J="tray-config-bridge",c=null;function M(t){c=t}function O(){if(!c)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return c}function U(){c=null}var E=1024,a=100*1024*1024,x=250,T=3600,S=T*1e3,m=new TextEncoder,_=/(^|\/)\.\.(\/|$)/,p=/[?#]/;function v(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r<=31||r===127)return!0}return!1}function $(t,e=E){if(t.length===0)throw n.filesPathInvalid("Path must be a non-empty string");A(t,e)}function G(t){return t.endsWith("/")?t.slice(0,-1):t}function A(t,e=E){if(t.length===0)return;if(_.test(t))throw n.filesPathInvalid("Path contains path traversal segment");if(p.test(t)||v(t))throw n.filesPathInvalid("Path contains illegal characters");let r=t.split("/");if(t.startsWith("/")||t.endsWith("/")||r.some(s=>s===""))throw n.filesPathInvalid("Path must not contain empty path segments");for(let s of r){let d=m.encode(s).length;if(d>x)throw n.filesPathInvalid(`Path segment exceeds ${x} UTF-8 bytes (got ${d})`)}let o=m.encode(t).length;if(o<1||o>e)throw n.filesPathInvalid(`Path must be between 1 and ${e} UTF-8 bytes (got ${o})`)}function V(t){if(t>a)throw n.filesValueTooLarge(`File exceeds maximum size of ${a} bytes (got ${t})`,a)}function W(t){let e=t!==void 0?t*1e3:S;return new Date(Date.now()+e)}import{join as f}from"path";var C="files",I="files-meta",P=1023,w=1,k=5;function K(t){let e=Math.max(Buffer.byteLength(l(t),"utf8"),Buffer.byteLength(g(t),"utf8"));return Math.max(0,P-e-w-k)}function l(t){return f(t,".helix",C)}function g(t){return f(t,".helix",I)}function y(t,e){return f(l(t),...e.split("/"))}function q(t,e){return f(g(t),...e.split("/"))+".json"}function Q(t,e){return e.length===0?l(t):y(t,e)}function Z(t,e){return e.length===0?g(t):f(g(t),...e.split("/"))}export{R as a,b,B as c,D as d,L as e,F as f,N as g,J as h,M as i,O as j,U as k,a as l,$ as m,G as n,A as o,V as p,W as q,K as r,y as s,q as t,Q as u,Z as v};
1
+ import{l as n}from"./chunk-ATJUJXR7.js";var R="X-Helix-Project-Execution-Token",b="X-Tray-Token",h={mode:"dev",deploymentId:null},u={...h},i={};function B(t){let{internalJwt:e,helixExecutionJwt:r,devToken:o,...s}=t;"internalJwt"in t&&(i.internalJwt=e),"helixExecutionJwt"in t&&(i.helixExecutionJwt=r),"devToken"in t&&(i.devToken=o),u={...u,...s}}function D(){return u}function L(){return i.internalJwt}function F(){return i.helixExecutionJwt}function N(){return i.devToken}var J="tray-config-bridge",c=null;function M(t){c=t}function O(){if(!c)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return c}function U(){c=null}var E=1024,a=100*1024*1024,x=250,T=3600,S=T*1e3,m=new TextEncoder,_=/(^|\/)\.\.(\/|$)/,p=/[?#]/;function v(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r<=31||r===127)return!0}return!1}function $(t,e=E){if(t.length===0)throw n.filesPathInvalid("Path must be a non-empty string");A(t,e)}function G(t){return t.endsWith("/")?t.slice(0,-1):t}function A(t,e=E){if(t.length===0)return;if(_.test(t))throw n.filesPathInvalid("Path contains path traversal segment");if(p.test(t)||v(t))throw n.filesPathInvalid("Path contains illegal characters");let r=t.split("/");if(t.startsWith("/")||t.endsWith("/")||r.some(s=>s===""))throw n.filesPathInvalid("Path must not contain empty path segments");for(let s of r){let d=m.encode(s).length;if(d>x)throw n.filesPathInvalid(`Path segment exceeds ${x} UTF-8 bytes (got ${d})`)}let o=m.encode(t).length;if(o<1||o>e)throw n.filesPathInvalid(`Path must be between 1 and ${e} UTF-8 bytes (got ${o})`)}function V(t){if(t>a)throw n.filesValueTooLarge(`File exceeds maximum size of ${a} bytes (got ${t})`,a)}function W(t){let e=t!==void 0?t*1e3:S;return new Date(Date.now()+e)}import{join as f}from"path";var C="files",I="files-meta",P=1023,w=1,k=5;function K(t){let e=Math.max(Buffer.byteLength(l(t),"utf8"),Buffer.byteLength(g(t),"utf8"));return Math.max(0,P-e-w-k)}function l(t){return f(t,".helix",C)}function g(t){return f(t,".helix",I)}function y(t,e){return f(l(t),...e.split("/"))}function q(t,e){return f(g(t),...e.split("/"))+".json"}function Q(t,e){return e.length===0?l(t):y(t,e)}function Z(t,e){return e.length===0?g(t):f(g(t),...e.split("/"))}export{R as a,b,B as c,D as d,L as e,F as f,N as g,J as h,M as i,O as j,U as k,a as l,$ as m,G as n,A as o,V as p,W as q,K as r,y as s,q as t,Q as u,Z as v};
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Built-in environments shipped in the published SDK. */
4
+ declare const ENVIRONMENT_VALUES: readonly ["production"];
5
+ /** Runtime environment name (built-ins plus any registered profiles). */
6
+ type Environment = string;
7
+ declare const environmentSchema: z.ZodEffects<z.ZodString, string, string>;
8
+
9
+ export { ENVIRONMENT_VALUES as E, type Environment as a, environmentSchema as e };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import * as h3 from 'h3';
2
- import { ZodType, z } from 'zod';
2
+ import { ZodType } from 'zod';
3
3
  import { c as FunctionHandler, b as DefineFunctionOptions, T as TrayContext } from './types-DXkq0EN9.js';
4
4
  export { D as DbCallParameters, a as DbClient, F as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, S as SqlBuilder, U as UnvalidatedInput } from './types-DXkq0EN9.js';
5
- import { T as TrayConfig, L as LoadedTrayConfig, b as WatchErrorPhase } from './sdk-config-B-Vfaig8.js';
6
- export { P as ProvisionedTrayConfig, a as SdkRuntimeConfig, U as UnprovisionedTrayConfig, W as WORKSPACE_ID_REQUIRED_CODE, c as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, d as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, e as resolveConfigFile, w as workspaceIdSchema } from './sdk-config-B-Vfaig8.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, b as WatchErrorPhase } from './sdk-config-DrgARqBz.js';
6
+ export { P as ProvisionedTrayConfig, a as SdkRuntimeConfig, U as UnprovisionedTrayConfig, W as WORKSPACE_ID_REQUIRED_CODE, c as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, d as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, e as resolveConfigFile, w as workspaceIdSchema } from './sdk-config-DrgARqBz.js';
7
+ export { E as ENVIRONMENT_VALUES, a as Environment, e as environmentSchema } from './env-schema-CMAM3FrY.js';
7
8
  import 'ky';
8
9
  import 'unstorage';
9
10
 
@@ -59,10 +60,6 @@ declare function getContext(): TrayContext;
59
60
  */
60
61
  declare function defineConfig(config: TrayConfig): TrayConfig;
61
62
 
62
- declare const ENVIRONMENT_VALUES: readonly ["production"];
63
- type Environment = (typeof ENVIRONMENT_VALUES)[number];
64
- declare const environmentSchema: z.ZodEnum<["production"]>;
65
-
66
63
  interface CreateConfigServiceOptions {
67
64
  /** Directory containing `helix.config.ts`. */
68
65
  cwd: string;
@@ -114,4 +111,4 @@ interface ConfigService {
114
111
  */
115
112
  declare function createConfigService(options: CreateConfigServiceOptions): Promise<ConfigService>;
116
113
 
117
- export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, ENVIRONMENT_VALUES, type Environment, FunctionHandler, LoadedTrayConfig, type RunWithinAppSpanArgs, TrayConfig, TrayContext, WatchErrorPhase, createConfigService, defineConfig, defineFunction, environmentSchema, getContext, runWithinAppSpan };
114
+ export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, FunctionHandler, LoadedTrayConfig, type RunWithinAppSpanArgs, TrayConfig, TrayContext, WatchErrorPhase, createConfigService, defineConfig, defineFunction, getContext, runWithinAppSpan };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{a as pt,b as qr}from"./chunk-L6J5L3JQ.js";import{a as T,b as D,d as y,e as O,f as I,g as ft,j as v,l as z,m as A,n as Pe,o as Ae,p as ht,q as F,r as wt,s as ie,t as ae,u as ce,v as bt}from"./chunk-EDBOWEUT.js";import{a as W,b as se,c as gt,d as yt}from"./chunk-V63DM4MB.js";import{a as u,b as mt}from"./chunk-W5TFZBQD.js";import{randomUUID as Uo}from"crypto";import{SpanStatusCode as Dr,SpanKind as Mo}from"@opentelemetry/api";import{AsyncLocalStorage as Ut}from"async_hooks";import{trace as sn,SpanKind as an,SpanStatusCode as Oe}from"@opentelemetry/api";import{ExportResultCode as cn,W3CTraceContextPropagator as un}from"@opentelemetry/core";import{NodeTracerProvider as dn,SimpleSpanProcessor as ln,BatchSpanProcessor as fn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Wr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as zr}from"@opentelemetry/exporter-logs-otlp-proto";var Vr={production:"https://api.tray.io/private/v1/helix/otlp"};function _e(e){return Vr[e]}function Jr(){return I()??""}function St(){return{[T]:Jr()}}function vt(){let e=_e(v().env);return new Wr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(St())})}function Et(){let e=_e(v().env);return new zr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(St())})}import{logs as Rt,SeverityNumber as ue}from"@opentelemetry/api-logs";import{LoggerProvider as Xr,BatchLogRecordProcessor as Zr}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 Yr(e){return new TextEncoder().encode(e).length}var xt="\u2026[truncated]",Gr=Yr(xt),L=4096;function _(e,t=L){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Gr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+xt}function b(e,t=L){return _(J(e),t)}var Qr="@trayai/helix-sdk",Y,Ct={debug:{number:ue.DEBUG,text:"DEBUG"},info:{number:ue.INFO,text:"INFO"},warn:{number:ue.WARN,text:"WARN"},error:{number:ue.ERROR,text:"ERROR"}};function en(){return y().mode==="lambda"?[new Zr({exporter:Et()})]:[]}function kt(){if(Y!==void 0)return;let e=en();e.length!==0&&(Y=new Xr({processors:e}),Rt.setGlobalLoggerProvider(Y))}function tn(e,t,r){let n=Ct[e]??Ct.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":b(r)}}:{}}}function Tt(e,t,r){Rt.getLogger(Qr).emit(tn(e,t,r))}async function It(e=2e3){if(Y===void 0)return;let t;try{await Promise.race([Y.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 De(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function rn(){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 k(e,t){return rn()?`\x1B[${e}m${t}\x1B[0m`:t}var nn=5,on={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Pt="32",At="31",de="2",_t="1";function le(e){return k(on[e]??"0",e.padEnd(nn))}function Dt(e,t){return`${le("FN")} ${k(_t,`${e} ${t}`.trim())}`}function Ot(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${k(de,n)} `:""}${le(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${k(de,J(r))}`),i}function Ft(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Lt(e){return`${le("AUTH")} ${e}`}function jt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=k(o==="error"?At:Pt,s);return`${le("API")} ${e} ${t} \u2192 ${i} ${k(de,`${n}ms`)}`}function Nt(e,t,r){let n=t?At:Pt,o=k(n,"\u25CF"),s=k(n,t?"error":"success");return`${o} ${k(_t,e)} ${s} ${k(de,`${r}ms`)}`}function j(e){try{process.stdout.write(e+`
3
- `)}catch{}}var fe=new Ut,pe=new Ut;function C(e){let t=pe.getStore();t&&(t[e]=!0)}var pn=/^[0-9a-f]{32}$/;function mn(e){let t=e.replace(/-/g,"").toLowerCase();return pn.test(t)?t:null}var gn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},N=new Map;function x(e,t,r){let n=N.get(e);n?n[t]=r:N.set(e,{[t]:r})}var G;function Bt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function yn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Mt(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,s=N.get(o),i={...n.attributes};if(s!==void 0){for(let[d,f]of Object.entries(s))typeof f=="string"?i[d]=_(f):typeof f=="object"&&f!==null?i[d]=b(f):i[d]=f;N.delete(o)}let a=fe.getStore(),c=a?mn(a):null;Mt({_otel:"span",traceId:c??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Bt(n.startTime),endTimeUnixNano:Bt(n.endTime),attributes:i,status:{code:gn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:cn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t,r){}onEnd(t){N.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&j(`
5
- `+Dt(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=N.get(n)?.properties;j(Ot(String(r.level??"info"),String(r.message??""),o,Ft(t.startTime)));break}case"auth":j(Lt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;j(jt(String(r.method??""),String(r.host??""),n,yn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function hn(){let t=[De()?new je:new ln(new Fe)];return y().mode==="lambda"&&t.push(new fn(vt())),t.push(new Le),t}function Ne(){G===void 0&&(G=new dn({spanProcessors:hn()}),G.register({propagator:new un}),kt())}async function Be(e=2e3){let t=[It(e)];G!==void 0&&t.push((async()=>{let r;try{await Promise.race([G.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 R=sn.getTracer("@trayai/helix-sdk");function Ue({executionId:e,deploymentId:t,routeOrJob:r,startedAt:n,startMs:o,errored:s,errorMessage:i,userId:a,flags:c}){let d=new Date().toISOString(),f=Date.now()-o;if(De()){j(`
7
- `+Nt(r,s,f));return}Mt({_otel:"summary",executionId:e,deploymentId:t,triggerType:"http",routeOrJob:r,status:s?"error":"success",startedAt:n,finishedAt:d,durationMs:f,userId:a,hasError:s||c.hasError,hasAuth:c.hasAuth,hasExternal:c.hasExternal,hasDb:c.hasDb,errorSummary:s&&i!==null?_(i):null})}async function wn(e,t){let r=e.startMs??Date.now();Ne();let n=!1,o=null;try{return await fe.run(e.executionId,()=>R.startActiveSpan("App",{kind:an.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{Ue({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 Be()}}import{defineEventHandler as Ho,getMethod as $o,getRequestURL as Ko,getHeaders as Fr,getHeader as Or}from"h3";import{readBody as bn,getQuery as Sn,getRouterParams as vn}from"h3";async function Ht(e,t){let r=await En(e),n=Sn(e),o=vn(e)??{},s={...n,...r,...o};return t?xn(s,t):s}async function En(e){try{let t=await bn(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 xn(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}import{SpanKind as Cn}from"@opentelemetry/api";function me(e,t,r){let n=R.startSpan("log",{kind:Cn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&x(n.spanContext().spanId,"properties",r),n.end(),Tt(e,t,r)}function $t(){return{info:(e,t)=>me("info",e,t),warn:(e,t)=>me("warn",e,t),error:(e,t)=>me("error",e,t),debug:(e,t)=>me("debug",e,t)}}var X=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Kt(e){return t=>{e.node.res.statusCode=t}}function qt(){return(e,t)=>{throw new X(e,t)}}import Tn from"ky";import{context as Me,trace as In,SpanKind as ye,SpanStatusCode as zt}from"@opentelemetry/api";import Rn from"ky";async function Vt(e,t={}){let r=O(),n=I(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw u.missingExecutionCredentials();let{env:i}=v(),a=se(i),c=t.timeout??6e4,d={Accept:"application/json"};o&&(d[D]=r),s&&(d[T]=n);let f=y().deploymentId,m=f?{...e,deploymentId:f}:e,l=await Rn.post(`${a}/broker/http`,{json:m,headers:d,throwHttpErrors:!1,timeout:c}),p;return(l.headers.get("content-type")??"").includes("application/json")?p=await l.json():p=await l.text(),{status:l.status,body:p}}import kn from"ky";async function Wt(e,t={}){let r=ft();if(!r)throw u.missingTrayToken();let{env:n}=v(),o=se(n),s=t.timeout??6e4,i=await kn.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:s}),a;return(i.headers.get("content-type")??"").includes("application/json")?a=await i.json():a=await i.text(),{status:i.status,body:a}}async function ge(e,t={}){let r=y().mode==="lambda"?Vt:Wt,n;try{n=await r(e,t)}catch(a){if(a instanceof u)throw a;let c=a instanceof Error?a.message??String(a):String(a);throw u.brokerError(0,c)}let{status:o,body:s}=n;if(o<200||o>=300){let a;if(s!==null&&typeof s=="object"){let c=s;typeof c.message=="string"?a=c.message:typeof c.error=="string"?a=c.error:a=String(s)}else a=String(s);throw u.brokerError(o,a,b(s))}let i=gt.safeParse(s);if(!i.success)throw u.brokerError(o,"broker returned malformed response",b(s));return yt(i.data)}var Pn=["get","post","put","patch","delete","head","options"],Jt="[stream body omitted]";function He(e){try{return new URL(e).hostname}catch{return e}}function An(e,t,r,n){let o=He(t),s="externalApi",i={kind:ye.CLIENT};return R.startActiveSpan(s,i,async a=>{let c=a.spanContext().spanId;return a.setAttributes({method:e,host:o}),x(c,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?Jt:r}:{}}),n(a,c)})}function $e(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:zt.OK}:{code:zt.ERROR,message:r}),e.end()}var _n=16;async function Dn(e,t){let r=e.clone().body;return r?Yt(r,t):new Uint8Array(0)}async function Yt(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:c,value:d}=await r.read();if(c)break;if(!d||d.byteLength===0){if(s+=1,s>=_n)break;continue}s=0;let f=t+1-o;if(d.byteLength>=f){n.push(d.slice(0,f)),o+=f;break}n.push(d),o+=d.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of n)i.set(c,a),a+=c.byteLength;return i}async function Gt(e,t,r){if("kyResponse"in r)try{let n=await Dn(r.kyResponse,L),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;if(n.length<=L)try{s=JSON.parse(o)}catch{s=o}else s=o;x(e,"response",s)}catch{x(e,"response",{status:t})}else x(e,"response",r.bodyValue)}async function On(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 Yt(o,L);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:Jt}}}return typeof t=="string"?{body:t}:{}}function Xt(){let e=Tn.create({});function t(n){return(o,s)=>{let i=Me.active(),a,c="",d=!1,f=(l,p)=>{a&&!d&&(d=!0,$e(a,l,p))},m=e.extend({hooks:{beforeRequest:[async(l,p)=>{let g=await On(l,p.body),w=g.body;if(a||(a=R.startSpan("externalApi",{kind:ye.CLIENT},i),c=a.spanContext().spanId),a.setAttributes({method:l.method.toUpperCase(),host:He(l.url)}),x(c,"request",{url:l.url,method:l.method.toUpperCase(),...w!==void 0?{body:w}:{}}),d=!1,C("hasExternal"),g.request)return g.request}],beforeRetry:[l=>{f("error","retry"),a=void 0,c="",d=!1}],afterResponse:[async(l,p,g)=>{a&&(a.setAttribute("statusCode",g.status),await Gt(c,g.status,{kyResponse:g}),g.ok?f("success"):s?.throwHttpErrors===!1&&(C("hasError"),f("error",`HTTP ${g.status}`)))}],beforeError:[l=>(C("hasError"),f("error",l.message),l)]}});return a=R.startSpan("externalApi",{kind:ye.CLIENT},i),c=a.spanContext().spanId,a.setAttributes({method:n.toUpperCase(),host:He(String(o))}),Me.with(In.setSpan(Me.active(),a),()=>{let l=n==="options"?m(o,{...s,method:"OPTIONS"}):m[n](o,s);return l.catch(p=>{C("hasError"),f("error",p instanceof Error?p.message:String(p))}),l})}}let r=Object.fromEntries(Pn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Fn(n)}}}function Fn(e){let r=v().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(i,a={})=>{let c=s.toUpperCase();return An(c,i,a.body,async(d,f)=>{C("hasAuth");let m=R.startSpan("auth",{kind:ye.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let l=W({authenticationId:n,method:c,url:i,body:a.body,headers:a.headers,query:a.query}),p=await ge(l,{timeout:a.timeout});return d.setAttribute("statusCode",p.status),await Gt(f,p.status,{bodyValue:p.body}),$e(d,"success"),p}catch(l){throw C("hasError"),l instanceof u&&l.detail.kind==="broker_error"&&l.detail.status>0&&d.setAttribute("statusCode",l.detail.status),$e(d,"error",l instanceof Error?l.message:String(l)),l}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as Kn,SpanStatusCode as tr}from"@opentelemetry/api";function Z(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Ln=18e4,Zt=Ln-1e4,jn=2e3;async function Qt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<Zt;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let c=Math.min(jn,200*2**s),d=c/2+Math.random()*(c/2),f=Zt-(Date.now()-o);await new Promise(m=>setTimeout(m,Math.min(d,f))),s++}throw u.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Nn=new Set(["SELECT","WITH","SHOW"]),Bn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Un(e){if(!e.clusterIdentifier&&!e.workgroupName)throw u.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw u.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw u.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw u.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw u.dbInvalidParameters("region is required")}function Mn(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 u.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):b(t);return u.dbCallFailed(s)}function Hn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw u.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function $n(e,t){return typeof t!="number"||t<0?{}:Nn.has(e)?{rowsRead:t}:Bn.has(e)?{rowsWritten:t}:{}}function er(e){async function t(r,n,o){let s=W({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 ge(s);if(i>=400)throw Mn(i,a);return Hn(a)}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw u.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:Un,async execute(r,n){let o=Z(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,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let p=b(i);throw u.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let d=await Qt(t,r.region,c),f=d.Status;if(f==="FAILED"){let p=typeof d.Error=="string"?d.Error:"statement failed";throw u.dbQueryFailed(`${p} (statement: ${c})`)}if(f==="ABORTED")throw u.dbQueryFailed(`statement aborted (statement: ${c})`);let m=$n(o,d.ResultRows);return d.HasResultSet===!1?{result:{rowsAffected:d.ResultRows??0},metadata:m}:{result:await t(r.region,"GetStatementResult",{Id:c}),metadata:m}}}}var Ke=64*1024;function qn(e){return e.length>Ke?`${e.slice(0,Ke)}...[truncated]`:e}function Vn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Wn(e,t,r,n){let o=typeof r=="string"?r:JSON.stringify(r);return o.length>Ke?x(t,"result",{truncated:!0,size:o.length}):x(t,"result",r),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),o}async function zn(e,t,r){let n=Z(r),o=qn(r);return R.startActiveSpan("database",{kind:Kn.CLIENT},async s=>{let i=s.spanContext().spanId;Vn(s,e,t,n,o);try{C("hasDb");let{result:a,metadata:c}=await e.execute(t,r),d=Wn(s,i,a,c);return s.setAttribute("status","success"),s.setStatus({code:tr.OK}),d}catch(a){C("hasError");let c=a instanceof Error?a.message:String(a);throw s.setAttribute("status","error"),s.setStatus({code:tr.ERROR,message:c}),a}finally{s.end()}})}function qe(e){let r=v().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e],o=er(n);function s(i,a){return o.validate(i),zn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as Zn}from"unstorage";var rr=1024,Ve=250*1024,Jn=new TextEncoder,Yn=/(^|\/)\.\.(\/|$)/,Gn=/[?#]/,Xn=/[\u0000-\u001F\u007F]/;function nr(e){if(e.length===0)throw u.kvKeyInvalid("Key must be a non-empty string");if(Yn.test(e))throw u.kvKeyInvalid("Key contains path traversal segment");if(Gn.test(e)||Xn.test(e))throw u.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw u.kvKeyInvalid("Key must not contain empty path segments");let t=Jn.encode(e).length;if(t<1||t>rr)throw u.kvKeyInvalid(`Key must be between 1 and ${rr} UTF-8 bytes (got ${t})`)}function or(e){let t;try{t=JSON.stringify(e)}catch{throw u.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw u.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>Ve)throw u.kvValueTooLarge(`Value exceeds maximum size of ${Ve} bytes (got ${r})`,Ve)}function Q(e){nr(e)}function he(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function sr(e){let t=he(e,"getItem"),r=he(e,"setItem"),n=he(e,"removeItem"),o=he(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return Q(i),t(i,a)},setItem(i,a,c){return Q(i),r(i,a,c)},removeItem(i,a){return Q(i),n(i,a)},hasItem(i,a){return Q(i),o(i,a)},getKeys(i,a){return i.length>0&&Q(i),s(i,a)}}}function we(e){return Zn({driver:sr(e)})}import{defineDriver as Qn}from"unstorage";function eo(e){try{return JSON.parse(e)}catch{return e}}var to=Qn(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){await t.set(r,eo(n))},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 ir(e){return to({client:e})}import so from"ky";import{z as S}from"zod";async function B(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}var ro={production:"https://api.tray.io"};function ar(e){return ro[e]}function no(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function oo(e){return e.split("/").map(encodeURIComponent).join("/")}function ee(e,t,r){return`${e}${no(t)}/${oo(r)}`}var io=6e4,We=S.lazy(()=>S.union([S.string(),S.number(),S.boolean(),S.null(),S.array(We),S.record(We)])),ao=S.object({projectId:S.string(),key:S.string(),value:We,type:S.enum(["string","number","boolean","null","array","object"]),organizationId:S.string(),scope:S.string(),createdBy:S.string(),createdAt:S.number(),updatedBy:S.string(),updatedAt:S.number()});function co(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function uo(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 be(e,t){throw u.kvCallFailed(e,uo(t),b(t))}async function Se(e,t,r={}){try{let n=await so(t,{method:e,headers:co(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:io}),o=e==="head"?void 0:await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw u.kvCallFailed(0,o)}}function cr(e){let t=ar(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Se("get",ee(t,r,n));if(o===404)return null;(o<200||o>=300)&&be(o,s);let i=ao.safeParse(s);if(!i.success)throw u.kvCallFailed(o,"platform returned malformed KeyValueEntry",b(s));return i.data.value},async set(n,o){let{status:s,body:i}=await Se("put",ee(t,r,n),{json:{value:o}});(s<200||s>=300)&&be(s,i)},async delete(n){let{status:o,body:s}=await Se("delete",ee(t,r,n));o!==204&&be(o,s)},async has(n){let{status:o,body:s}=await Se("head",ee(t,r,n));if(o===200)return!0;if(o===404)return!1;be(o,s)}}}function ve(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{or(r),await e.setItem(t,r,n)}}}function lo(){let e=v();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function ur(e){let t=lo(),r=e??cr(t),n=we(ir(r));return ve(n)}import fo from"unstorage/drivers/memory";var ze;function po(){return ze||(ze=we(fo())),ze}function dr(){return ve(po())}function mo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function lr(){return mo()?ur():dr()}import{createHash as ho}from"crypto";import{mkdir as wo,readFile as yr,readdir as hr,rm as pr,unlink as bo,writeFile as mr}from"fs/promises";import{dirname as So}from"path";async function go(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>z)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${z} bytes (got more than ${z})`,z);r.push(s)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?go(e):Buffer.from(e)}var yo={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"},fr="application/octet-stream";function Ee(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return fr;let r=e.slice(t+1).toLowerCase();return yo[r]??fr}function H(){let e=y().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function M(e){try{return await e()}catch(t){if(t instanceof u)throw t;let r=t?.code;throw r?u.filesCallFailed(0,`Local file storage operation failed: ${r}`):u.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xe(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 yr(ae(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function gr(e){await wo(So(e),{recursive:!0})}async function vo(e,t){let r=ce(e,t),n;try{n=await hr(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 wr(e,t){let r=ce(e,t),n;try{n=await hr(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 wr(e,i)):s.isFile()&&o.push(i)}return o}function br(){return{async put(e,t,r){return M(async()=>{let n=H(),o=await U(t),s=r?.contentType??Ee(e),i=ho("sha1").update(o).digest("hex"),a=new Date,c=ie(n,e);await gr(c),await mr(c,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},f=ae(n,e);return await gr(f),await mr(f,JSON.stringify(d)),xe(e,d)})},async get(e){return M(async()=>{let t=await Je(e);return t?{data:await yr(ie(H(),e)),metadata:xe(e,t)}:null})},async head(e){return M(async()=>{let t=await Je(e);return t?xe(e,t):null})},async delete(e){return M(async()=>{let t=H();await Promise.all([ie(t,e),ae(t,e)].map(async r=>{try{await bo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return M(async()=>{let t=H(),r=await wr(t,e);return await Promise.all([pr(ce(t,e),{recursive:!0,force:!0}),pr(bt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return M(async()=>{let r=H(),n=t?.limit??100,s=(await vo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let c=await Je(a);return c?xe(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:F(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:F(t?.expiresIn)}}}}import{createHash as Po}from"crypto";var Eo={production:"https://api.tray.io"};function Ce(e){return Eo[e]}function xo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function te(e,t){return`${e}${xo(t)}`}function $(e,t,r){return`${te(e,t)}/${encodeURIComponent(r)}`}function Re(e,t,r){return`${$(e,t,r)}/upload`}function Sr(e,t,r){return`${$(e,t,r)}/download`}function vr(e,t,r){return`${$(e,t,r)}/signed-url`}function Er(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${te(e,t)}/file?${o.toString()}`}function xr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${te(e,t)}?${o.toString()}`}import Ge from"ky";import{z as h}from"zod";var Xe=6e4,Cr=h.object({id:h.string(),workspaceId:h.string(),projectId:h.string(),parentFolder:h.string().nullable().optional(),name:h.string(),size:h.number().nullable().optional(),objectType:h.enum(["Folder","File"]),contentType:h.string().nullable().optional(),createdAt:h.string(),updatedAt:h.string()}),Co=h.object({signedURL:h.string()}),Ro=h.object({path:h.array(h.object({id:h.string(),name:h.string()})),elements:h.array(Cr)});function Ze(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function Rr(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 P(e,t){throw u.filesCallFailed(e,Rr(t),b(t))}function ko(e,t){return e===400&&Rr(t).toLowerCase()==="resource not found"}async function To(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 K(e,t,r={}){try{let n=await Ge(t,{method:e,headers:Ze(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Xe}),o=await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message:String(n);throw u.filesCallFailed(0,o)}}function Ye(e,t){let r=Cr.safeParse(t);if(!r.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",b(t));return r.data}function kr(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await K("post",te(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Ye(o,s)},async getByName(n,o){let{status:s,body:i}=await K("get",Er(t,r,n,o));return s===404||ko(s,i)?null:((s<200||s>=300)&&P(s,i),Ye(s,i))},async getById(n){let{status:o,body:s}=await K("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Ye(o,s))},async listChildren(n,o){let{status:s,body:i}=await K("get",xr(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=Ro.safeParse(i);if(!a.success)throw u.filesCallFailed(s,"platform returned malformed listing",b(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:c,contentType:d}=await To(a),f;try{f=await Ge(Re(t,r,n),{method:"post",headers:{...Ze(),"content-type":d},body:new Uint8Array(c),throwHttpErrors:!1,timeout:Xe})}catch(l){if(l instanceof u)throw l;let p=l instanceof Error?l.message:String(l);throw u.filesCallFailed(0,p)}let m=await B(f);(f.status<200||f.status>=300)&&P(f.status,m)},async downloadContent(n){let o;try{o=await Ge(Sr(t,r,n),{method:"get",headers:Ze(),throwHttpErrors:!1,timeout:Xe})}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message:String(i);throw u.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await B(o);P(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await K("get",vr(t,r,n));(o<200||o>=300)&&P(o,s);let i=Co.safeParse(s);if(!i.success)throw u.filesCallFailed(o,"platform returned malformed signed URL response",b(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await K("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function Qe(e){return e.split("/").filter(t=>t.length>0)}function et(e){return e instanceof u&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Io(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(et(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function tt(e,t){let r=Qe(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await Io(e,o,s)).id;return{parentFolder:o,name:n}}async function re(e,t){let r=Qe(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 rt(e,t){if(t.length===0)return;let r=Qe(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 Ao=500,_o=8;async function Do(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 Oo(){let e=v();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Fo(e){return Po("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function ke(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Fo(t)}}async function Tr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(et(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Ir(e,t){let{elements:r}=await e.listChildren(t,Ao);return(await Do(r,_o,async o=>{let s=o.objectType==="Folder"?await Ir(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Pr(e){let t=Oo(),r=e??kr(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:d}=await tt(r,s),f=await U(i),m=a?.contentType??Ee(s),l=await r.getByName(c,d);if(l&&l.objectType!=="File")throw u.filesCallFailed(409,`A folder already exists at "${s}"`);let p=l??await Tr(r,c,d,m);await r.uploadContent(p.id,f,d,m);let g=await r.getById(p.id);return ke(s,g??p,m)},async get(s){let i=await re(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:ke(s,a)}},async head(s){let i=await re(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:ke(s,a)},async delete(s){let i=await re(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 rt(r,s);if(i===null)return{deleted:0};let a=await Ir(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await rt(r,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:d}=await r.listChildren(a,c);return{files:d.filter(m=>m.objectType==="File").map(m=>ke(s?`${s}/${m.name}`:m.name,m)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await tt(r,s),f=await r.getByName(a,c)??await Tr(r,a,c,i?.contentType);return{url:Re(n,o,f.id),expiresAt:F(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await re(r,s),c=a?await r.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw u.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(c.id),expiresAt:F(i?.expiresIn)}}}}function nt(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){A(n,r);let i=await U(o);return ht(i.byteLength),e.put(n,i,s)},async get(n){return A(n,r),e.get(n)},async head(n){return A(n,r),e.head(n)},async delete(n){return A(n,r),e.delete(n)},async deleteMany(n){let o=Pe(n);return Ae(o,r),e.deleteMany(o)},async list(n,o){let s=Pe(n??"");return Ae(s,r),e.list(s,o)},async getUploadUrl(n,o){return A(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return A(n,r),e.getDownloadUrl(n,o)}}}function Lo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ar(){if(Lo())return nt(Pr());let e=y().projectRoot;return nt(br(),{maxPathBytes:e?wt(e):void 0})}function _r(e,t){let{statusCode:r,message:n}=jo(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function jo(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_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 No=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Bo(e){return e.toLowerCase().includes("tray_lid")}function ot(e){let t={};for(let[r,n]of Object.entries(e))if(!No.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let i=s.split("=")[0].trim();return!Bo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function qo(e,t){let{inputSchema:r,outputSchema:n}=Go(t),o=e;return Ho(async s=>{let i=y(),{executionId:a,userId:c,deploymentId:d}=Xo(i,s),f=Date.now(),m=new Date().toISOString(),l=$o(s),p=Ko(s).pathname,g=Zo(),w=$t(),q=`${l} ${p}`;Ne();let V={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Vo(()=>pe.run(V,()=>fe.run(a,async()=>{let oe=await Wo(s,r);if(!oe.ok)return{response:oe.response,errored:!1,errorMessage:null};let Kr=es(s,oe.input,g,w,l,p,a,d,c);return zo(o,Kr,n,s,w,a,d,{method:l,path:p,rawInput:oe.input})})),{executionId:a,deploymentId:d,routeOrJob:q,startedAt:m,startMs:f,userId:c,flags:V})})}async function Vo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Ue({...t,errored:r,errorMessage:n}),await Be()}}async function Wo(e,t){try{return{ok:!0,input:await Ht(e,t)}}catch(r){let n=Qo(e,r);if(n)return{ok:!1,response:n};throw r}}async function zo(e,t,r,n,o,s,i,a){return R.startActiveSpan("function",{root:!0,kind:Mo.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async c=>{t.traceId=c.spanContext().traceId;let d=ot(Fr(n)),f=c.spanContext().spanId;x(f,"input",a.rawInput),x(f,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let m=!1,l=null,p,g;try{let w=await pt.run(t,()=>e(t));if(p=w,w==null)n.node.res.statusCode=204,g="";else if(w instanceof Response)g=w;else if(r){let q=r.safeParse(w);if(!q.success){let V=Object.keys(q.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:V,executionId:s}),u.outputValidationFailed(V)}g=q.data}else g=w}catch(w){m=!0,l=w instanceof Error?w.message:String(w),C("hasError"),g=Jo(w,n,o,s)}finally{Yo(c,n,{errored:m,errorMessage:l,handlerResult:p,response:g})}return{response:g,errored:m,errorMessage:l}})}function Jo(e,t,r,n){if(e instanceof X)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(mt(e))return _r(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 Yo(e,t,r){let n=e.spanContext().spanId;e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&x(n,"output",r.handlerResult),x(n,"response",r.response);let o=pe.getStore();e.setAttribute("hasAuth",o?.hasAuth??!1),e.setAttribute("hasExternal",o?.hasExternal??!1),e.setAttribute("hasDb",o?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let s=r.errored||(o?.hasError??!1);e.setStatus({code:s?Dr.ERROR:Dr.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Go(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 Xo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:Or(t,"x-tray-execution-id"))??Uo(),o=(r?e.userId:Or(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Zo(){try{return v().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function Qo(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 es(e,t,r,n,o,s,i,a,c){return{input:t,method:o,path:s,headers:ot(Fr(e)),http:Xt(),db:d=>qe(d),kv:()=>lr(),files:()=>Ar(),log:n,config:r,status:Kt(e),error:qt(),state:{},request:e,executionId:i,deploymentId:a,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function ts(e){return e}import{resolve as st}from"path";import{existsSync as Nr}from"fs";import{loadConfig as ns}from"c12";import{z as E}from"zod";import{z as rs}from"zod";var Lr=["production"],Te=rs.enum(Lr);var it=E.string().uuid("projectId must be a valid UUID"),at=E.string().min(1,"workspaceId must be a non-empty string"),os=E.object({name:E.string().min(1,"name is required"),projectId:it.optional(),workspaceId:at.optional(),env:Te.default("production"),authentications:E.record(E.string()).optional().default({}),config:E.record(E.unknown()).optional().default({})}),jr=E.object({name:E.string().min(1,"name is required"),workspaceId:at.optional(),env:Te,authentications:E.record(E.string()),config:E.record(E.unknown())}),ss=E.discriminatedUnion("kind",[jr.extend({kind:E.literal("provisioned"),projectId:it}),jr.extend({kind:E.literal("unprovisioned")})]),Br=["helix","tray"],Ur=["ts","mts","cts","js","mjs","cjs"];function Ie(e){for(let t of Br)for(let r of Ur){let n=st(e,`${t}.config.${r}`);if(Nr(n))return n}}function is(e){for(let t of Br)if(Ur.some(r=>Nr(st(e,`${t}.config.${r}`))))return t;return"helix"}function ct(e){return{name:is(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function ut(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw u.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=os.safeParse(e);if(!r.success){let a=r.error.issues.map(c=>c.message).join("; ");throw u.configLoadFailed(`Invalid helix.config.ts at ${t}: ${a}`)}let{projectId:n,workspaceId:o,...s}=r.data,i=o!==void 0?{workspaceId:o}:{};return n!==void 0?{kind:"provisioned",projectId:n,...s,...i}:{kind:"unprovisioned",...s,...i}}async function ne(e){let t=e??process.cwd(),r;try{r=await ns(ct(t))}catch(o){throw u.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??Ie(t);if(!n)throw u.configLoadFailed(`helix.config.ts not found at ${st(t,"helix.config.ts")}`);return ut(r.config,n)}var Mr="WORKSPACE_ID_REQUIRED";function as(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:Mr});return e.workspaceId}import{existsSync as cs,watch as us,writeSync as ds}from"fs";import{join as ls,resolve as fs}from"path";import{watchConfig as ps}from"c12";function ms(e,t){let r=e instanceof Error?e.message:String(e);ds(2,`[helix-watch] ${t.phase} error: ${r}
8
- `)}function dt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var gs=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,Hr=new Set;function $r(e){return Ie(e)!==void 0}async function ys(e,t){if($r(e.cwd))try{return{current:await ne(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:dt(),initialLoadSucceeded:!1}}if(e.watch){let r=fs(e.cwd);Hr.has(r)||(process.stderr.write(`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
9
- `),Hr.add(r))}return{current:dt(),initialLoadSucceeded:!1}}var lt=class{constructor(t,r,n){this.cwd=t;this.onError=r;this.emit=n}cwd;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=ps({...ct(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=ut(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,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){try{this.directoryWatcher=us(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();gs.test(n)&&cs(ls(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await ne(this.cwd)}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function hs(e){let t=e.onError??ms,r=new Set,n=await ys(e,t),o=n.current;function s(a){o=a;for(let c of[...r])try{c(a)}catch(d){t(d,{phase:"reload"})}}let i=new lt(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!$r(e.cwd)){let a=dt();return s(a),a}try{let a=await ne(e.cwd);return s(a),a}catch(a){return t(a,{phase:"reload"}),o}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}export{Lr as ENVIRONMENT_VALUES,Mr as WORKSPACE_ID_REQUIRED_CODE,hs as createConfigService,ts as defineConfig,qo as defineFunction,Te as environmentSchema,qr as getContext,y as getSdkConfig,ne as loadConfig,ss as loadedTrayConfigSchema,it as projectIdSchema,as as requireWorkspaceId,Ie as resolveConfigFile,wn as runWithinAppSpan,at as workspaceIdSchema};
1
+ import{a as ht,b as zr}from"./chunk-L6J5L3JQ.js";import{a as T,b as D,d as y,e as O,f as I,g as pt,j as E,l as J,m as A,n as Ae,o as _e,p as Et,q as L,r as St,s as ae,t as ce,u as ue,v as xt}from"./chunk-KURGNIK4.js";import{a as z,b as ie,c as vt,d as bt}from"./chunk-5XNPF4RA.js";import{b as mt,d as F,e as gt,i as yt,l as u,m as wt}from"./chunk-ATJUJXR7.js";import{randomUUID as Uo}from"crypto";import{SpanStatusCode as jr,SpanKind as Mo}from"@opentelemetry/api";import{AsyncLocalStorage as Kt}from"async_hooks";import{trace as cn,SpanKind as un,SpanStatusCode as Fe}from"@opentelemetry/api";import{ExportResultCode as dn,W3CTraceContextPropagator as ln}from"@opentelemetry/core";import{NodeTracerProvider as fn,SimpleSpanProcessor as pn,BatchSpanProcessor as mn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Jr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Yr}from"@opentelemetry/exporter-logs-otlp-proto";function De(e){return F(e).hosts.ingest}function Gr(){return I()??""}function Ct(){return{[T]:Gr()}}function Rt(){let e=De(E().env);return new Jr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Ct())})}function kt(){let e=De(E().env);return new Yr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Ct())})}import{logs as Pt,SeverityNumber as de}from"@opentelemetry/api-logs";import{LoggerProvider as Qr,BatchLogRecordProcessor as en}from"@opentelemetry/sdk-logs";function Y(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Xr(e){return new TextEncoder().encode(e).length}var Tt="\u2026[truncated]",Zr=Xr(Tt),j=4096;function _(e,t=j){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Zr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Tt}function v(e,t=j){return _(Y(e),t)}var tn="@trayai/helix-sdk",G,It={debug:{number:de.DEBUG,text:"DEBUG"},info:{number:de.INFO,text:"INFO"},warn:{number:de.WARN,text:"WARN"},error:{number:de.ERROR,text:"ERROR"}};function rn(){return y().mode==="lambda"?[new en({exporter:kt()})]:[]}function At(){if(G!==void 0)return;let e=rn();e.length!==0&&(G=new Qr({processors:e}),Pt.setGlobalLoggerProvider(G))}function nn(e,t,r){let n=It[e]??It.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":v(r)}}:{}}}function _t(e,t,r){Pt.getLogger(tn).emit(nn(e,t,r))}async function Dt(e=2e3){if(G===void 0)return;let t;try{await Promise.race([G.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 on(){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 k(e,t){return on()?`\x1B[${e}m${t}\x1B[0m`:t}var sn=5,an={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ot="32",Ft="31",le="2",Lt="1";function fe(e){return k(an[e]??"0",e.padEnd(sn))}function jt(e,t){return`${fe("FN")} ${k(Lt,`${e} ${t}`.trim())}`}function Nt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${k(le,n)} `:""}${fe(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${k(le,Y(r))}`),i}function Bt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Ut(e){return`${fe("AUTH")} ${e}`}function Mt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=k(o==="error"?Ft:Ot,s);return`${fe("API")} ${e} ${t} \u2192 ${i} ${k(le,`${n}ms`)}`}function $t(e,t,r){let n=t?Ft:Ot,o=k(n,"\u25CF"),s=k(n,t?"error":"success");return`${o} ${k(Lt,e)} ${s} ${k(le,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var pe=new Kt,me=new Kt;function C(e){let t=me.getStore();t&&(t[e]=!0)}var gn=/^[0-9a-f]{32}$/;function yn(e){let t=e.replace(/-/g,"").toLowerCase();return gn.test(t)?t:null}var hn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},B=new Map;function x(e,t,r){let n=B.get(e);n?n[t]=r:B.set(e,{[t]:r})}var X;function Ht(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function wn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function qt(e){try{process.stdout.write(Y(e)+`
4
+ `)}catch{}}var Le=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=B.get(o),i={...n.attributes};if(s!==void 0){for(let[d,l]of Object.entries(s))typeof l=="string"?i[d]=_(l):typeof l=="object"&&l!==null?i[d]=v(l):i[d]=l;B.delete(o)}let a=pe.getStore(),c=a?yn(a):null;qt({_otel:"span",traceId:c??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Ht(n.startTime),endTimeUnixNano:Ht(n.endTime),attributes:i,status:{code:hn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:dn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t,r){}onEnd(t){B.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
+ `+jt(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=B.get(n)?.properties;N(Nt(String(r.level??"info"),String(r.message??""),o,Bt(t.startTime)));break}case"auth":N(Ut(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(Mt(String(r.method??""),String(r.host??""),n,wn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function vn(){let t=[Oe()?new Ne:new pn(new Le)];return y().mode==="lambda"&&t.push(new mn(Rt())),t.push(new je),t}function Be(){X===void 0&&(X=new fn({spanProcessors:vn()}),X.register({propagator:new ln}),At())}async function Ue(e=2e3){let t=[Dt(e)];X!==void 0&&t.push((async()=>{let r;try{await Promise.race([X.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 R=cn.getTracer("@trayai/helix-sdk");function Me({executionId:e,deploymentId:t,routeOrJob:r,startedAt:n,startMs:o,errored:s,errorMessage:i,userId:a,flags:c}){let d=new Date().toISOString(),l=Date.now()-o;if(Oe()){N(`
7
+ `+$t(r,s,l));return}qt({_otel:"summary",executionId:e,deploymentId:t,triggerType:"http",routeOrJob:r,status:s?"error":"success",startedAt:n,finishedAt:d,durationMs:l,userId:a,hasError:s||c.hasError,hasAuth:c.hasAuth,hasExternal:c.hasExternal,hasDb:c.hasDb,errorSummary:s&&i!==null?_(i):null})}async function bn(e,t){let r=e.startMs??Date.now();Be();let n=!1,o=null;try{return await pe.run(e.executionId,()=>R.startActiveSpan("App",{kind:un.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?Fe.ERROR:Fe.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:Fe.ERROR,message:o}),i}finally{s.end()}}))}finally{Me({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 Ue()}}import{defineEventHandler as $o,getMethod as Ho,getRequestURL as Ko,getHeaders as Br,getHeader as Nr}from"h3";import{readBody as En,getQuery as Sn,getRouterParams as xn}from"h3";async function Vt(e,t){let r=await Cn(e),n=Sn(e),o=xn(e)??{},s={...n,...r,...o};return t?Rn(s,t):s}async function Cn(e){try{let t=await En(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 Rn(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}import{SpanKind as kn}from"@opentelemetry/api";function ge(e,t,r){let n=R.startSpan("log",{kind:kn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&x(n.spanContext().spanId,"properties",r),n.end(),_t(e,t,r)}function Wt(){return{info:(e,t)=>ge("info",e,t),warn:(e,t)=>ge("warn",e,t),error:(e,t)=>ge("error",e,t),debug:(e,t)=>ge("debug",e,t)}}var Z=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function zt(e){return t=>{e.node.res.statusCode=t}}function Jt(){return(e,t)=>{throw new Z(e,t)}}import Pn from"ky";import{context as $e,trace as An,SpanKind as he,SpanStatusCode as Xt}from"@opentelemetry/api";import Tn from"ky";async function Yt(e,t={}){let r=O(),n=I(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw u.missingExecutionCredentials();let{env:i}=E(),a=ie(i),c=t.timeout??6e4,d={Accept:"application/json"};o&&(d[D]=r),s&&(d[T]=n);let l=y().deploymentId,m=l?{...e,deploymentId:l}:e,f=await Tn.post(`${a}/broker/http`,{json:m,headers:d,throwHttpErrors:!1,timeout:c}),p;return(f.headers.get("content-type")??"").includes("application/json")?p=await f.json():p=await f.text(),{status:f.status,body:p}}import In from"ky";async function Gt(e,t={}){let r=pt();if(!r)throw u.missingTrayToken();let{env:n}=E(),o=ie(n),s=t.timeout??6e4,i=await In.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:s}),a;return(i.headers.get("content-type")??"").includes("application/json")?a=await i.json():a=await i.text(),{status:i.status,body:a}}async function ye(e,t={}){let r=y().mode==="lambda"?Yt:Gt,n;try{n=await r(e,t)}catch(a){if(a instanceof u)throw a;let c=a instanceof Error?a.message??String(a):String(a);throw u.brokerError(0,c)}let{status:o,body:s}=n;if(o<200||o>=300){let a;if(s!==null&&typeof s=="object"){let c=s;typeof c.message=="string"?a=c.message:typeof c.error=="string"?a=c.error:a=String(s)}else a=String(s);throw u.brokerError(o,a,v(s))}let i=vt.safeParse(s);if(!i.success)throw u.brokerError(o,"broker returned malformed response",v(s));return bt(i.data)}var _n=["get","post","put","patch","delete","head","options"],Zt="[stream body omitted]";function He(e){try{return new URL(e).hostname}catch{return e}}function Dn(e,t,r,n){let o=He(t),s="externalApi",i={kind:he.CLIENT};return R.startActiveSpan(s,i,async a=>{let c=a.spanContext().spanId;return a.setAttributes({method:e,host:o}),x(c,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?Zt:r}:{}}),n(a,c)})}function Ke(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Xt.OK}:{code:Xt.ERROR,message:r}),e.end()}var On=16;async function Fn(e,t){let r=e.clone().body;return r?Qt(r,t):new Uint8Array(0)}async function Qt(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:c,value:d}=await r.read();if(c)break;if(!d||d.byteLength===0){if(s+=1,s>=On)break;continue}s=0;let l=t+1-o;if(d.byteLength>=l){n.push(d.slice(0,l)),o+=l;break}n.push(d),o+=d.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of n)i.set(c,a),a+=c.byteLength;return i}async function er(e,t,r){if("kyResponse"in r)try{let n=await Fn(r.kyResponse,j),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;if(n.length<=j)try{s=JSON.parse(o)}catch{s=o}else s=o;x(e,"response",s)}catch{x(e,"response",{status:t})}else x(e,"response",r.bodyValue)}async function Ln(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 Qt(o,j);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:Zt}}}return typeof t=="string"?{body:t}:{}}function tr(){let e=Pn.create({});function t(n){return(o,s)=>{let i=$e.active(),a,c="",d=!1,l=(f,p)=>{a&&!d&&(d=!0,Ke(a,f,p))},m=e.extend({hooks:{beforeRequest:[async(f,p)=>{let g=await Ln(f,p.body),w=g.body;if(a||(a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId),a.setAttributes({method:f.method.toUpperCase(),host:He(f.url)}),x(c,"request",{url:f.url,method:f.method.toUpperCase(),...w!==void 0?{body:w}:{}}),d=!1,C("hasExternal"),g.request)return g.request}],beforeRetry:[f=>{l("error","retry"),a=void 0,c="",d=!1}],afterResponse:[async(f,p,g)=>{a&&(a.setAttribute("statusCode",g.status),await er(c,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(C("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[f=>(C("hasError"),l("error",f.message),f)]}});return a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId,a.setAttributes({method:n.toUpperCase(),host:He(String(o))}),$e.with(An.setSpan($e.active(),a),()=>{let f=n==="options"?m(o,{...s,method:"OPTIONS"}):m[n](o,s);return f.catch(p=>{C("hasError"),l("error",p instanceof Error?p.message:String(p))}),f})}}let r=Object.fromEntries(_n.map(n=>[n,t(n)]));return{...e,...r,authed(n){return jn(n)}}}function jn(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(i,a={})=>{let c=s.toUpperCase();return Dn(c,i,a.body,async(d,l)=>{C("hasAuth");let m=R.startSpan("auth",{kind:he.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let f=z({authenticationId:n,method:c,url:i,body:a.body,headers:a.headers,query:a.query}),p=await ye(f,{timeout:a.timeout});return d.setAttribute("statusCode",p.status),await er(l,p.status,{bodyValue:p.body}),Ke(d,"success"),p}catch(f){throw C("hasError"),f instanceof u&&f.detail.kind==="broker_error"&&f.detail.status>0&&d.setAttribute("statusCode",f.detail.status),Ke(d,"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")}}import{SpanKind as Vn,SpanStatusCode as sr}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Nn=18e4,rr=Nn-1e4,Bn=2e3;async function nr(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<rr;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let c=Math.min(Bn,200*2**s),d=c/2+Math.random()*(c/2),l=rr-(Date.now()-o);await new Promise(m=>setTimeout(m,Math.min(d,l))),s++}throw u.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Un=new Set(["SELECT","WITH","SHOW"]),Mn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function $n(e){if(!e.clusterIdentifier&&!e.workgroupName)throw u.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw u.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw u.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw u.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw u.dbInvalidParameters("region is required")}function Hn(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 u.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):v(t);return u.dbCallFailed(s)}function Kn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw u.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function qn(e,t){return typeof t!="number"||t<0?{}:Un.has(e)?{rowsRead:t}:Mn.has(e)?{rowsWritten:t}:{}}function or(e){async function t(r,n,o){let s=z({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 ye(s);if(i>=400)throw Hn(i,a);return Kn(a)}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw u.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:$n,async execute(r,n){let o=Q(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,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let p=v(i);throw u.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let d=await nr(t,r.region,c),l=d.Status;if(l==="FAILED"){let p=typeof d.Error=="string"?d.Error:"statement failed";throw u.dbQueryFailed(`${p} (statement: ${c})`)}if(l==="ABORTED")throw u.dbQueryFailed(`statement aborted (statement: ${c})`);let m=qn(o,d.ResultRows);return d.HasResultSet===!1?{result:{rowsAffected:d.ResultRows??0},metadata:m}:{result:await t(r.region,"GetStatementResult",{Id:c}),metadata:m}}}}var qe=64*1024;function Wn(e){return e.length>qe?`${e.slice(0,qe)}...[truncated]`:e}function zn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Jn(e,t,r,n){let o=typeof r=="string"?r:JSON.stringify(r);return o.length>qe?x(t,"result",{truncated:!0,size:o.length}):x(t,"result",r),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),o}async function Yn(e,t,r){let n=Q(r),o=Wn(r);return R.startActiveSpan("database",{kind:Vn.CLIENT},async s=>{let i=s.spanContext().spanId;zn(s,e,t,n,o);try{C("hasDb");let{result:a,metadata:c}=await e.execute(t,r),d=Jn(s,i,a,c);return s.setAttribute("status","success"),s.setStatus({code:sr.OK}),d}catch(a){C("hasError");let c=a instanceof Error?a.message:String(a);throw s.setAttribute("status","error"),s.setStatus({code:sr.ERROR,message:c}),a}finally{s.end()}})}function Ve(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e],o=or(n);function s(i,a){return o.validate(i),Yn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as eo}from"unstorage";var ir=1024,We=250*1024,Gn=new TextEncoder,Xn=/(^|\/)\.\.(\/|$)/,Zn=/[?#]/,Qn=/[\u0000-\u001F\u007F]/;function ar(e){if(e.length===0)throw u.kvKeyInvalid("Key must be a non-empty string");if(Xn.test(e))throw u.kvKeyInvalid("Key contains path traversal segment");if(Zn.test(e)||Qn.test(e))throw u.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw u.kvKeyInvalid("Key must not contain empty path segments");let t=Gn.encode(e).length;if(t<1||t>ir)throw u.kvKeyInvalid(`Key must be between 1 and ${ir} UTF-8 bytes (got ${t})`)}function cr(e){let t;try{t=JSON.stringify(e)}catch{throw u.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw u.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>We)throw u.kvValueTooLarge(`Value exceeds maximum size of ${We} bytes (got ${r})`,We)}function ee(e){ar(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function ur(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 ee(i),t(i,a)},setItem(i,a,c){return ee(i),r(i,a,c)},removeItem(i,a){return ee(i),n(i,a)},hasItem(i,a){return ee(i),o(i,a)},getKeys(i,a){return i.length>0&&ee(i),s(i,a)}}}function ve(e){return eo({driver:ur(e)})}import{defineDriver as to}from"unstorage";function ro(e){try{return JSON.parse(e)}catch{return e}}var no=to(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){await t.set(r,ro(n))},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 dr(e){return no({client:e})}import io from"ky";import{z as b}from"zod";async function U(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 lr(e){return F(e).hosts.api}function oo(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function so(e){return e.split("/").map(encodeURIComponent).join("/")}function te(e,t,r){return`${e}${oo(t)}/${so(r)}`}var ao=6e4,ze=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(ze),b.record(ze)])),co=b.object({projectId:b.string(),key:b.string(),value:ze,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 uo(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function lo(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 be(e,t){throw u.kvCallFailed(e,lo(t),v(t))}async function Ee(e,t,r={}){try{let n=await io(t,{method:e,headers:uo(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ao}),o=e==="head"?void 0:await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw u.kvCallFailed(0,o)}}function fr(e){let t=lr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",te(t,r,n));if(o===404)return null;(o<200||o>=300)&&be(o,s);let i=co.safeParse(s);if(!i.success)throw u.kvCallFailed(o,"platform returned malformed KeyValueEntry",v(s));return i.data.value},async set(n,o){let{status:s,body:i}=await Ee("put",te(t,r,n),{json:{value:o}});(s<200||s>=300)&&be(s,i)},async delete(n){let{status:o,body:s}=await Ee("delete",te(t,r,n));o!==204&&be(o,s)},async has(n){let{status:o,body:s}=await Ee("head",te(t,r,n));if(o===200)return!0;if(o===404)return!1;be(o,s)}}}function Se(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{cr(r),await e.setItem(t,r,n)}}}function fo(){let e=E();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function pr(e){let t=fo(),r=e??fr(t),n=ve(dr(r));return Se(n)}import po from"unstorage/drivers/memory";var Je;function mo(){return Je||(Je=ve(po())),Je}function mr(){return Se(mo())}function go(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function gr(){return go()?pr():mr()}import{createHash as wo}from"crypto";import{mkdir as vo,readFile as br,readdir as Er,rm as hr,unlink as bo,writeFile as wr}from"fs/promises";import{dirname as Eo}from"path";async function yo(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>J)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${J} bytes (got more than ${J})`,J);r.push(s)}}return Buffer.concat(r)}async function M(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?yo(e):Buffer.from(e)}var ho={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"},yr="application/octet-stream";function xe(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return yr;let r=e.slice(t+1).toLowerCase();return ho[r]??yr}function H(){let e=y().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function $(e){try{return await e()}catch(t){if(t instanceof u)throw t;let r=t?.code;throw r?u.filesCallFailed(0,`Local file storage operation failed: ${r}`):u.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Ce(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ye(e){try{let t=await br(ce(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function vr(e){await vo(Eo(e),{recursive:!0})}async function So(e,t){let r=ue(e,t),n;try{n=await Er(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 Sr(e,t){let r=ue(e,t),n;try{n=await Er(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 Sr(e,i)):s.isFile()&&o.push(i)}return o}function xr(){return{async put(e,t,r){return $(async()=>{let n=H(),o=await M(t),s=r?.contentType??xe(e),i=wo("sha1").update(o).digest("hex"),a=new Date,c=ae(n,e);await vr(c),await wr(c,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},l=ce(n,e);return await vr(l),await wr(l,JSON.stringify(d)),Ce(e,d)})},async get(e){return $(async()=>{let t=await Ye(e);return t?{data:await br(ae(H(),e)),metadata:Ce(e,t)}:null})},async head(e){return $(async()=>{let t=await Ye(e);return t?Ce(e,t):null})},async delete(e){return $(async()=>{let t=H();await Promise.all([ae(t,e),ce(t,e)].map(async r=>{try{await bo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return $(async()=>{let t=H(),r=await Sr(t,e);return await Promise.all([hr(ue(t,e),{recursive:!0,force:!0}),hr(xt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return $(async()=>{let r=H(),n=t?.limit??100,s=(await So(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let c=await Ye(a);return c?Ce(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}}}}import{createHash as Po}from"crypto";function Re(e){return F(e).hosts.api}function xo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function re(e,t){return`${e}${xo(t)}`}function K(e,t,r){return`${re(e,t)}/${encodeURIComponent(r)}`}function ke(e,t,r){return`${K(e,t,r)}/upload`}function Cr(e,t,r){return`${K(e,t,r)}/download`}function Rr(e,t,r){return`${K(e,t,r)}/signed-url`}function kr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${re(e,t)}/file?${o.toString()}`}function Tr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${re(e,t)}?${o.toString()}`}import Xe from"ky";import{z as h}from"zod";var Ze=6e4,Ir=h.object({id:h.string(),workspaceId:h.string(),projectId:h.string(),parentFolder:h.string().nullable().optional(),name:h.string(),size:h.number().nullable().optional(),objectType:h.enum(["Folder","File"]),contentType:h.string().nullable().optional(),createdAt:h.string(),updatedAt:h.string()}),Co=h.object({signedURL:h.string()}),Ro=h.object({path:h.array(h.object({id:h.string(),name:h.string()})),elements:h.array(Ir)});function Qe(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function Pr(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 P(e,t){throw u.filesCallFailed(e,Pr(t),v(t))}function ko(e,t){return e===400&&Pr(t).toLowerCase()==="resource not found"}async function To(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 q(e,t,r={}){try{let n=await Xe(t,{method:e,headers:Qe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ze}),o=await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message:String(n);throw u.filesCallFailed(0,o)}}function Ge(e,t){let r=Ir.safeParse(t);if(!r.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",v(t));return r.data}function Ar(e){let t=Re(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await q("post",re(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Ge(o,s)},async getByName(n,o){let{status:s,body:i}=await q("get",kr(t,r,n,o));return s===404||ko(s,i)?null:((s<200||s>=300)&&P(s,i),Ge(s,i))},async getById(n){let{status:o,body:s}=await q("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Ge(o,s))},async listChildren(n,o){let{status:s,body:i}=await q("get",Tr(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=Ro.safeParse(i);if(!a.success)throw u.filesCallFailed(s,"platform returned malformed listing",v(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:c,contentType:d}=await To(a),l;try{l=await Xe(ke(t,r,n),{method:"post",headers:{...Qe(),"content-type":d},body:new Uint8Array(c),throwHttpErrors:!1,timeout:Ze})}catch(f){if(f instanceof u)throw f;let p=f instanceof Error?f.message:String(f);throw u.filesCallFailed(0,p)}let m=await U(l);(l.status<200||l.status>=300)&&P(l.status,m)},async downloadContent(n){let o;try{o=await Xe(Cr(t,r,n),{method:"get",headers:Qe(),throwHttpErrors:!1,timeout:Ze})}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message:String(i);throw u.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await U(o);P(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await q("get",Rr(t,r,n));(o<200||o>=300)&&P(o,s);let i=Co.safeParse(s);if(!i.success)throw u.filesCallFailed(o,"platform returned malformed signed URL response",v(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await q("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function et(e){return e.split("/").filter(t=>t.length>0)}function tt(e){return e instanceof u&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Io(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(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function rt(e,t){let r=et(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await Io(e,o,s)).id;return{parentFolder:o,name:n}}async function ne(e,t){let r=et(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 nt(e,t){if(t.length===0)return;let r=et(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 Ao=500,_o=8;async function Do(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 Oo(){let e=E();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Fo(e){return Po("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Te(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Fo(t)}}async function _r(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Dr(e,t){let{elements:r}=await e.listChildren(t,Ao);return(await Do(r,_o,async o=>{let s=o.objectType==="Folder"?await Dr(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Or(e){let t=Oo(),r=e??Ar(t),n=Re(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:d}=await rt(r,s),l=await M(i),m=a?.contentType??xe(s),f=await r.getByName(c,d);if(f&&f.objectType!=="File")throw u.filesCallFailed(409,`A folder already exists at "${s}"`);let p=f??await _r(r,c,d,m);await r.uploadContent(p.id,l,d,m);let g=await r.getById(p.id);return Te(s,g??p,m)},async get(s){let i=await ne(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:Te(s,a)}},async head(s){let i=await ne(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Te(s,a)},async delete(s){let i=await ne(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 nt(r,s);if(i===null)return{deleted:0};let a=await Dr(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await nt(r,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:d}=await r.listChildren(a,c);return{files:d.filter(m=>m.objectType==="File").map(m=>Te(s?`${s}/${m.name}`:m.name,m)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await rt(r,s),l=await r.getByName(a,c)??await _r(r,a,c,i?.contentType);return{url:ke(n,o,l.id),expiresAt:L(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await ne(r,s),c=a?await r.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw u.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(c.id),expiresAt:L(i?.expiresIn)}}}}function ot(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){A(n,r);let i=await M(o);return Et(i.byteLength),e.put(n,i,s)},async get(n){return A(n,r),e.get(n)},async head(n){return A(n,r),e.head(n)},async delete(n){return A(n,r),e.delete(n)},async deleteMany(n){let o=Ae(n);return _e(o,r),e.deleteMany(o)},async list(n,o){let s=Ae(n??"");return _e(s,r),e.list(s,o)},async getUploadUrl(n,o){return A(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return A(n,r),e.getDownloadUrl(n,o)}}}function Lo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Fr(){if(Lo())return ot(Or());let e=y().projectRoot;return ot(xr(),{maxPathBytes:e?St(e):void 0})}function Lr(e,t){let{statusCode:r,message:n}=jo(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function jo(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_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 No=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Bo(e){return e.toLowerCase().includes("tray_lid")}function st(e){let t={};for(let[r,n]of Object.entries(e))if(!No.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let i=s.split("=")[0].trim();return!Bo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function qo(e,t){let{inputSchema:r,outputSchema:n}=Go(t),o=e;return $o(async s=>{let i=y(),{executionId:a,userId:c,deploymentId:d}=Xo(i,s),l=Date.now(),m=new Date().toISOString(),f=Ho(s),p=Ko(s).pathname,g=Zo(),w=Wt(),V=`${f} ${p}`;Be();let W={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Vo(()=>me.run(W,()=>pe.run(a,async()=>{let se=await Wo(s,r);if(!se.ok)return{response:se.response,errored:!1,errorMessage:null};let Wr=es(s,se.input,g,w,f,p,a,d,c);return zo(o,Wr,n,s,w,a,d,{method:f,path:p,rawInput:se.input})})),{executionId:a,deploymentId:d,routeOrJob:V,startedAt:m,startMs:l,userId:c,flags:W})})}async function Vo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Me({...t,errored:r,errorMessage:n}),await Ue()}}async function Wo(e,t){try{return{ok:!0,input:await Vt(e,t)}}catch(r){let n=Qo(e,r);if(n)return{ok:!1,response:n};throw r}}async function zo(e,t,r,n,o,s,i,a){return R.startActiveSpan("function",{root:!0,kind:Mo.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async c=>{t.traceId=c.spanContext().traceId;let d=st(Br(n)),l=c.spanContext().spanId;x(l,"input",a.rawInput),x(l,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let m=!1,f=null,p,g;try{let w=await ht.run(t,()=>e(t));if(p=w,w==null)n.node.res.statusCode=204,g="";else if(w instanceof Response)g=w;else if(r){let V=r.safeParse(w);if(!V.success){let W=Object.keys(V.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:W,executionId:s}),u.outputValidationFailed(W)}g=V.data}else g=w}catch(w){m=!0,f=w instanceof Error?w.message:String(w),C("hasError"),g=Jo(w,n,o,s)}finally{Yo(c,n,{errored:m,errorMessage:f,handlerResult:p,response:g})}return{response:g,errored:m,errorMessage:f}})}function Jo(e,t,r,n){if(e instanceof Z)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(wt(e))return Lr(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 Yo(e,t,r){let n=e.spanContext().spanId;e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&x(n,"output",r.handlerResult),x(n,"response",r.response);let o=me.getStore();e.setAttribute("hasAuth",o?.hasAuth??!1),e.setAttribute("hasExternal",o?.hasExternal??!1),e.setAttribute("hasDb",o?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let s=r.errored||(o?.hasError??!1);e.setStatus({code:s?jr.ERROR:jr.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Go(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 Xo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:Nr(t,"x-tray-execution-id"))??Uo(),o=(r?e.userId:Nr(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Zo(){try{return E().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function Qo(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 es(e,t,r,n,o,s,i,a,c){return{input:t,method:o,path:s,headers:st(Br(e)),http:tr(),db:d=>Ve(d),kv:()=>gr(),files:()=>Fr(),log:n,config:r,status:zt(e),error:Jt(),state:{},request:e,executionId:i,deploymentId:a,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function ts(e){return e}import{resolve as it}from"path";import{existsSync as Mr}from"fs";import{loadConfig as os}from"c12";import{z as S}from"zod";import{z as rs}from"zod";var ns=["production"],Ie=rs.string().refine(e=>mt(e),e=>({message:`Invalid enum value. Expected ${gt().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var at=S.string().uuid("projectId must be a valid UUID"),ct=S.string().min(1,"workspaceId must be a non-empty string"),ss=S.object({name:S.string().min(1,"name is required"),projectId:at.optional(),workspaceId:ct.optional(),env:Ie.default("production"),authentications:S.record(S.string()).optional().default({}),config:S.record(S.unknown()).optional().default({})}),Ur=S.object({name:S.string().min(1,"name is required"),workspaceId:ct.optional(),env:Ie,authentications:S.record(S.string()),config:S.record(S.unknown())}),is=S.discriminatedUnion("kind",[Ur.extend({kind:S.literal("provisioned"),projectId:at}),Ur.extend({kind:S.literal("unprovisioned")})]),$r=["helix","tray"],Hr=["ts","mts","cts","js","mjs","cjs"];function Pe(e){for(let t of $r)for(let r of Hr){let n=it(e,`${t}.config.${r}`);if(Mr(n))return n}}function as(e){for(let t of $r)if(Hr.some(r=>Mr(it(e,`${t}.config.${r}`))))return t;return"helix"}function ut(e){return{name:as(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function dt(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw u.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=ss.safeParse(e);if(!r.success){let d=r.error.issues.map(l=>l.message).join("; ");throw u.configLoadFailed(`Invalid helix.config.ts at ${t}: ${d}`)}let{projectId:n,workspaceId:o,...s}=r.data,i=o!==void 0?{workspaceId:o}:{},a=yt(),c=a!==void 0?{...s,env:a}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...i}:{kind:"unprovisioned",...c,...i}}async function oe(e){let t=e??process.cwd(),r;try{r=await os(ut(t))}catch(o){throw u.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??Pe(t);if(!n)throw u.configLoadFailed(`helix.config.ts not found at ${it(t,"helix.config.ts")}`);return dt(r.config,n)}var Kr="WORKSPACE_ID_REQUIRED";function cs(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:Kr});return e.workspaceId}import{existsSync as us,watch as ds,writeSync as ls}from"fs";import{join as fs,resolve as ps}from"path";import{watchConfig as ms}from"c12";function gs(e,t){let r=e instanceof Error?e.message:String(e);ls(2,`[helix-watch] ${t.phase} error: ${r}
8
+ `)}function lt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ys=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,qr=new Set;function Vr(e){return Pe(e)!==void 0}async function hs(e,t){if(Vr(e.cwd))try{return{current:await oe(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:lt(),initialLoadSucceeded:!1}}if(e.watch){let r=ps(e.cwd);qr.has(r)||(process.stderr.write(`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
9
+ `),qr.add(r))}return{current:lt(),initialLoadSucceeded:!1}}var ft=class{constructor(t,r,n){this.cwd=t;this.onError=r;this.emit=n}cwd;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=ms({...ut(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=dt(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,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){try{this.directoryWatcher=ds(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();ys.test(n)&&us(fs(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await oe(this.cwd)}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function ws(e){let t=e.onError??gs,r=new Set,n=await hs(e,t),o=n.current;function s(a){o=a;for(let c of[...r])try{c(a)}catch(d){t(d,{phase:"reload"})}}let i=new ft(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!Vr(e.cwd)){let a=lt();return s(a),a}try{let a=await oe(e.cwd);return s(a),a}catch(a){return t(a,{phase:"reload"}),o}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}export{ns as ENVIRONMENT_VALUES,Kr as WORKSPACE_ID_REQUIRED_CODE,ws as createConfigService,ts as defineConfig,qo as defineFunction,Ie as environmentSchema,zr as getContext,y as getSdkConfig,oe as loadConfig,is as loadedTrayConfigSchema,at as projectIdSchema,cs as requireWorkspaceId,Pe as resolveConfigFile,bn as runWithinAppSpan,ct as workspaceIdSchema};
@@ -1,5 +1,5 @@
1
- import { L as LoadedTrayConfig } from '../sdk-config-B-Vfaig8.js';
2
- export { S as SdkConfigInput, s as setSdkConfig } from '../sdk-config-B-Vfaig8.js';
1
+ import { L as LoadedTrayConfig } from '../sdk-config-DrgARqBz.js';
2
+ export { S as SdkConfigInput, s as setSdkConfig } from '../sdk-config-DrgARqBz.js';
3
3
  import 'zod';
4
4
 
5
5
  /** BroadcastChannel name for parent→worker config updates. */
@@ -125,4 +125,47 @@ declare function isSdkError(err: unknown): err is SdkError;
125
125
  declare function contentFilePath(projectRoot: string, path: string): string;
126
126
  declare function metaFilePath(projectRoot: string, path: string): string;
127
127
 
128
- export { CONFIG_BRIDGE_CHANNEL, assertValidPath, clearActiveConfig, contentFilePath, getActiveConfig, isSdkError, metaFilePath, setActiveConfig };
128
+ interface EnvironmentHosts {
129
+ api: string;
130
+ broker: string;
131
+ ingest: string;
132
+ weaver: string;
133
+ app: string;
134
+ projectHost: string;
135
+ dashboard: string;
136
+ }
137
+ interface EnvironmentLoginInfo {
138
+ storePrefix: string;
139
+ appUrl: string;
140
+ cookieName: string;
141
+ cookieDomain: string;
142
+ }
143
+ interface EnvironmentProfile {
144
+ name: string;
145
+ exposedName: string;
146
+ displayName: string;
147
+ hosts: EnvironmentHosts;
148
+ login: EnvironmentLoginInfo;
149
+ }
150
+ /**
151
+ * Register an environment profile. Idempotent when the same profile is
152
+ * registered again; throws if a different profile reuses the same `name` or
153
+ * `exposedName`.
154
+ */
155
+ declare function registerEnvironmentProfile(profile: EnvironmentProfile): void;
156
+ declare function isKnownEnvironment(name: string): boolean;
157
+ declare function getEnvironmentProfile(name: string): EnvironmentProfile | undefined;
158
+ declare function requireEnvironmentProfile(name: string): EnvironmentProfile;
159
+ /** Internal config env names currently registered (includes built-ins). */
160
+ declare function listEnvironmentNames(): string[];
161
+ /** User-facing `--env` values for all registered profiles. */
162
+ declare function listExposedEnvNames(): string[];
163
+ /** Resolve user-facing `--env` value → internal env name. */
164
+ declare function parseExposedEnvironment(value: string): string | undefined;
165
+ declare function setForcedEnvironment(name: string | undefined): void;
166
+ declare function resolveForcedEnvironment(): string | undefined;
167
+ declare function getAdditionalEnvironmentProfiles(): EnvironmentProfile[];
168
+ /** Test helper: drop non-builtin profiles and restore production. */
169
+ declare function resetEnvironmentRegistryForTests(): void;
170
+
171
+ export { CONFIG_BRIDGE_CHANNEL, type EnvironmentProfile, assertValidPath, clearActiveConfig, contentFilePath, getActiveConfig, getAdditionalEnvironmentProfiles, getEnvironmentProfile, isKnownEnvironment, isSdkError, listEnvironmentNames, listExposedEnvNames, metaFilePath, parseExposedEnvironment, registerEnvironmentProfile, requireEnvironmentProfile, resetEnvironmentRegistryForTests, resolveForcedEnvironment, setActiveConfig, setForcedEnvironment };
@@ -1 +1 @@
1
- import{c as o,h as t,i as e,j as r,k as i,m as n,s as g,t as p}from"../chunk-EDBOWEUT.js";import{b as f}from"../chunk-W5TFZBQD.js";export{t as CONFIG_BRIDGE_CHANNEL,n as assertValidPath,i as clearActiveConfig,g as contentFilePath,r as getActiveConfig,f as isSdkError,p as metaFilePath,e as setActiveConfig,o as setSdkConfig};
1
+ import{c as e,h as n,i as o,j as r,k as t,m as x,s as P,t as C}from"../chunk-KURGNIK4.js";import{a as i,b as s,c as m,d as f,e as v,f as E,g,h as p,i as l,j as a,k as d,m as c}from"../chunk-ATJUJXR7.js";export{n as CONFIG_BRIDGE_CHANNEL,x as assertValidPath,t as clearActiveConfig,P as contentFilePath,r as getActiveConfig,a as getAdditionalEnvironmentProfiles,m as getEnvironmentProfile,s as isKnownEnvironment,c as isSdkError,v as listEnvironmentNames,E as listExposedEnvNames,C as metaFilePath,g as parseExposedEnvironment,i as registerEnvironmentProfile,f as requireEnvironmentProfile,d as resetEnvironmentRegistryForTests,l as resolveForcedEnvironment,o as setActiveConfig,p as setForcedEnvironment,e as setSdkConfig};
@@ -6,12 +6,12 @@ declare const trayConfigSchema: z.ZodObject<{
6
6
  name: z.ZodString;
7
7
  projectId: z.ZodOptional<z.ZodString>;
8
8
  workspaceId: z.ZodOptional<z.ZodString>;
9
- env: z.ZodDefault<z.ZodEnum<["production"]>>;
9
+ env: z.ZodDefault<z.ZodEffects<z.ZodString, string, string>>;
10
10
  authentications: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
11
11
  config: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
12
12
  }, "strip", z.ZodTypeAny, {
13
13
  name: string;
14
- env: "production";
14
+ env: string;
15
15
  authentications: Record<string, string>;
16
16
  config: Record<string, unknown>;
17
17
  projectId?: string | undefined;
@@ -20,7 +20,7 @@ declare const trayConfigSchema: z.ZodObject<{
20
20
  name: string;
21
21
  projectId?: string | undefined;
22
22
  workspaceId?: string | undefined;
23
- env?: "production" | undefined;
23
+ env?: string | undefined;
24
24
  authentications?: Record<string, string> | undefined;
25
25
  config?: Record<string, unknown> | undefined;
26
26
  }>;
@@ -35,7 +35,7 @@ type TrayConfig = z.input<typeof trayConfigSchema>;
35
35
  declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
36
36
  name: z.ZodString;
37
37
  workspaceId: z.ZodOptional<z.ZodString>;
38
- env: z.ZodEnum<["production"]>;
38
+ env: z.ZodEffects<z.ZodString, string, string>;
39
39
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
40
40
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
41
41
  } & {
@@ -45,7 +45,7 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
45
45
  kind: "provisioned";
46
46
  name: string;
47
47
  projectId: string;
48
- env: "production";
48
+ env: string;
49
49
  authentications: Record<string, string>;
50
50
  config: Record<string, unknown>;
51
51
  workspaceId?: string | undefined;
@@ -53,14 +53,14 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
53
53
  kind: "provisioned";
54
54
  name: string;
55
55
  projectId: string;
56
- env: "production";
56
+ env: string;
57
57
  authentications: Record<string, string>;
58
58
  config: Record<string, unknown>;
59
59
  workspaceId?: string | undefined;
60
60
  }>, z.ZodObject<{
61
61
  name: z.ZodString;
62
62
  workspaceId: z.ZodOptional<z.ZodString>;
63
- env: z.ZodEnum<["production"]>;
63
+ env: z.ZodEffects<z.ZodString, string, string>;
64
64
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
65
65
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
66
66
  } & {
@@ -68,14 +68,14 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
68
68
  }, "strip", z.ZodTypeAny, {
69
69
  kind: "unprovisioned";
70
70
  name: string;
71
- env: "production";
71
+ env: string;
72
72
  authentications: Record<string, string>;
73
73
  config: Record<string, unknown>;
74
74
  workspaceId?: string | undefined;
75
75
  }, {
76
76
  kind: "unprovisioned";
77
77
  name: string;
78
- env: "production";
78
+ env: string;
79
79
  authentications: Record<string, string>;
80
80
  config: Record<string, unknown>;
81
81
  workspaceId?: string | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.66.0",
3
+ "version": "0.68.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -43,7 +43,7 @@
43
43
  "dependencies": {
44
44
  "@opentelemetry/api": "^1.9.1",
45
45
  "@opentelemetry/api-logs": "0.220.0",
46
- "@opentelemetry/core": "^2.7.1",
46
+ "@opentelemetry/core": "^2.8.0",
47
47
  "@opentelemetry/exporter-logs-otlp-proto": "0.220.0",
48
48
  "@opentelemetry/exporter-trace-otlp-proto": "0.220.0",
49
49
  "@opentelemetry/resources": "^2.7.1",
@@ -1 +0,0 @@
1
- import{a as p}from"./chunk-W5TFZBQD.js";var l=new Set(["proxy-authorization","x-tray-token"]);function m(e){let t=e.toLowerCase();return l.has(t)||t.startsWith("x-tray-internal-")}function R(e){let t;return e instanceof Headers?t=Array.from(e.entries()):Array.isArray(e)?t=e:t=Object.entries(e),t.filter(([o])=>!m(o)).map(([o,i])=>({name:o,value:i}))}function B(e){return typeof e=="string"?"string":e instanceof Blob?"Blob":e instanceof FormData?"FormData":e instanceof ArrayBuffer?"ArrayBuffer":e instanceof Uint8Array?"Uint8Array":typeof ReadableStream<"u"&&e instanceof ReadableStream?"ReadableStream":null}function S(e){let t=new URL(e.url);if(t.protocol!=="https:")throw p.unsupportedScheme(t.protocol.replace(/:$/,""));let o=e.body!==void 0&&e.body!==null?B(e.body):null;if(o!==null)throw p.unsupportedBodyType(o);let i=t.host,s=t.pathname,n=[];for(let[d,a]of t.searchParams.entries())n.push({name:d,value:a});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[d,a]of e.query.entries())n.push({name:d,value:a});else for(let[d,a]of Object.entries(e.query))if(Array.isArray(a))for(let h of a)n.push({name:d,value:h});else n.push({name:d,value:a});let u=e.headers!==void 0?R(e.headers):[],c=e.body!==void 0&&e.body!==null?{host:i,method:e.method,path:s,body:e.body,headers:u,queryParams:n}:{host:i,method:e.method,path:s,headers:u,queryParams:n};return{authenticationId:e.authenticationId,httpRequest:c}}var k={production:"https://api.tray.io/private/v1/code"};function q(e){return k[e]}import{z as r}from"zod";var y=r.object({name:r.string(),value:r.string()}),g=r.object({host:r.string(),method:r.string(),path:r.string().startsWith("/"),body:r.record(r.unknown()).optional(),headers:r.array(y),queryParams:r.array(y)}),v=r.object({authenticationId:r.string().uuid(),httpRequest:g}),w=r.object({httpResponse:r.object({status:r.number(),body:r.unknown().optional(),headers:r.array(y)})});function L(e){let{status:t,body:o,headers:i}=e.httpResponse,s={};for(let{name:n,value:u}of i){let f=n.toLowerCase(),c=s[f];c===void 0?s[f]=u:Array.isArray(c)?c.push(u):s[f]=[c,u]}return{status:t,body:o,headers:s}}export{S as a,q as b,w as c,L as d};
@@ -1 +0,0 @@
1
- var a=class e extends Error{detail;constructor(r){super(s(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,i){return new e({kind:"broker_error",status:r,message:n,body:i})}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 kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,i){return new e({kind:"kv_call_failed",status:r,message:n,body:i})}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,i){return new e({kind:"files_call_failed",status:r,message:n,body:i})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function t(e){return e instanceof a}function s(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`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_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)"}}export{a,t as b};