@trayai/helix-sdk 0.63.0 → 0.65.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.
package/README.md CHANGED
@@ -18,6 +18,7 @@ The runtime SDK for **Helix** — a TypeScript-first platform for building integ
18
18
  - [Testing](#testing)
19
19
  - [Entry points](#entry-points)
20
20
  - [Tech stack](#tech-stack)
21
+ - [Security](#security)
21
22
  - [License](#license)
22
23
 
23
24
  ## Requirements
@@ -225,6 +226,10 @@ Key exported types include `TrayContext`, `TrayConfig`, `LoadedTrayConfig`, `Htt
225
226
  - TypeScript 5.x, Node.js 24+, ESM
226
227
  - [zod](https://zod.dev) — input/output schema validation
227
228
 
229
+ ## Security
230
+
231
+ Please report security vulnerabilities according to Tray's [security policy](https://tray.ai/documentation/platform/enterprise-core/security-compliance/security-policies#vulnerability-disclosure-program).
232
+
228
233
  ## License
229
234
 
230
235
  Apache-2.0 — see [LICENSE.md](./LICENSE.md).
@@ -0,0 +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};
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType, z } from 'zod';
3
- import { c as FunctionHandler, b as DefineFunctionOptions, T as TrayContext } from './types-BxQmQx3V.js';
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-BxQmQx3V.js';
3
+ import { c as FunctionHandler, b as DefineFunctionOptions, T as TrayContext } from './types-DXkq0EN9.js';
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
5
  import { T as TrayConfig, L as LoadedTrayConfig, b as WatchErrorPhase } from './sdk-config-B-Vfaig8.js';
6
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';
7
7
  import 'ky';
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{a as pt,b as $r}from"./chunk-L6J5L3JQ.js";import{a as T,b as O,d as y,e as D,f as I,g as ft,j as b,l as V,m as P,n as Ae,o as _e,p as ht,q as F,r as ie,s as ae,t as ce,u as wt}from"./chunk-J5OA4RGR.js";import{a as q,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 jo}from"crypto";import{SpanStatusCode as Ar,SpanKind as No}from"@opentelemetry/api";import{AsyncLocalStorage as Bt}from"async_hooks";import{trace as nn,SpanKind as on,SpanStatusCode as Fe}from"@opentelemetry/api";import{ExportResultCode as sn,W3CTraceContextPropagator as an}from"@opentelemetry/core";import{NodeTracerProvider as cn,SimpleSpanProcessor as un,BatchSpanProcessor as dn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as qr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Vr}from"@opentelemetry/exporter-logs-otlp-proto";var Kr={production:"https://api.tray.io/private/v1/helix/otlp"};function Oe(e){return Kr[e]}function Wr(){return I()??""}function bt(){return{[T]:Wr()}}function vt(){let e=Oe(b().env);return new qr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(bt())})}function St(){let e=Oe(b().env);return new Vr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(bt())})}import{logs as Ct,SeverityNumber as ue}from"@opentelemetry/api-logs";import{LoggerProvider as Yr,BatchLogRecordProcessor as Gr}from"@opentelemetry/sdk-logs";function W(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function zr(e){return new TextEncoder().encode(e).length}var Et="\u2026[truncated]",Jr=zr(Et),L=4096;function A(e,t=L){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Jr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Et}function v(e,t=L){return A(W(e),t)}var Xr="@trayai/helix-sdk",z,xt={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 Zr(){return y().mode==="lambda"?[new Gr({exporter:St()})]:[]}function kt(){if(z!==void 0)return;let e=Zr();e.length!==0&&(z=new Yr({processors:e}),Ct.setGlobalLoggerProvider(z))}function Qr(e,t,r){let n=xt[e]??xt.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":v(r)}}:{}}}function Rt(e,t,r){Ct.getLogger(Xr).emit(Qr(e,t,r))}async function Tt(e=2e3){if(z===void 0)return;let t;try{await Promise.race([z.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 en(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function R(e,t){return en()?`\x1B[${e}m${t}\x1B[0m`:t}var tn=5,rn={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},It="32",Pt="31",de="2",At="1";function le(e){return R(rn[e]??"0",e.padEnd(tn))}function _t(e,t){return`${le("FN")} ${R(At,`${e} ${t}`.trim())}`}function Ot(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${R(de,n)} `:""}${le(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${R(de,W(r))}`),i}function Dt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Ft(e){return`${le("AUTH")} ${e}`}function Lt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=R(o==="error"?Pt:It,s);return`${le("API")} ${e} ${t} \u2192 ${i} ${R(de,`${n}ms`)}`}function jt(e,t,r){let n=t?Pt:It,o=R(n,"\u25CF"),s=R(n,t?"error":"success");return`${o} ${R(At,e)} ${s} ${R(de,`${r}ms`)}`}function j(e){try{process.stdout.write(e+`
3
- `)}catch{}}var fe=new Bt,pe=new Bt;function C(e){let t=pe.getStore();t&&(t[e]=!0)}var ln=/^[0-9a-f]{32}$/;function fn(e){let t=e.replace(/-/g,"").toLowerCase();return ln.test(t)?t:null}var pn={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 J;function Nt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function mn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Mt(e){try{process.stdout.write(W(e)+`
4
- `)}catch{}}var Le=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]=A(f):typeof f=="object"&&f!==null?i[d]=v(f):i[d]=f;N.delete(o)}let a=fe.getStore(),c=a?fn(a):null;Mt({_otel:"span",traceId:c??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Nt(n.startTime),endTimeUnixNano:Nt(n.endTime),attributes:i,status:{code:pn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:A(n.status.message)}:{}}})}r({code:sn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t,r){}onEnd(t){N.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")&&j(`
5
- `+_t(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,Dt(t.startTime)));break}case"auth":j(Ft(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;j(Lt(String(r.method??""),String(r.host??""),n,mn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function gn(){let t=[De()?new Ne:new un(new Le)];return y().mode==="lambda"&&t.push(new dn(vt())),t.push(new je),t}function Be(){J===void 0&&(J=new cn({spanProcessors:gn()}),J.register({propagator:new an}),kt())}async function Me(e=2e3){let t=[Tt(e)];J!==void 0&&t.push((async()=>{let r;try{await Promise.race([J.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 k=nn.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
- `+jt(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?A(i):null})}async function yn(e,t){let r=e.startMs??Date.now();Be();let n=!1,o=null;try{return await fe.run(e.executionId,()=>k.startActiveSpan("App",{kind:on.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{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 Me()}}import{defineEventHandler as Bo,getMethod as Mo,getRequestURL as Uo,getHeaders as Or,getHeader as _r}from"h3";import{readBody as hn,getQuery as wn,getRouterParams as bn}from"h3";async function Ut(e,t){let r=await vn(e),n=wn(e),o=bn(e)??{},s={...n,...r,...o};return t?Sn(s,t):s}async function vn(e){try{let t=await hn(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 Sn(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 En}from"@opentelemetry/api";function me(e,t,r){let n=k.startSpan("log",{kind:En.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&x(n.spanContext().spanId,"properties",r),n.end(),Rt(e,t,r)}function Ht(){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 Y=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function $t(e){return t=>{e.node.res.statusCode=t}}function Kt(){return(e,t)=>{throw new Y(e,t)}}import kn from"ky";import{context as He,trace as Rn,SpanKind as ye,SpanStatusCode as Wt}from"@opentelemetry/api";import xn from"ky";async function qt(e,t={}){let r=D(),n=I(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw u.missingExecutionCredentials();let{env:i}=b(),a=se(i),c=t.timeout??6e4,d={Accept:"application/json"};o&&(d[O]=r),s&&(d[T]=n);let f=y().deploymentId,m=f?{...e,deploymentId:f}:e,l=await xn.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 Cn from"ky";async function Vt(e,t={}){let r=ft();if(!r)throw u.missingTrayToken();let{env:n}=b(),o=se(n),s=t.timeout??6e4,i=await Cn.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"?qt:Vt,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=gt.safeParse(s);if(!i.success)throw u.brokerError(o,"broker returned malformed response",v(s));return yt(i.data)}var Tn=["get","post","put","patch","delete","head","options"],zt="[stream body omitted]";function $e(e){try{return new URL(e).hostname}catch{return e}}function In(e,t,r,n){let o=$e(t),s="externalApi",i={kind:ye.CLIENT};return k.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:Wt.OK}:{code:Wt.ERROR,message:r}),e.end()}var Pn=16;async function An(e,t){let r=e.clone().body;return r?Jt(r,t):new Uint8Array(0)}async function Jt(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:c,value:d}=await r.read();if(c)break;if(!d||d.byteLength===0){if(s+=1,s>=Pn)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 Yt(e,t,r){if("kyResponse"in r)try{let n=await An(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 _n(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 Jt(o,L);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:zt}}}return typeof t=="string"?{body:t}:{}}function Gt(){let e=kn.create({});function t(n){return(o,s)=>{let i=He.active(),a,c="",d=!1,f=(l,p)=>{a&&!d&&(d=!0,Ke(a,l,p))},m=e.extend({hooks:{beforeRequest:[async(l,p)=>{let g=await _n(l,p.body),h=g.body;if(a||(a=k.startSpan("externalApi",{kind:ye.CLIENT},i),c=a.spanContext().spanId),a.setAttributes({method:l.method.toUpperCase(),host:$e(l.url)}),x(c,"request",{url:l.url,method:l.method.toUpperCase(),...h!==void 0?{body:h}:{}}),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 Yt(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=k.startSpan("externalApi",{kind:ye.CLIENT},i),c=a.spanContext().spanId,a.setAttributes({method:n.toUpperCase(),host:$e(String(o))}),He.with(Rn.setSpan(He.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(Tn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return On(n)}}}function On(e){let r=b().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 In(c,i,a.body,async(d,f)=>{C("hasAuth");let m=k.startSpan("auth",{kind:ye.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let l=q({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 Yt(f,p.status,{bodyValue:p.body}),Ke(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),Ke(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 Hn,SpanStatusCode as er}from"@opentelemetry/api";function G(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Dn=18e4,Xt=Dn-1e4,Fn=2e3;async function Zt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<Xt;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let c=Math.min(Fn,200*2**s),d=c/2+Math.random()*(c/2),f=Xt-(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 Ln=new Set(["SELECT","WITH","SHOW"]),jn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Nn(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 Bn(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"?A(t):v(t);return u.dbCallFailed(s)}function Mn(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 Un(e,t){return typeof t!="number"||t<0?{}:Ln.has(e)?{rowsRead:t}:jn.has(e)?{rowsWritten:t}:{}}function Qt(e){async function t(r,n,o){let s=q({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 Bn(i,a);return Mn(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:Nn,async execute(r,n){let o=G(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 Zt(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=Un(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 $n(e){return e.length>qe?`${e.slice(0,qe)}...[truncated]`:e}function Kn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function qn(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 Vn(e,t,r){let n=G(r),o=$n(r);return k.startActiveSpan("database",{kind:Hn.CLIENT},async s=>{let i=s.spanContext().spanId;Kn(s,e,t,n,o);try{C("hasDb");let{result:a,metadata:c}=await e.execute(t,r),d=qn(s,i,a,c);return s.setAttribute("status","success"),s.setStatus({code:er.OK}),d}catch(a){C("hasError");let c=a instanceof Error?a.message:String(a);throw s.setAttribute("status","error"),s.setStatus({code:er.ERROR,message:c}),a}finally{s.end()}})}function Ve(e){let r=b().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e],o=Qt(n);function s(i,a){return o.validate(i),Vn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as Gn}from"unstorage";var tr=1024,We=250*1024,Wn=new TextEncoder,zn=/(^|\/)\.\.(\/|$)/,Jn=/[?#]/,Yn=/[\u0000-\u001F\u007F]/;function rr(e){if(e.length===0)throw u.kvKeyInvalid("Key must be a non-empty string");if(zn.test(e))throw u.kvKeyInvalid("Key contains path traversal segment");if(Jn.test(e)||Yn.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=Wn.encode(e).length;if(t<1||t>tr)throw u.kvKeyInvalid(`Key must be between 1 and ${tr} UTF-8 bytes (got ${t})`)}function nr(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 X(e){rr(e)}function he(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function or(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 X(i),t(i,a)},setItem(i,a,c){return X(i),r(i,a,c)},removeItem(i,a){return X(i),n(i,a)},hasItem(i,a){return X(i),o(i,a)},getKeys(i,a){return i.length>0&&X(i),s(i,a)}}}function we(e){return Gn({driver:or(e)})}import{defineDriver as Xn}from"unstorage";function Zn(e){try{return JSON.parse(e)}catch{return e}}var Qn=Xn(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,Zn(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 sr(e){return Qn({client:e})}import no from"ky";import{z as w}from"zod";async function B(e){if(!(e.headers.get("content-type")??"").includes("application/json")){let r=await e.text();return r.length>0?r:void 0}return e.json()}var eo={production:"https://api.tray.io"};function ir(e){return eo[e]}function to(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function ro(e){return e.split("/").map(encodeURIComponent).join("/")}function Z(e,t,r){return`${e}${to(t)}/${ro(r)}`}var oo=6e4,ze=w.lazy(()=>w.union([w.string(),w.number(),w.boolean(),w.null(),w.array(ze),w.record(ze)])),so=w.object({projectId:w.string(),key:w.string(),value:ze,type:w.enum(["string","number","boolean","null","array","object"]),organizationId:w.string(),scope:w.string(),createdBy:w.string(),createdAt:w.number(),updatedBy:w.string(),updatedAt:w.number()});function io(){let e=D(),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[O]=e),n&&(o[T]=t),o}function ao(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,ao(t),v(t))}async function ve(e,t,r={}){try{let n=await no(t,{method:e,headers:io(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:oo}),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 ar(e){let t=ir(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await ve("get",Z(t,r,n));if(o===404)return null;(o<200||o>=300)&&be(o,s);let i=so.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 ve("put",Z(t,r,n),{json:{value:o}});(s<200||s>=300)&&be(s,i)},async delete(n){let{status:o,body:s}=await ve("delete",Z(t,r,n));o!==204&&be(o,s)},async has(n){let{status:o,body:s}=await ve("head",Z(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)=>{nr(r),await e.setItem(t,r,n)}}}function co(){let e=b();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function cr(e){let t=co(),r=e??ar(t),n=we(sr(r));return Se(n)}import uo from"unstorage/drivers/memory";var Je;function lo(){return Je||(Je=we(uo())),Je}function ur(){return Se(lo())}function fo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function dr(){return fo()?cr():ur()}import{createHash as go}from"crypto";import{mkdir as yo,readFile as gr,readdir as yr,rm as fr,unlink as ho,writeFile as pr}from"fs/promises";import{dirname as wo}from"path";async function po(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>V)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${V} bytes (got more than ${V})`,V);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?po(e):Buffer.from(e)}var mo={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"},lr="application/octet-stream";function Ee(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return lr;let r=e.slice(t+1).toLowerCase();return mo[r]??lr}function H(){let e=y().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function U(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),metadata:t.metadata,etag:t.etag}}async function Ye(e){try{let t=await gr(ae(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function mr(e){await yo(wo(e),{recursive:!0})}async function bo(e,t){let r=ce(e,t),n;try{n=await yr(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 hr(e,t){let r=ce(e,t),n;try{n=await yr(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 hr(e,i)):s.isFile()&&o.push(i)}return o}function wr(){return{async put(e,t,r){return U(async()=>{let n=H(),o=await M(t),s=r?.contentType??Ee(e),i=go("sha1").update(o).digest("hex"),a=new Date,c=ie(n,e);await mr(c),await pr(c,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),metadata:r?.metadata??{},etag:i},f=ae(n,e);return await mr(f),await pr(f,JSON.stringify(d)),xe(e,d)})},async get(e){return U(async()=>{let t=await Ye(e);return t?{data:await gr(ie(H(),e)),metadata:xe(e,t)}:null})},async head(e){return U(async()=>{let t=await Ye(e);return t?xe(e,t):null})},async delete(e){return U(async()=>{let t=H();await Promise.all([ie(t,e),ae(t,e)].map(async r=>{try{await ho(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return U(async()=>{let t=H(),r=await hr(t,e);return await Promise.all([fr(ce(t,e),{recursive:!0,force:!0}),fr(wt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return U(async()=>{let r=H(),n=t?.limit??100,s=(await bo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let c=await Ye(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 Ro}from"crypto";var vo={production:"https://api.tray.io"};function Ce(e){return vo[e]}function So(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function Q(e,t){return`${e}${So(t)}`}function ee(e,t,r){return`${Q(e,t)}/${encodeURIComponent(r)}`}function ke(e,t,r){return`${ee(e,t,r)}/upload`}function Re(e,t,r){return`${ee(e,t,r)}/download`}function br(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${Q(e,t)}/file?${o.toString()}`}function vr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${Q(e,t)}?${o.toString()}`}import Xe from"ky";import{z as S}from"zod";var Ze=6e4,Sr=S.object({id:S.string(),workspaceId:S.string(),projectId:S.string(),parentFolder:S.string().nullable().optional(),name:S.string(),size:S.number().nullable().optional(),objectType:S.enum(["Folder","File"]),contentType:S.string().nullable().optional(),createdAt:S.string(),updatedAt:S.string()}),Eo=S.object({path:S.array(S.object({id:S.string(),name:S.string()})),elements:S.array(Sr)});function Qe(){let e=D(),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[O]=e),n&&(o[T]=t),o}function Er(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 _(e,t){throw u.filesCallFailed(e,Er(t),v(t))}function xo(e,t){return e===400&&Er(t).toLowerCase()==="resource not found"}async function Co(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function te(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 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 Ge(e,t){let r=Sr.safeParse(t);if(!r.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",v(t));return r.data}function xr(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await te("post",Q(t,r),{json:n});return(o<200||o>=300)&&_(o,s),Ge(o,s)},async getByName(n,o){let{status:s,body:i}=await te("get",br(t,r,n,o));return s===404||xo(s,i)?null:((s<200||s>=300)&&_(s,i),Ge(s,i))},async getById(n){let{status:o,body:s}=await te("get",ee(t,r,n));return o===404?null:((o<200||o>=300)&&_(o,s),Ge(o,s))},async listChildren(n,o){let{status:s,body:i}=await te("get",vr(t,r,n,o));(s<200||s>=300)&&_(s,i);let a=Eo.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 Co(a),f;try{f=await Xe(ke(t,r,n),{method:"post",headers:{...Qe(),"content-type":d},body:new Uint8Array(c),throwHttpErrors:!1,timeout:Ze})}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)&&_(f.status,m)},async downloadContent(n){let o;try{o=await Xe(Re(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 B(o);_(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async deleteById(n){let{status:o,body:s}=await te("delete",ee(t,r,n));o===204||o===404||(o<200||o>=300)&&_(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 ko(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 ko(e,o,s)).id;return{parentFolder:o,name:n}}async function re(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 To=500,Io=8;async function Po(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 Ao(){let e=b();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function _o(e){return Ro("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),metadata:{},etag:_o(t)}}async function Cr(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 kr(e,t){let{elements:r}=await e.listChildren(t,To);return(await Po(r,Io,async o=>{let s=o.objectType==="Folder"?await kr(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Rr(e){let t=Ao(),r=e??xr(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:d}=await rt(r,s),f=await M(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 Cr(r,c,d,m);await r.uploadContent(p.id,f,d,m);let g=await r.getById(p.id);return Te(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:Te(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:Te(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 nt(r,s);if(i===null)return{deleted:0};let a=await kr(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),f=await r.getByName(a,c)??await Cr(r,a,c,i?.contentType);return{url:ke(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:Re(n,o,c.id),expiresAt:F(i?.expiresIn)}}}}function Tr(e){return{async put(t,r,n){P(t);let o=await M(r);return ht(o.byteLength),e.put(t,o,n)},async get(t){return P(t),e.get(t)},async head(t){return P(t),e.head(t)},async delete(t){return P(t),e.delete(t)},async deleteMany(t){let r=Ae(t);return _e(r),e.deleteMany(r)},async list(t,r){let n=Ae(t??"");return _e(n),e.list(n,r)},async getUploadUrl(t,r){return P(t),e.getUploadUrl(t,r)},async getDownloadUrl(t,r){return P(t),e.getDownloadUrl(t,r)}}}function Oo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ir(){let e=Oo()?Rr():wr();return Tr(e)}function Pr(e,t){let{statusCode:r,message:n}=Do(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Do(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 Fo=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Lo(e){return e.toLowerCase().includes("tray_lid")}function ot(e){let t={};for(let[r,n]of Object.entries(e))if(!Fo.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!Lo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ho(e,t){let{inputSchema:r,outputSchema:n}=zo(t),o=e;return Bo(async s=>{let i=y(),{executionId:a,userId:c,deploymentId:d}=Jo(i,s),f=Date.now(),m=new Date().toISOString(),l=Mo(s),p=Uo(s).pathname,g=Yo(),h=Ht(),$=`${l} ${p}`;Be();let K={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return $o(()=>pe.run(K,()=>fe.run(a,async()=>{let oe=await Ko(s,r);if(!oe.ok)return{response:oe.response,errored:!1,errorMessage:null};let Hr=Xo(s,oe.input,g,h,l,p,a,d,c);return qo(o,Hr,n,s,h,a,d,{method:l,path:p,rawInput:oe.input})})),{executionId:a,deploymentId:d,routeOrJob:$,startedAt:m,startMs:f,userId:c,flags:K})})}async function $o(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 Me()}}async function Ko(e,t){try{return{ok:!0,input:await Ut(e,t)}}catch(r){let n=Go(e,r);if(n)return{ok:!1,response:n};throw r}}async function qo(e,t,r,n,o,s,i,a){return k.startActiveSpan("function",{root:!0,kind:No.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async c=>{t.traceId=c.spanContext().traceId;let d=ot(Or(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 h=await pt.run(t,()=>e(t));if(p=h,h==null)n.node.res.statusCode=204,g="";else if(h instanceof Response)g=h;else if(r){let $=r.safeParse(h);if(!$.success){let K=Object.keys($.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:K,executionId:s}),u.outputValidationFailed(K)}g=$.data}else g=h}catch(h){m=!0,l=h instanceof Error?h.message:String(h),C("hasError"),g=Vo(h,n,o,s)}finally{Wo(c,n,{errored:m,errorMessage:l,handlerResult:p,response:g})}return{response:g,errored:m,errorMessage:l}})}function Vo(e,t,r,n){if(e instanceof Y)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(mt(e))return Pr(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 Wo(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?Ar.ERROR:Ar.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function zo(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 Jo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:_r(t,"x-tray-execution-id"))??jo(),o=(r?e.userId:_r(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Yo(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function Go(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 Xo(e,t,r,n,o,s,i,a,c){return{input:t,method:o,path:s,headers:ot(Or(e)),http:Gt(),db:d=>Ve(d),kv:()=>dr(),files:()=>Ir(),log:n,config:r,status:$t(e),error:Kt(),state:{},request:e,executionId:i,deploymentId:a,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function Zo(e){return e}import{resolve as st}from"path";import{existsSync as Lr}from"fs";import{loadConfig as es}from"c12";import{z as E}from"zod";import{z as Qo}from"zod";var Dr=["production"],Ie=Qo.enum(Dr);var it=E.string().uuid("projectId must be a valid UUID"),at=E.string().min(1,"workspaceId must be a non-empty string"),ts=E.object({name:E.string().min(1,"name is required"),projectId:it.optional(),workspaceId:at.optional(),env:Ie.default("production"),authentications:E.record(E.string()).optional().default({}),config:E.record(E.unknown()).optional().default({})}),Fr=E.object({name:E.string().min(1,"name is required"),workspaceId:at.optional(),env:Ie,authentications:E.record(E.string()),config:E.record(E.unknown())}),rs=E.discriminatedUnion("kind",[Fr.extend({kind:E.literal("provisioned"),projectId:it}),Fr.extend({kind:E.literal("unprovisioned")})]),jr=["helix","tray"],Nr=["ts","mts","cts","js","mjs","cjs"];function Pe(e){for(let t of jr)for(let r of Nr){let n=st(e,`${t}.config.${r}`);if(Lr(n))return n}}function ns(e){for(let t of jr)if(Nr.some(r=>Lr(st(e,`${t}.config.${r}`))))return t;return"helix"}function ct(e){return{name:ns(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=ts.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 es(ct(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 ${st(t,"helix.config.ts")}`);return ut(r.config,n)}var Br="WORKSPACE_ID_REQUIRED";function os(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:Br});return e.workspaceId}import{existsSync as ss,watch as is,writeSync as as}from"fs";import{join as cs,resolve as us}from"path";import{watchConfig as ds}from"c12";function ls(e,t){let r=e instanceof Error?e.message:String(e);as(2,`[helix-watch] ${t.phase} error: ${r}
8
- `)}function dt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var fs=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,Mr=new Set;function Ur(e){return Pe(e)!==void 0}async function ps(e,t){if(Ur(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=us(e.cwd);Mr.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
- `),Mr.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=ds({...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=is(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();fs.test(n)&&ss(cs(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 ms(e){let t=e.onError??ls,r=new Set,n=await ps(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(!Ur(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{Dr as ENVIRONMENT_VALUES,Br as WORKSPACE_ID_REQUIRED_CODE,ms as createConfigService,Zo as defineConfig,Ho as defineFunction,Ie as environmentSchema,$r as getContext,y as getSdkConfig,ne as loadConfig,rs as loadedTrayConfigSchema,it as projectIdSchema,os as requireWorkspaceId,Pe as resolveConfigFile,yn as runWithinAppSpan,at as workspaceIdSchema};
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};
@@ -11,7 +11,7 @@ declare function getActiveConfig(): LoadedTrayConfig;
11
11
  /** Test-only cleanup hook to drop worker-local state between cases. */
12
12
  declare function clearActiveConfig(): void;
13
13
 
14
- declare function assertValidPath(path: string): void;
14
+ declare function assertValidPath(path: string, maxPathBytes?: number): void;
15
15
 
16
16
  type SdkErrorDetail = {
17
17
  readonly kind: "unknown_alias";
@@ -1 +1 @@
1
- import{c as o,h as t,i as e,j as r,k as i,m as n,r as g,s as p}from"../chunk-J5OA4RGR.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 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,4 +1,4 @@
1
- import { T as TrayContext } from '../types-BxQmQx3V.js';
1
+ import { T as TrayContext } from '../types-DXkq0EN9.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
@@ -29,12 +29,6 @@ interface FileMetadata {
29
29
  size: number;
30
30
  contentType: string;
31
31
  lastModified: Date;
32
- /**
33
- * Custom metadata set via `PutOptions.metadata`.
34
- * **Dev only** — the production backend has no field for this; it's silently
35
- * dropped in Lambda mode and always comes back empty there.
36
- */
37
- metadata: Record<string, string>;
38
32
  /**
39
33
  * Content hash. **Dev**: real sha1 of the bytes. **Lambda**: synthesized from
40
34
  * size + lastModified — the backend doesn't expose a content hash, so don't
@@ -44,7 +38,6 @@ interface FileMetadata {
44
38
  }
45
39
  interface PutOptions {
46
40
  contentType?: string;
47
- metadata?: Record<string, string>;
48
41
  }
49
42
  interface SignedUrlOptions {
50
43
  expiresIn?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.63.0",
3
+ "version": "0.65.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -1 +0,0 @@
1
- import{a as i}from"./chunk-W5TFZBQD.js";var w="X-Helix-Project-Execution-Token",A="X-Tray-Token",E={mode:"dev",deploymentId:null},l={...E},o={};function k(t){let{internalJwt:e,helixExecutionJwt:n,devToken:r,...f}=t;"internalJwt"in t&&(o.internalJwt=e),"helixExecutionJwt"in t&&(o.helixExecutionJwt=n),"devToken"in t&&(o.devToken=r),l={...l,...f}}function y(){return l}function R(){return o.internalJwt}function D(){return o.helixExecutionJwt}function L(){return o.devToken}var F="tray-config-bridge",c=null;function N(t){c=t}function H(){if(!c)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return c}function J(){c=null}var d=1024,g=100*1024*1024,u=250,h=3600,T=h*1e3,x=new TextEncoder,p=/(^|\/)\.\.(\/|$)/,C=/[?#]/;function S(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<=31||n===127)return!0}return!1}function M(t){if(t.length===0)throw i.filesPathInvalid("Path must be a non-empty string");v(t)}function O(t){return t.endsWith("/")?t.slice(0,-1):t}function v(t){if(t.length===0)return;if(p.test(t))throw i.filesPathInvalid("Path contains path traversal segment");if(C.test(t)||S(t))throw i.filesPathInvalid("Path contains illegal characters");let e=t.split("/");if(t.startsWith("/")||t.endsWith("/")||e.some(r=>r===""))throw i.filesPathInvalid("Path must not contain empty path segments");for(let r of e){let f=x.encode(r).length;if(f>u)throw i.filesPathInvalid(`Path segment exceeds ${u} UTF-8 bytes (got ${f})`)}let n=x.encode(t).length;if(n<1||n>d)throw i.filesPathInvalid(`Path must be between 1 and ${d} UTF-8 bytes (got ${n})`)}function X(t){if(t>g)throw i.filesValueTooLarge(`File exceeds maximum size of ${g} bytes (got ${t})`,g)}function $(t){let e=t!==void 0?t*1e3:T;return new Date(Date.now()+e)}import{join as s}from"path";var _="files",I="files-meta";function m(t){return s(t,".helix",_)}function a(t){return s(t,".helix",I)}function P(t,e){return s(m(t),...e.split("/"))}function W(t,e){return s(a(t),...e.split("/"))+".json"}function Y(t,e){return e.length===0?m(t):P(t,e)}function j(t,e){return e.length===0?a(t):s(a(t),...e.split("/"))}export{w as a,A as b,k as c,y as d,R as e,D as f,L as g,F as h,N as i,H as j,J as k,g as l,M as m,O as n,v as o,X as p,$ as q,P as r,W as s,Y as t,j as u};