@trayai/helix-sdk 0.69.0 → 0.69.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +9 -9
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{a as ht,b as zr}from"./chunk-L6J5L3JQ.js";import{a as T,b as D,d as y,e as O,f as I,g as pt,j as E,l as J,m as A,n as Ae,o as _e,p as Et,q as L,r as St,s as ae,t as ce,u as ue,v as xt}from"./chunk-KURGNIK4.js";import{a as z,b as ie,c as vt,d as bt}from"./chunk-5XNPF4RA.js";import{b as mt,d as F,e as gt,i as yt,l as u,m as wt}from"./chunk-ATJUJXR7.js";import{randomUUID as Uo}from"crypto";import{SpanStatusCode as jr,SpanKind as Mo}from"@opentelemetry/api";import{AsyncLocalStorage as Kt}from"async_hooks";import{trace as cn,SpanKind as un,SpanStatusCode as Fe}from"@opentelemetry/api";import{ExportResultCode as dn,W3CTraceContextPropagator as ln}from"@opentelemetry/core";import{NodeTracerProvider as fn,SimpleSpanProcessor as pn,BatchSpanProcessor as mn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Jr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Yr}from"@opentelemetry/exporter-logs-otlp-proto";function De(e){return F(e).hosts.ingest}function Gr(){return I()??""}function Ct(){return{[T]:Gr()}}function Rt(){let e=De(E().env);return new Jr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Ct())})}function kt(){let e=De(E().env);return new Yr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Ct())})}import{logs as Pt,SeverityNumber as de}from"@opentelemetry/api-logs";import{LoggerProvider as Qr,BatchLogRecordProcessor as en}from"@opentelemetry/sdk-logs";function Y(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Xr(e){return new TextEncoder().encode(e).length}var Tt="\u2026[truncated]",Zr=Xr(Tt),j=4096;function _(e,t=j){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Zr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Tt}function v(e,t=j){return _(Y(e),t)}var tn="@trayai/helix-sdk",G,It={debug:{number:de.DEBUG,text:"DEBUG"},info:{number:de.INFO,text:"INFO"},warn:{number:de.WARN,text:"WARN"},error:{number:de.ERROR,text:"ERROR"}};function rn(){return y().mode==="lambda"?[new en({exporter:kt()})]:[]}function At(){if(G!==void 0)return;let e=rn();e.length!==0&&(G=new Qr({processors:e}),Pt.setGlobalLoggerProvider(G))}function nn(e,t,r){let n=It[e]??It.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":v(r)}}:{}}}function _t(e,t,r){Pt.getLogger(tn).emit(nn(e,t,r))}async function Dt(e=2e3){if(G===void 0)return;let t;try{await Promise.race([G.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
- `)}finally{t!==void 0&&clearTimeout(t)}}function Oe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function on(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function k(e,t){return on()?`\x1B[${e}m${t}\x1B[0m`:t}var sn=5,an={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ot="32",Ft="31",le="2",Lt="1";function fe(e){return k(an[e]??"0",e.padEnd(sn))}function jt(e,t){return`${fe("FN")} ${k(Lt,`${e} ${t}`.trim())}`}function Nt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${k(le,n)} `:""}${fe(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${k(le,Y(r))}`),i}function Bt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Ut(e){return`${fe("AUTH")} ${e}`}function Mt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=k(o==="error"?Ft:Ot,s);return`${fe("API")} ${e} ${t} \u2192 ${i} ${k(le,`${n}ms`)}`}function $t(e,t,r){let n=t?Ft:Ot,o=k(n,"\u25CF"),s=k(n,t?"error":"success");return`${o} ${k(Lt,e)} ${s} ${k(le,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
- `)}catch{}}var pe=new Kt,me=new Kt;function C(e){let t=me.getStore();t&&(t[e]=!0)}var gn=/^[0-9a-f]{32}$/;function yn(e){let t=e.replace(/-/g,"").toLowerCase();return gn.test(t)?t:null}var hn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},B=new Map;function x(e,t,r){let n=B.get(e);n?n[t]=r:B.set(e,{[t]:r})}var X;function Ht(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function wn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function qt(e){try{process.stdout.write(Y(e)+`
4
- `)}catch{}}var Le=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=B.get(o),i={...n.attributes};if(s!==void 0){for(let[d,l]of Object.entries(s))typeof l=="string"?i[d]=_(l):typeof l=="object"&&l!==null?i[d]=v(l):i[d]=l;B.delete(o)}let a=pe.getStore(),c=a?yn(a):null;qt({_otel:"span",traceId:c??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Ht(n.startTime),endTimeUnixNano:Ht(n.endTime),attributes:i,status:{code:hn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:dn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t,r){}onEnd(t){B.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
- `+jt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=B.get(n)?.properties;N(Nt(String(r.level??"info"),String(r.message??""),o,Bt(t.startTime)));break}case"auth":N(Ut(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(Mt(String(r.method??""),String(r.host??""),n,wn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function vn(){let t=[Oe()?new Ne:new pn(new Le)];return y().mode==="lambda"&&t.push(new mn(Rt())),t.push(new je),t}function Be(){X===void 0&&(X=new fn({spanProcessors:vn()}),X.register({propagator:new ln}),At())}async function Ue(e=2e3){let t=[Dt(e)];X!==void 0&&t.push((async()=>{let r;try{await Promise.race([X.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
- `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var R=cn.getTracer("@trayai/helix-sdk");function Me({executionId:e,deploymentId:t,routeOrJob:r,startedAt:n,startMs:o,errored:s,errorMessage:i,userId:a,flags:c}){let d=new Date().toISOString(),l=Date.now()-o;if(Oe()){N(`
7
- `+$t(r,s,l));return}qt({_otel:"summary",executionId:e,deploymentId:t,triggerType:"http",routeOrJob:r,status:s?"error":"success",startedAt:n,finishedAt:d,durationMs:l,userId:a,hasError:s||c.hasError,hasAuth:c.hasAuth,hasExternal:c.hasExternal,hasDb:c.hasDb,errorSummary:s&&i!==null?_(i):null})}async function bn(e,t){let r=e.startMs??Date.now();Be();let n=!1,o=null;try{return await pe.run(e.executionId,()=>R.startActiveSpan("App",{kind:un.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return n=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",n?"error":"success"),s.setStatus({code:n?Fe.ERROR:Fe.OK}),i}catch(i){throw n=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Fe.ERROR,message:o}),i}finally{s.end()}}))}finally{Me({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await Ue()}}import{defineEventHandler as $o,getMethod as Ho,getRequestURL as Ko,getHeaders as Br,getHeader as Nr}from"h3";import{readBody as En,getQuery as Sn,getRouterParams as xn}from"h3";async function Vt(e,t){let r=await Cn(e),n=Sn(e),o=xn(e)??{},s={...n,...r,...o};return t?Rn(s,t):s}async function Cn(e){try{let t=await En(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Rn(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}import{SpanKind as kn}from"@opentelemetry/api";function ge(e,t,r){let n=R.startSpan("log",{kind:kn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&x(n.spanContext().spanId,"properties",r),n.end(),_t(e,t,r)}function Wt(){return{info:(e,t)=>ge("info",e,t),warn:(e,t)=>ge("warn",e,t),error:(e,t)=>ge("error",e,t),debug:(e,t)=>ge("debug",e,t)}}var Z=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function zt(e){return t=>{e.node.res.statusCode=t}}function Jt(){return(e,t)=>{throw new Z(e,t)}}import Pn from"ky";import{context as $e,trace as An,SpanKind as he,SpanStatusCode as Xt}from"@opentelemetry/api";import Tn from"ky";async function Yt(e,t={}){let r=O(),n=I(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw u.missingExecutionCredentials();let{env:i}=E(),a=ie(i),c=t.timeout??6e4,d={Accept:"application/json"};o&&(d[D]=r),s&&(d[T]=n);let l=y().deploymentId,m=l?{...e,deploymentId:l}:e,f=await Tn.post(`${a}/broker/http`,{json:m,headers:d,throwHttpErrors:!1,timeout:c}),p;return(f.headers.get("content-type")??"").includes("application/json")?p=await f.json():p=await f.text(),{status:f.status,body:p}}import In from"ky";async function Gt(e,t={}){let r=pt();if(!r)throw u.missingTrayToken();let{env:n}=E(),o=ie(n),s=t.timeout??6e4,i=await In.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:s}),a;return(i.headers.get("content-type")??"").includes("application/json")?a=await i.json():a=await i.text(),{status:i.status,body:a}}async function ye(e,t={}){let r=y().mode==="lambda"?Yt:Gt,n;try{n=await r(e,t)}catch(a){if(a instanceof u)throw a;let c=a instanceof Error?a.message??String(a):String(a);throw u.brokerError(0,c)}let{status:o,body:s}=n;if(o<200||o>=300){let a;if(s!==null&&typeof s=="object"){let c=s;typeof c.message=="string"?a=c.message:typeof c.error=="string"?a=c.error:a=String(s)}else a=String(s);throw u.brokerError(o,a,v(s))}let i=vt.safeParse(s);if(!i.success)throw u.brokerError(o,"broker returned malformed response",v(s));return bt(i.data)}var _n=["get","post","put","patch","delete","head","options"],Zt="[stream body omitted]";function He(e){try{return new URL(e).hostname}catch{return e}}function Dn(e,t,r,n){let o=He(t),s="externalApi",i={kind:he.CLIENT};return R.startActiveSpan(s,i,async a=>{let c=a.spanContext().spanId;return a.setAttributes({method:e,host:o}),x(c,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?Zt:r}:{}}),n(a,c)})}function Ke(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Xt.OK}:{code:Xt.ERROR,message:r}),e.end()}var On=16;async function Fn(e,t){let r=e.clone().body;return r?Qt(r,t):new Uint8Array(0)}async function Qt(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:c,value:d}=await r.read();if(c)break;if(!d||d.byteLength===0){if(s+=1,s>=On)break;continue}s=0;let l=t+1-o;if(d.byteLength>=l){n.push(d.slice(0,l)),o+=l;break}n.push(d),o+=d.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of n)i.set(c,a),a+=c.byteLength;return i}async function er(e,t,r){if("kyResponse"in r)try{let n=await Fn(r.kyResponse,j),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;if(n.length<=j)try{s=JSON.parse(o)}catch{s=o}else s=o;x(e,"response",s)}catch{x(e,"response",{status:t})}else x(e,"response",r.bodyValue)}async function Ln(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),s=new Request(e,{body:n,duplex:"half"}),i=await Qt(o,j);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:Zt}}}return typeof t=="string"?{body:t}:{}}function tr(){let e=Pn.create({});function t(n){return(o,s)=>{let i=$e.active(),a,c="",d=!1,l=(f,p)=>{a&&!d&&(d=!0,Ke(a,f,p))},m=e.extend({hooks:{beforeRequest:[async(f,p)=>{let g=await Ln(f,p.body),w=g.body;if(a||(a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId),a.setAttributes({method:f.method.toUpperCase(),host:He(f.url)}),x(c,"request",{url:f.url,method:f.method.toUpperCase(),...w!==void 0?{body:w}:{}}),d=!1,C("hasExternal"),g.request)return g.request}],beforeRetry:[f=>{l("error","retry"),a=void 0,c="",d=!1}],afterResponse:[async(f,p,g)=>{a&&(a.setAttribute("statusCode",g.status),await er(c,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(C("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[f=>(C("hasError"),l("error",f.message),f)]}});return a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId,a.setAttributes({method:n.toUpperCase(),host:He(String(o))}),$e.with(An.setSpan($e.active(),a),()=>{let f=n==="options"?m(o,{...s,method:"OPTIONS"}):m[n](o,s);return f.catch(p=>{C("hasError"),l("error",p instanceof Error?p.message:String(p))}),f})}}let r=Object.fromEntries(_n.map(n=>[n,t(n)]));return{...e,...r,authed(n){return jn(n)}}}function jn(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(i,a={})=>{let c=s.toUpperCase();return Dn(c,i,a.body,async(d,l)=>{C("hasAuth");let m=R.startSpan("auth",{kind:he.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let f=z({authenticationId:n,method:c,url:i,body:a.body,headers:a.headers,query:a.query}),p=await ye(f,{timeout:a.timeout});return d.setAttribute("statusCode",p.status),await er(l,p.status,{bodyValue:p.body}),Ke(d,"success"),p}catch(f){throw C("hasError"),f instanceof u&&f.detail.kind==="broker_error"&&f.detail.status>0&&d.setAttribute("statusCode",f.detail.status),Ke(d,"error",f instanceof Error?f.message:String(f)),f}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as Vn,SpanStatusCode as sr}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Nn=18e4,rr=Nn-1e4,Bn=2e3;async function nr(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<rr;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let c=Math.min(Bn,200*2**s),d=c/2+Math.random()*(c/2),l=rr-(Date.now()-o);await new Promise(m=>setTimeout(m,Math.min(d,l))),s++}throw u.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Un=new Set(["SELECT","WITH","SHOW"]),Mn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function $n(e){if(!e.clusterIdentifier&&!e.workgroupName)throw u.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw u.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw u.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw u.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw u.dbInvalidParameters("region is required")}function Hn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return u.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):v(t);return u.dbCallFailed(s)}function Kn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw u.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function qn(e,t){return typeof t!="number"||t<0?{}:Un.has(e)?{rowsRead:t}:Mn.has(e)?{rowsWritten:t}:{}}function or(e){async function t(r,n,o){let s=z({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:i,body:a}=await ye(s);if(i>=400)throw Hn(i,a);return Kn(a)}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw u.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:$n,async execute(r,n){let o=Q(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let p=v(i);throw u.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let d=await nr(t,r.region,c),l=d.Status;if(l==="FAILED"){let p=typeof d.Error=="string"?d.Error:"statement failed";throw u.dbQueryFailed(`${p} (statement: ${c})`)}if(l==="ABORTED")throw u.dbQueryFailed(`statement aborted (statement: ${c})`);let m=qn(o,d.ResultRows);return d.HasResultSet===!1?{result:{rowsAffected:d.ResultRows??0},metadata:m}:{result:await t(r.region,"GetStatementResult",{Id:c}),metadata:m}}}}var qe=64*1024;function Wn(e){return e.length>qe?`${e.slice(0,qe)}...[truncated]`:e}function zn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Jn(e,t,r,n){let o=typeof r=="string"?r:JSON.stringify(r);return o.length>qe?x(t,"result",{truncated:!0,size:o.length}):x(t,"result",r),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),o}async function Yn(e,t,r){let n=Q(r),o=Wn(r);return R.startActiveSpan("database",{kind:Vn.CLIENT},async s=>{let i=s.spanContext().spanId;zn(s,e,t,n,o);try{C("hasDb");let{result:a,metadata:c}=await e.execute(t,r),d=Jn(s,i,a,c);return s.setAttribute("status","success"),s.setStatus({code:sr.OK}),d}catch(a){C("hasError");let c=a instanceof Error?a.message:String(a);throw s.setAttribute("status","error"),s.setStatus({code:sr.ERROR,message:c}),a}finally{s.end()}})}function Ve(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e],o=or(n);function s(i,a){return o.validate(i),Yn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as eo}from"unstorage";var ir=1024,We=250*1024,Gn=new TextEncoder,Xn=/(^|\/)\.\.(\/|$)/,Zn=/[?#]/,Qn=/[\u0000-\u001F\u007F]/;function ar(e){if(e.length===0)throw u.kvKeyInvalid("Key must be a non-empty string");if(Xn.test(e))throw u.kvKeyInvalid("Key contains path traversal segment");if(Zn.test(e)||Qn.test(e))throw u.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw u.kvKeyInvalid("Key must not contain empty path segments");let t=Gn.encode(e).length;if(t<1||t>ir)throw u.kvKeyInvalid(`Key must be between 1 and ${ir} UTF-8 bytes (got ${t})`)}function cr(e){let t;try{t=JSON.stringify(e)}catch{throw u.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw u.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>We)throw u.kvValueTooLarge(`Value exceeds maximum size of ${We} bytes (got ${r})`,We)}function ee(e){ar(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function ur(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return ee(i),t(i,a)},setItem(i,a,c){return ee(i),r(i,a,c)},removeItem(i,a){return ee(i),n(i,a)},hasItem(i,a){return ee(i),o(i,a)},getKeys(i,a){return i.length>0&&ee(i),s(i,a)}}}function ve(e){return eo({driver:ur(e)})}import{defineDriver as to}from"unstorage";function ro(e){try{return JSON.parse(e)}catch{return e}}var no=to(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n){await t.set(r,ro(n))},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function dr(e){return no({client:e})}import io from"ky";import{z as b}from"zod";async function U(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function lr(e){return F(e).hosts.api}function oo(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function so(e){return e.split("/").map(encodeURIComponent).join("/")}function te(e,t,r){return`${e}${oo(t)}/${so(r)}`}var ao=6e4,ze=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(ze),b.record(ze)])),co=b.object({projectId:b.string(),key:b.string(),value:ze,type:b.enum(["string","number","boolean","null","array","object"]),organizationId:b.string(),scope:b.string(),createdBy:b.string(),createdAt:b.number(),updatedBy:b.string(),updatedAt:b.number()});function uo(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function lo(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function be(e,t){throw u.kvCallFailed(e,lo(t),v(t))}async function Ee(e,t,r={}){try{let n=await io(t,{method:e,headers:uo(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ao}),o=e==="head"?void 0:await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw u.kvCallFailed(0,o)}}function fr(e){let t=lr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",te(t,r,n));if(o===404)return null;(o<200||o>=300)&&be(o,s);let i=co.safeParse(s);if(!i.success)throw u.kvCallFailed(o,"platform returned malformed KeyValueEntry",v(s));return i.data.value},async set(n,o){let{status:s,body:i}=await Ee("put",te(t,r,n),{json:{value:o}});(s<200||s>=300)&&be(s,i)},async delete(n){let{status:o,body:s}=await Ee("delete",te(t,r,n));o!==204&&be(o,s)},async has(n){let{status:o,body:s}=await Ee("head",te(t,r,n));if(o===200)return!0;if(o===404)return!1;be(o,s)}}}function Se(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{cr(r),await e.setItem(t,r,n)}}}function fo(){let e=E();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function pr(e){let t=fo(),r=e??fr(t),n=ve(dr(r));return Se(n)}import po from"unstorage/drivers/memory";var Je;function mo(){return Je||(Je=ve(po())),Je}function mr(){return Se(mo())}function go(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function gr(){return go()?pr():mr()}import{createHash as wo}from"crypto";import{mkdir as vo,readFile as br,readdir as Er,rm as hr,unlink as bo,writeFile as wr}from"fs/promises";import{dirname as Eo}from"path";async function yo(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>J)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${J} bytes (got more than ${J})`,J);r.push(s)}}return Buffer.concat(r)}async function M(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?yo(e):Buffer.from(e)}var ho={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},yr="application/octet-stream";function xe(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return yr;let r=e.slice(t+1).toLowerCase();return ho[r]??yr}function H(){let e=y().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function $(e){try{return await e()}catch(t){if(t instanceof u)throw t;let r=t?.code;throw r?u.filesCallFailed(0,`Local file storage operation failed: ${r}`):u.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Ce(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ye(e){try{let t=await br(ce(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function vr(e){await vo(Eo(e),{recursive:!0})}async function So(e,t){let r=ue(e,t),n;try{n=await Er(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function Sr(e,t){let r=ue(e,t),n;try{n=await Er(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of n){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await Sr(e,i)):s.isFile()&&o.push(i)}return o}function xr(){return{async put(e,t,r){return $(async()=>{let n=H(),o=await M(t),s=r?.contentType??xe(e),i=wo("sha1").update(o).digest("hex"),a=new Date,c=ae(n,e);await vr(c),await wr(c,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},l=ce(n,e);return await vr(l),await wr(l,JSON.stringify(d)),Ce(e,d)})},async get(e){return $(async()=>{let t=await Ye(e);return t?{data:await br(ae(H(),e)),metadata:Ce(e,t)}:null})},async head(e){return $(async()=>{let t=await Ye(e);return t?Ce(e,t):null})},async delete(e){return $(async()=>{let t=H();await Promise.all([ae(t,e),ce(t,e)].map(async r=>{try{await bo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return $(async()=>{let t=H(),r=await Sr(t,e);return await Promise.all([hr(ue(t,e),{recursive:!0,force:!0}),hr(xt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return $(async()=>{let r=H(),n=t?.limit??100,s=(await So(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let c=await Ye(a);return c?Ce(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}}}}import{createHash as Po}from"crypto";function Re(e){return F(e).hosts.api}function xo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function re(e,t){return`${e}${xo(t)}`}function K(e,t,r){return`${re(e,t)}/${encodeURIComponent(r)}`}function ke(e,t,r){return`${K(e,t,r)}/upload`}function Cr(e,t,r){return`${K(e,t,r)}/download`}function Rr(e,t,r){return`${K(e,t,r)}/signed-url`}function kr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${re(e,t)}/file?${o.toString()}`}function Tr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${re(e,t)}?${o.toString()}`}import Xe from"ky";import{z as h}from"zod";var Ze=6e4,Ir=h.object({id:h.string(),workspaceId:h.string(),projectId:h.string(),parentFolder:h.string().nullable().optional(),name:h.string(),size:h.number().nullable().optional(),objectType:h.enum(["Folder","File"]),contentType:h.string().nullable().optional(),createdAt:h.string(),updatedAt:h.string()}),Co=h.object({signedURL:h.string()}),Ro=h.object({path:h.array(h.object({id:h.string(),name:h.string()})),elements:h.array(Ir)});function Qe(){let e=O(),t=I(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[D]=e),n&&(o[T]=t),o}function Pr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function P(e,t){throw u.filesCallFailed(e,Pr(t),v(t))}function ko(e,t){return e===400&&Pr(t).toLowerCase()==="resource not found"}async function To(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function q(e,t,r={}){try{let n=await Xe(t,{method:e,headers:Qe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ze}),o=await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message:String(n);throw u.filesCallFailed(0,o)}}function Ge(e,t){let r=Ir.safeParse(t);if(!r.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",v(t));return r.data}function Ar(e){let t=Re(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await q("post",re(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Ge(o,s)},async getByName(n,o){let{status:s,body:i}=await q("get",kr(t,r,n,o));return s===404||ko(s,i)?null:((s<200||s>=300)&&P(s,i),Ge(s,i))},async getById(n){let{status:o,body:s}=await q("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Ge(o,s))},async listChildren(n,o){let{status:s,body:i}=await q("get",Tr(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=Ro.safeParse(i);if(!a.success)throw u.filesCallFailed(s,"platform returned malformed listing",v(i));return a.data},async uploadContent(n,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:c,contentType:d}=await To(a),l;try{l=await Xe(ke(t,r,n),{method:"post",headers:{...Qe(),"content-type":d},body:new Uint8Array(c),throwHttpErrors:!1,timeout:Ze})}catch(f){if(f instanceof u)throw f;let p=f instanceof Error?f.message:String(f);throw u.filesCallFailed(0,p)}let m=await U(l);(l.status<200||l.status>=300)&&P(l.status,m)},async downloadContent(n){let o;try{o=await Xe(Cr(t,r,n),{method:"get",headers:Qe(),throwHttpErrors:!1,timeout:Ze})}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message:String(i);throw u.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await U(o);P(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await q("get",Rr(t,r,n));(o<200||o>=300)&&P(o,s);let i=Co.safeParse(s);if(!i.success)throw u.filesCallFailed(o,"platform returned malformed signed URL response",v(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await q("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function et(e){return e.split("/").filter(t=>t.length>0)}function tt(e){return e instanceof u&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Io(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function rt(e,t){let r=et(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await Io(e,o,s)).id;return{parentFolder:o,name:n}}async function ne(e,t){let r=et(t),n=r[r.length-1],o;for(let s of r.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:n}}async function nt(e,t){if(t.length===0)return;let r=et(t),n;for(let o of r){let s=await e.getByName(n,o);if(!s||s.objectType!=="Folder")return null;n=s.id}return n}var Ao=500,_o=8;async function Do(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;n[i]=await r(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}function Oo(){let e=E();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Fo(e){return Po("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Te(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Fo(t)}}async function _r(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Dr(e,t){let{elements:r}=await e.listChildren(t,Ao);return(await Do(r,_o,async o=>{let s=o.objectType==="Folder"?await Dr(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Or(e){let t=Oo(),r=e??Ar(t),n=Re(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:d}=await rt(r,s),l=await M(i),m=a?.contentType??xe(s),f=await r.getByName(c,d);if(f&&f.objectType!=="File")throw u.filesCallFailed(409,`A folder already exists at "${s}"`);let p=f??await _r(r,c,d,m);await r.uploadContent(p.id,l,d,m);let g=await r.getById(p.id);return Te(s,g??p,m)},async get(s){let i=await ne(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Te(s,a)}},async head(s){let i=await ne(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Te(s,a)},async delete(s){let i=await ne(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await nt(r,s);if(i===null)return{deleted:0};let a=await Dr(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await nt(r,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:d}=await r.listChildren(a,c);return{files:d.filter(m=>m.objectType==="File").map(m=>Te(s?`${s}/${m.name}`:m.name,m)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await rt(r,s),l=await r.getByName(a,c)??await _r(r,a,c,i?.contentType);return{url:ke(n,o,l.id),expiresAt:L(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await ne(r,s),c=a?await r.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw u.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(c.id),expiresAt:L(i?.expiresIn)}}}}function ot(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){A(n,r);let i=await M(o);return Et(i.byteLength),e.put(n,i,s)},async get(n){return A(n,r),e.get(n)},async head(n){return A(n,r),e.head(n)},async delete(n){return A(n,r),e.delete(n)},async deleteMany(n){let o=Ae(n);return _e(o,r),e.deleteMany(o)},async list(n,o){let s=Ae(n??"");return _e(s,r),e.list(s,o)},async getUploadUrl(n,o){return A(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return A(n,r),e.getDownloadUrl(n,o)}}}function Lo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Fr(){if(Lo())return ot(Or());let e=y().projectRoot;return ot(xr(),{maxPathBytes:e?St(e):void 0})}function Lr(e,t){let{statusCode:r,message:n}=jo(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function jo(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var No=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Bo(e){return e.toLowerCase().includes("tray_lid")}function st(e){let t={};for(let[r,n]of Object.entries(e))if(!No.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let i=s.split("=")[0].trim();return!Bo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function qo(e,t){let{inputSchema:r,outputSchema:n}=Go(t),o=e;return $o(async s=>{let i=y(),{executionId:a,userId:c,deploymentId:d}=Xo(i,s),l=Date.now(),m=new Date().toISOString(),f=Ho(s),p=Ko(s).pathname,g=Zo(),w=Wt(),V=`${f} ${p}`;Be();let W={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Vo(()=>me.run(W,()=>pe.run(a,async()=>{let se=await Wo(s,r);if(!se.ok)return{response:se.response,errored:!1,errorMessage:null};let Wr=es(s,se.input,g,w,f,p,a,d,c);return zo(o,Wr,n,s,w,a,d,{method:f,path:p,rawInput:se.input})})),{executionId:a,deploymentId:d,routeOrJob:V,startedAt:m,startMs:l,userId:c,flags:W})})}async function Vo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Me({...t,errored:r,errorMessage:n}),await Ue()}}async function Wo(e,t){try{return{ok:!0,input:await Vt(e,t)}}catch(r){let n=Qo(e,r);if(n)return{ok:!1,response:n};throw r}}async function zo(e,t,r,n,o,s,i,a){return R.startActiveSpan("function",{root:!0,kind:Mo.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async c=>{t.traceId=c.spanContext().traceId;let d=st(Br(n)),l=c.spanContext().spanId;x(l,"input",a.rawInput),x(l,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let m=!1,f=null,p,g;try{let w=await ht.run(t,()=>e(t));if(p=w,w==null)n.node.res.statusCode=204,g="";else if(w instanceof Response)g=w;else if(r){let V=r.safeParse(w);if(!V.success){let W=Object.keys(V.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:W,executionId:s}),u.outputValidationFailed(W)}g=V.data}else g=w}catch(w){m=!0,f=w instanceof Error?w.message:String(w),C("hasError"),g=Jo(w,n,o,s)}finally{Yo(c,n,{errored:m,errorMessage:f,handlerResult:p,response:g})}return{response:g,errored:m,errorMessage:f}})}function Jo(e,t,r,n){if(e instanceof Z)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(wt(e))return Lr(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Yo(e,t,r){let n=e.spanContext().spanId;e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&x(n,"output",r.handlerResult),x(n,"response",r.response);let o=me.getStore();e.setAttribute("hasAuth",o?.hasAuth??!1),e.setAttribute("hasExternal",o?.hasExternal??!1),e.setAttribute("hasDb",o?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let s=r.errored||(o?.hasError??!1);e.setStatus({code:s?jr.ERROR:jr.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Go(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Xo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:Nr(t,"x-tray-execution-id"))??Uo(),o=(r?e.userId:Nr(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Zo(){try{return E().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function Qo(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function es(e,t,r,n,o,s,i,a,c){return{input:t,method:o,path:s,headers:st(Br(e)),http:tr(),db:d=>Ve(d),kv:()=>gr(),files:()=>Fr(),log:n,config:r,status:zt(e),error:Jt(),state:{},request:e,executionId:i,deploymentId:a,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function ts(e){return e}import{resolve as it}from"path";import{existsSync as Mr}from"fs";import{loadConfig as os}from"c12";import{z as S}from"zod";import{z as rs}from"zod";var ns=["production"],Ie=rs.string().refine(e=>mt(e),e=>({message:`Invalid enum value. Expected ${gt().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var at=S.string().uuid("projectId must be a valid UUID"),ct=S.string().min(1,"workspaceId must be a non-empty string"),ss=S.object({name:S.string().min(1,"name is required"),projectId:at.optional(),workspaceId:ct.optional(),env:Ie.default("production"),authentications:S.record(S.string()).optional().default({}),config:S.record(S.unknown()).optional().default({})}),Ur=S.object({name:S.string().min(1,"name is required"),workspaceId:ct.optional(),env:Ie,authentications:S.record(S.string()),config:S.record(S.unknown())}),is=S.discriminatedUnion("kind",[Ur.extend({kind:S.literal("provisioned"),projectId:at}),Ur.extend({kind:S.literal("unprovisioned")})]),$r=["helix","tray"],Hr=["ts","mts","cts","js","mjs","cjs"];function Pe(e){for(let t of $r)for(let r of Hr){let n=it(e,`${t}.config.${r}`);if(Mr(n))return n}}function as(e){for(let t of $r)if(Hr.some(r=>Mr(it(e,`${t}.config.${r}`))))return t;return"helix"}function ut(e){return{name:as(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function dt(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw u.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=ss.safeParse(e);if(!r.success){let d=r.error.issues.map(l=>l.message).join("; ");throw u.configLoadFailed(`Invalid helix.config.ts at ${t}: ${d}`)}let{projectId:n,workspaceId:o,...s}=r.data,i=o!==void 0?{workspaceId:o}:{},a=yt(),c=a!==void 0?{...s,env:a}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...i}:{kind:"unprovisioned",...c,...i}}async function oe(e){let t=e??process.cwd(),r;try{r=await os(ut(t))}catch(o){throw u.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??Pe(t);if(!n)throw u.configLoadFailed(`helix.config.ts not found at ${it(t,"helix.config.ts")}`);return dt(r.config,n)}var Kr="WORKSPACE_ID_REQUIRED";function cs(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:Kr});return e.workspaceId}import{existsSync as us,watch as ds,writeSync as ls}from"fs";import{join as fs,resolve as ps}from"path";import{watchConfig as ms}from"c12";function gs(e,t){let r=e instanceof Error?e.message:String(e);ls(2,`[helix-watch] ${t.phase} error: ${r}
8
- `)}function lt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ys=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,qr=new Set;function Vr(e){return Pe(e)!==void 0}async function hs(e,t){if(Vr(e.cwd))try{return{current:await oe(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:lt(),initialLoadSucceeded:!1}}if(e.watch){let r=ps(e.cwd);qr.has(r)||(process.stderr.write(`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
9
- `),qr.add(r))}return{current:lt(),initialLoadSucceeded:!1}}var ft=class{constructor(t,r,n){this.cwd=t;this.onError=r;this.emit=n}cwd;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=ms({...ut(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=dt(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){try{this.directoryWatcher=ds(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();ys.test(n)&&us(fs(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await oe(this.cwd)}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function ws(e){let t=e.onError??gs,r=new Set,n=await hs(e,t),o=n.current;function s(a){o=a;for(let c of[...r])try{c(a)}catch(d){t(d,{phase:"reload"})}}let i=new ft(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!Vr(e.cwd)){let a=lt();return s(a),a}try{let a=await oe(e.cwd);return s(a),a}catch(a){return t(a,{phase:"reload"}),o}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}export{ns as ENVIRONMENT_VALUES,Kr as WORKSPACE_ID_REQUIRED_CODE,ws as createConfigService,ts as defineConfig,qo as defineFunction,Ie as environmentSchema,zr as getContext,y as getSdkConfig,oe as loadConfig,is as loadedTrayConfigSchema,at as projectIdSchema,cs as requireWorkspaceId,Pe as resolveConfigFile,bn as runWithinAppSpan,ct as workspaceIdSchema};
1
+ import{a as wt,b as Jr}from"./chunk-L6J5L3JQ.js";import{a as T,b as D,d as y,e as O,f as I,g as mt,j as E,l as J,m as A,n as Ae,o as _e,p as St,q as L,r as xt,s as ae,t as ce,u as ue,v as Ct}from"./chunk-KURGNIK4.js";import{a as z,b as ie,c as bt,d as Et}from"./chunk-5XNPF4RA.js";import{b as gt,d as F,e as yt,i as ht,l as u,m as vt}from"./chunk-ATJUJXR7.js";import{randomUUID as Mo}from"crypto";import{SpanStatusCode as Nr,SpanKind as $o}from"@opentelemetry/api";import{AsyncLocalStorage as qt}from"async_hooks";import{trace as un,SpanKind as dn,SpanStatusCode as Fe}from"@opentelemetry/api";import{ExportResultCode as ln,W3CTraceContextPropagator as fn}from"@opentelemetry/core";import{NodeTracerProvider as pn,SimpleSpanProcessor as mn,BatchSpanProcessor as gn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Yr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Gr}from"@opentelemetry/exporter-logs-otlp-proto";function De(e){return F(e).hosts.ingest}function Xr(){return I()??""}function Rt(){return{[T]:Xr()}}function kt(){let e=De(E().env);return new Yr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Rt())})}function Tt(){let e=De(E().env);return new Gr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Rt())})}import{logs as At,SeverityNumber as de}from"@opentelemetry/api-logs";import{LoggerProvider as en,BatchLogRecordProcessor as tn}from"@opentelemetry/sdk-logs";function Y(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Zr(e){return new TextEncoder().encode(e).length}var It="\u2026[truncated]",Qr=Zr(It),j=4096;function _(e,t=j){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Qr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+It}function v(e,t=j){return _(Y(e),t)}var rn="@trayai/helix-sdk",G,Pt={debug:{number:de.DEBUG,text:"DEBUG"},info:{number:de.INFO,text:"INFO"},warn:{number:de.WARN,text:"WARN"},error:{number:de.ERROR,text:"ERROR"}};function nn(){return y().mode==="lambda"?[new tn({exporter:Tt()})]:[]}function _t(){if(G!==void 0)return;let e=nn();e.length!==0&&(G=new en({processors:e}),At.setGlobalLoggerProvider(G))}function on(e,t,r){let n=Pt[e]??Pt.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":v(r)}}:{}}}function Dt(e,t,r){At.getLogger(rn).emit(on(e,t,r))}async function Ot(e=2e3){if(G===void 0)return;let t;try{await Promise.race([G.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
+ `)}finally{t!==void 0&&clearTimeout(t)}}function Oe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function sn(){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 sn()?`\x1B[${e}m${t}\x1B[0m`:t}var an=5,cn={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ft="32",Lt="31",le="2",jt="1";function fe(e){return k(cn[e]??"0",e.padEnd(an))}function Nt(e,t){return`${fe("FN")} ${k(jt,`${e} ${t}`.trim())}`}function Bt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${k(le,n)} `:""}${fe(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${k(le,Y(r))}`),i}function Ut(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Mt(e){return`${fe("AUTH")} ${e}`}function $t(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=k(o==="error"?Lt:Ft,s);return`${fe("API")} ${e} ${t} \u2192 ${i} ${k(le,`${n}ms`)}`}function Ht(e,t,r){let n=t?Lt:Ft,o=k(n,"\u25CF"),s=k(n,t?"error":"success");return`${o} ${k(jt,e)} ${s} ${k(le,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var pe=new qt,me=new qt;function C(e){let t=me.getStore();t&&(t[e]=!0)}var yn=/^[0-9a-f]{32}$/;function hn(e){let t=e.replace(/-/g,"").toLowerCase();return yn.test(t)?t:null}var wn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},B=new Map;function x(e,t,r){let n=B.get(e);n?n[t]=r:B.set(e,{[t]:r})}var X;function Kt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function vn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Vt(e){try{process.stdout.write(Y(e)+`
4
+ `)}catch{}}var Le=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=B.get(o),i={...n.attributes};if(s!==void 0){for(let[d,l]of Object.entries(s))typeof l=="string"?i[d]=_(l):typeof l=="object"&&l!==null?i[d]=v(l):i[d]=l;B.delete(o)}let a=pe.getStore(),c=a?hn(a):null;Vt({_otel:"span",traceId:c??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Kt(n.startTime),endTimeUnixNano:Kt(n.endTime),attributes:i,status:{code:wn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:ln.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t,r){}onEnd(t){B.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
+ `+Nt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=B.get(n)?.properties;N(Bt(String(r.level??"info"),String(r.message??""),o,Ut(t.startTime)));break}case"auth":N(Mt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N($t(String(r.method??""),String(r.host??""),n,vn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Be=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function bn(){let t=[Oe()?new Ne:new mn(new Le)];return y().mode==="lambda"&&t.push(new Be(new gn(kt()))),t.push(new je),t}function Ue(){X===void 0&&(X=new pn({spanProcessors:bn()}),X.register({propagator:new fn}),_t())}async function Me(e=2e3){let t=[Ot(e)];X!==void 0&&t.push((async()=>{let r;try{await Promise.race([X.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
+ `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var R=un.getTracer("@trayai/helix-sdk");function $e({executionId:e,deploymentId:t,routeOrJob:r,startedAt:n,startMs:o,errored:s,errorMessage:i,userId:a,flags:c}){let d=new Date().toISOString(),l=Date.now()-o;if(Oe()){N(`
7
+ `+Ht(r,s,l));return}Vt({_otel:"summary",executionId:e,deploymentId:t,triggerType:"http",routeOrJob:r,status:s?"error":"success",startedAt:n,finishedAt:d,durationMs:l,userId:a,hasError:s||c.hasError,hasAuth:c.hasAuth,hasExternal:c.hasExternal,hasDb:c.hasDb,errorSummary:s&&i!==null?_(i):null})}async function En(e,t){let r=e.startMs??Date.now();Ue();let n=!1,o=null;try{return await pe.run(e.executionId,()=>R.startActiveSpan("App",{kind:dn.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{$e({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 Ho,getMethod as Ko,getRequestURL as qo,getHeaders as Ur,getHeader as Br}from"h3";import{readBody as Sn,getQuery as xn,getRouterParams as Cn}from"h3";async function Wt(e,t){let r=await Rn(e),n=xn(e),o=Cn(e)??{},s={...n,...r,...o};return t?kn(s,t):s}async function Rn(e){try{let t=await Sn(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 kn(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 Tn}from"@opentelemetry/api";function ge(e,t,r){let n=R.startSpan("log",{kind:Tn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&x(n.spanContext().spanId,"properties",r),n.end(),Dt(e,t,r)}function zt(){return{info:(e,t)=>ge("info",e,t),warn:(e,t)=>ge("warn",e,t),error:(e,t)=>ge("error",e,t),debug:(e,t)=>ge("debug",e,t)}}var Z=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Jt(e){return t=>{e.node.res.statusCode=t}}function Yt(){return(e,t)=>{throw new Z(e,t)}}import An from"ky";import{context as He,trace as _n,SpanKind as he,SpanStatusCode as Zt}from"@opentelemetry/api";import In from"ky";async function Gt(e,t={}){let r=O(),n=I(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw u.missingExecutionCredentials();let{env:i}=E(),a=ie(i),c=t.timeout??6e4,d={Accept:"application/json"};o&&(d[D]=r),s&&(d[T]=n);let l=y().deploymentId,m=l?{...e,deploymentId:l}:e,f=await In.post(`${a}/broker/http`,{json:m,headers:d,throwHttpErrors:!1,timeout:c}),p;return(f.headers.get("content-type")??"").includes("application/json")?p=await f.json():p=await f.text(),{status:f.status,body:p}}import Pn from"ky";async function Xt(e,t={}){let r=mt();if(!r)throw u.missingTrayToken();let{env:n}=E(),o=ie(n),s=t.timeout??6e4,i=await Pn.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:s}),a;return(i.headers.get("content-type")??"").includes("application/json")?a=await i.json():a=await i.text(),{status:i.status,body:a}}async function ye(e,t={}){let r=y().mode==="lambda"?Gt:Xt,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=bt.safeParse(s);if(!i.success)throw u.brokerError(o,"broker returned malformed response",v(s));return Et(i.data)}var Dn=["get","post","put","patch","delete","head","options"],Qt="[stream body omitted]";function Ke(e){try{return new URL(e).hostname}catch{return e}}function On(e,t,r,n){let o=Ke(t),s="externalApi",i={kind:he.CLIENT};return R.startActiveSpan(s,i,async a=>{let c=a.spanContext().spanId;return a.setAttributes({method:e,host:o}),x(c,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?Qt:r}:{}}),n(a,c)})}function qe(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Zt.OK}:{code:Zt.ERROR,message:r}),e.end()}var Fn=16;async function Ln(e,t){let r=e.clone().body;return r?er(r,t):new Uint8Array(0)}async function er(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>=Fn)break;continue}s=0;let l=t+1-o;if(d.byteLength>=l){n.push(d.slice(0,l)),o+=l;break}n.push(d),o+=d.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of n)i.set(c,a),a+=c.byteLength;return i}async function tr(e,t,r){if("kyResponse"in r)try{let n=await Ln(r.kyResponse,j),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;if(n.length<=j)try{s=JSON.parse(o)}catch{s=o}else s=o;x(e,"response",s)}catch{x(e,"response",{status:t})}else x(e,"response",r.bodyValue)}async function jn(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 er(o,j);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:Qt}}}return typeof t=="string"?{body:t}:{}}function rr(){let e=An.create({});function t(n){return(o,s)=>{let i=He.active(),a,c="",d=!1,l=(f,p)=>{a&&!d&&(d=!0,qe(a,f,p))},m=e.extend({hooks:{beforeRequest:[async(f,p)=>{let g=await jn(f,p.body),w=g.body;if(a||(a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId),a.setAttributes({method:f.method.toUpperCase(),host:Ke(f.url)}),x(c,"request",{url:f.url,method:f.method.toUpperCase(),...w!==void 0?{body:w}:{}}),d=!1,C("hasExternal"),g.request)return g.request}],beforeRetry:[f=>{l("error","retry"),a=void 0,c="",d=!1}],afterResponse:[async(f,p,g)=>{a&&(a.setAttribute("statusCode",g.status),await tr(c,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(C("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[f=>(C("hasError"),l("error",f.message),f)]}});return a=R.startSpan("externalApi",{kind:he.CLIENT},i),c=a.spanContext().spanId,a.setAttributes({method:n.toUpperCase(),host:Ke(String(o))}),He.with(_n.setSpan(He.active(),a),()=>{let f=n==="options"?m(o,{...s,method:"OPTIONS"}):m[n](o,s);return f.catch(p=>{C("hasError"),l("error",p instanceof Error?p.message:String(p))}),f})}}let r=Object.fromEntries(Dn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Nn(n)}}}function Nn(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(i,a={})=>{let c=s.toUpperCase();return On(c,i,a.body,async(d,l)=>{C("hasAuth");let m=R.startSpan("auth",{kind:he.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let f=z({authenticationId:n,method:c,url:i,body:a.body,headers:a.headers,query:a.query}),p=await ye(f,{timeout:a.timeout});return d.setAttribute("statusCode",p.status),await tr(l,p.status,{bodyValue:p.body}),qe(d,"success"),p}catch(f){throw C("hasError"),f instanceof u&&f.detail.kind==="broker_error"&&f.detail.status>0&&d.setAttribute("statusCode",f.detail.status),qe(d,"error",f instanceof Error?f.message:String(f)),f}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as Wn,SpanStatusCode as ir}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Bn=18e4,nr=Bn-1e4,Un=2e3;async function or(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<nr;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let c=Math.min(Un,200*2**s),d=c/2+Math.random()*(c/2),l=nr-(Date.now()-o);await new Promise(m=>setTimeout(m,Math.min(d,l))),s++}throw u.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Mn=new Set(["SELECT","WITH","SHOW"]),$n=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Hn(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 Kn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return u.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):v(t);return u.dbCallFailed(s)}function qn(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 Vn(e,t){return typeof t!="number"||t<0?{}:Mn.has(e)?{rowsRead:t}:$n.has(e)?{rowsWritten:t}:{}}function sr(e){async function t(r,n,o){let s=z({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:i,body:a}=await ye(s);if(i>=400)throw Kn(i,a);return qn(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:Hn,async execute(r,n){let o=Q(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let p=v(i);throw u.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let d=await or(t,r.region,c),l=d.Status;if(l==="FAILED"){let p=typeof d.Error=="string"?d.Error:"statement failed";throw u.dbQueryFailed(`${p} (statement: ${c})`)}if(l==="ABORTED")throw u.dbQueryFailed(`statement aborted (statement: ${c})`);let m=Vn(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 Ve=64*1024;function zn(e){return e.length>Ve?`${e.slice(0,Ve)}...[truncated]`:e}function Jn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Yn(e,t,r,n){let o=typeof r=="string"?r:JSON.stringify(r);return o.length>Ve?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 Gn(e,t,r){let n=Q(r),o=zn(r);return R.startActiveSpan("database",{kind:Wn.CLIENT},async s=>{let i=s.spanContext().spanId;Jn(s,e,t,n,o);try{C("hasDb");let{result:a,metadata:c}=await e.execute(t,r),d=Yn(s,i,a,c);return s.setAttribute("status","success"),s.setStatus({code:ir.OK}),d}catch(a){C("hasError");let c=a instanceof Error?a.message:String(a);throw s.setAttribute("status","error"),s.setStatus({code:ir.ERROR,message:c}),a}finally{s.end()}})}function We(e){let r=E().authentications??{};if(!r[e])throw u.unknownAlias(e,Object.keys(r));let n=r[e],o=sr(n);function s(i,a){return o.validate(i),Gn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as to}from"unstorage";var ar=1024,ze=250*1024,Xn=new TextEncoder,Zn=/(^|\/)\.\.(\/|$)/,Qn=/[?#]/,eo=/[\u0000-\u001F\u007F]/;function cr(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(Qn.test(e)||eo.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=Xn.encode(e).length;if(t<1||t>ar)throw u.kvKeyInvalid(`Key must be between 1 and ${ar} UTF-8 bytes (got ${t})`)}function ur(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>ze)throw u.kvValueTooLarge(`Value exceeds maximum size of ${ze} bytes (got ${r})`,ze)}function ee(e){cr(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function dr(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return ee(i),t(i,a)},setItem(i,a,c){return ee(i),r(i,a,c)},removeItem(i,a){return ee(i),n(i,a)},hasItem(i,a){return ee(i),o(i,a)},getKeys(i,a){return i.length>0&&ee(i),s(i,a)}}}function ve(e){return to({driver:dr(e)})}import{defineDriver as ro}from"unstorage";function no(e){try{return JSON.parse(e)}catch{return e}}var oo=ro(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,no(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 lr(e){return oo({client:e})}import ao from"ky";import{z as b}from"zod";async function U(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function fr(e){return F(e).hosts.api}function so(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function io(e){return e.split("/").map(encodeURIComponent).join("/")}function te(e,t,r){return`${e}${so(t)}/${io(r)}`}var co=6e4,Je=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(Je),b.record(Je)])),uo=b.object({projectId:b.string(),key:b.string(),value:Je,type:b.enum(["string","number","boolean","null","array","object"]),organizationId:b.string(),scope:b.string(),createdBy:b.string(),createdAt:b.number(),updatedBy:b.string(),updatedAt:b.number()});function lo(){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 fo(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,fo(t),v(t))}async function Ee(e,t,r={}){try{let n=await ao(t,{method:e,headers:lo(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:co}),o=e==="head"?void 0:await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw u.kvCallFailed(0,o)}}function pr(e){let t=fr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",te(t,r,n));if(o===404)return null;(o<200||o>=300)&&be(o,s);let i=uo.safeParse(s);if(!i.success)throw u.kvCallFailed(o,"platform returned malformed KeyValueEntry",v(s));return i.data.value},async set(n,o){let{status:s,body:i}=await Ee("put",te(t,r,n),{json:{value:o}});(s<200||s>=300)&&be(s,i)},async delete(n){let{status:o,body:s}=await Ee("delete",te(t,r,n));o!==204&&be(o,s)},async has(n){let{status:o,body:s}=await Ee("head",te(t,r,n));if(o===200)return!0;if(o===404)return!1;be(o,s)}}}function Se(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{ur(r),await e.setItem(t,r,n)}}}function po(){let e=E();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function mr(e){let t=po(),r=e??pr(t),n=ve(lr(r));return Se(n)}import mo from"unstorage/drivers/memory";var Ye;function go(){return Ye||(Ye=ve(mo())),Ye}function gr(){return Se(go())}function yo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function yr(){return yo()?mr():gr()}import{createHash as vo}from"crypto";import{mkdir as bo,readFile as Er,readdir as Sr,rm as wr,unlink as Eo,writeFile as vr}from"fs/promises";import{dirname as So}from"path";async function ho(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>J)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${J} bytes (got more than ${J})`,J);r.push(s)}}return Buffer.concat(r)}async function M(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?ho(e):Buffer.from(e)}var wo={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"},hr="application/octet-stream";function xe(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return hr;let r=e.slice(t+1).toLowerCase();return wo[r]??hr}function H(){let e=y().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function $(e){try{return await e()}catch(t){if(t instanceof u)throw t;let r=t?.code;throw r?u.filesCallFailed(0,`Local file storage operation failed: ${r}`):u.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Ce(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ge(e){try{let t=await Er(ce(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function br(e){await bo(So(e),{recursive:!0})}async function xo(e,t){let r=ue(e,t),n;try{n=await Sr(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 xr(e,t){let r=ue(e,t),n;try{n=await Sr(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 xr(e,i)):s.isFile()&&o.push(i)}return o}function Cr(){return{async put(e,t,r){return $(async()=>{let n=H(),o=await M(t),s=r?.contentType??xe(e),i=vo("sha1").update(o).digest("hex"),a=new Date,c=ae(n,e);await br(c),await vr(c,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},l=ce(n,e);return await br(l),await vr(l,JSON.stringify(d)),Ce(e,d)})},async get(e){return $(async()=>{let t=await Ge(e);return t?{data:await Er(ae(H(),e)),metadata:Ce(e,t)}:null})},async head(e){return $(async()=>{let t=await Ge(e);return t?Ce(e,t):null})},async delete(e){return $(async()=>{let t=H();await Promise.all([ae(t,e),ce(t,e)].map(async r=>{try{await Eo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return $(async()=>{let t=H(),r=await xr(t,e);return await Promise.all([wr(ue(t,e),{recursive:!0,force:!0}),wr(Ct(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return $(async()=>{let r=H(),n=t?.limit??100,s=(await xo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let c=await Ge(a);return c?Ce(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw u.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}}}}import{createHash as Ao}from"crypto";function Re(e){return F(e).hosts.api}function Co(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function re(e,t){return`${e}${Co(t)}`}function K(e,t,r){return`${re(e,t)}/${encodeURIComponent(r)}`}function ke(e,t,r){return`${K(e,t,r)}/upload`}function Rr(e,t,r){return`${K(e,t,r)}/download`}function kr(e,t,r){return`${K(e,t,r)}/signed-url`}function Tr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${re(e,t)}/file?${o.toString()}`}function Ir(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${re(e,t)}?${o.toString()}`}import Ze from"ky";import{z as h}from"zod";var Qe=6e4,Pr=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()}),Ro=h.object({signedURL:h.string()}),ko=h.object({path:h.array(h.object({id:h.string(),name:h.string()})),elements:h.array(Pr)});function et(){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 Ar(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,Ar(t),v(t))}function To(e,t){return e===400&&Ar(t).toLowerCase()==="resource not found"}async function Io(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function q(e,t,r={}){try{let n=await Ze(t,{method:e,headers:et(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Qe}),o=await U(n);return{status:n.status,body:o}}catch(n){if(n instanceof u)throw n;let o=n instanceof Error?n.message:String(n);throw u.filesCallFailed(0,o)}}function Xe(e,t){let r=Pr.safeParse(t);if(!r.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",v(t));return r.data}function _r(e){let t=Re(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await q("post",re(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Xe(o,s)},async getByName(n,o){let{status:s,body:i}=await q("get",Tr(t,r,n,o));return s===404||To(s,i)?null:((s<200||s>=300)&&P(s,i),Xe(s,i))},async getById(n){let{status:o,body:s}=await q("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Xe(o,s))},async listChildren(n,o){let{status:s,body:i}=await q("get",Ir(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=ko.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 Io(a),l;try{l=await Ze(ke(t,r,n),{method:"post",headers:{...et(),"content-type":d},body:new Uint8Array(c),throwHttpErrors:!1,timeout:Qe})}catch(f){if(f instanceof u)throw f;let p=f instanceof Error?f.message:String(f);throw u.filesCallFailed(0,p)}let m=await U(l);(l.status<200||l.status>=300)&&P(l.status,m)},async downloadContent(n){let o;try{o=await Ze(Rr(t,r,n),{method:"get",headers:et(),throwHttpErrors:!1,timeout:Qe})}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message:String(i);throw u.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await U(o);P(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await q("get",kr(t,r,n));(o<200||o>=300)&&P(o,s);let i=Ro.safeParse(s);if(!i.success)throw u.filesCallFailed(o,"platform returned malformed signed URL response",v(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await q("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function tt(e){return e.split("/").filter(t=>t.length>0)}function rt(e){return e instanceof u&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Po(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(rt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function nt(e,t){let r=tt(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await Po(e,o,s)).id;return{parentFolder:o,name:n}}async function ne(e,t){let r=tt(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 ot(e,t){if(t.length===0)return;let r=tt(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 _o=500,Do=8;async function Oo(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 Fo(){let e=E();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Lo(e){return Ao("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Te(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Lo(t)}}async function Dr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(rt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Or(e,t){let{elements:r}=await e.listChildren(t,_o);return(await Oo(r,Do,async o=>{let s=o.objectType==="Folder"?await Or(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Fr(e){let t=Fo(),r=e??_r(t),n=Re(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:d}=await nt(r,s),l=await M(i),m=a?.contentType??xe(s),f=await r.getByName(c,d);if(f&&f.objectType!=="File")throw u.filesCallFailed(409,`A folder already exists at "${s}"`);let p=f??await Dr(r,c,d,m);await r.uploadContent(p.id,l,d,m);let g=await r.getById(p.id);return Te(s,g??p,m)},async get(s){let i=await ne(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Te(s,a)}},async head(s){let i=await ne(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Te(s,a)},async delete(s){let i=await ne(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await ot(r,s);if(i===null)return{deleted:0};let a=await Or(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await ot(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 nt(r,s),l=await r.getByName(a,c)??await Dr(r,a,c,i?.contentType);return{url:ke(n,o,l.id),expiresAt:L(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await ne(r,s),c=a?await r.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw u.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(c.id),expiresAt:L(i?.expiresIn)}}}}function st(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){A(n,r);let i=await M(o);return St(i.byteLength),e.put(n,i,s)},async get(n){return A(n,r),e.get(n)},async head(n){return A(n,r),e.head(n)},async delete(n){return A(n,r),e.delete(n)},async deleteMany(n){let o=Ae(n);return _e(o,r),e.deleteMany(o)},async list(n,o){let s=Ae(n??"");return _e(s,r),e.list(s,o)},async getUploadUrl(n,o){return A(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return A(n,r),e.getDownloadUrl(n,o)}}}function jo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Lr(){if(jo())return st(Fr());let e=y().projectRoot;return st(Cr(),{maxPathBytes:e?xt(e):void 0})}function jr(e,t){let{statusCode:r,message:n}=No(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function No(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 Bo=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Uo(e){return e.toLowerCase().includes("tray_lid")}function it(e){let t={};for(let[r,n]of Object.entries(e))if(!Bo.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!Uo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Vo(e,t){let{inputSchema:r,outputSchema:n}=Xo(t),o=e;return Ho(async s=>{let i=y(),{executionId:a,userId:c,deploymentId:d}=Zo(i,s),l=Date.now(),m=new Date().toISOString(),f=Ko(s),p=qo(s).pathname,g=Qo(),w=zt(),V=`${f} ${p}`;Ue();let W={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Wo(()=>me.run(W,()=>pe.run(a,async()=>{let se=await zo(s,r);if(!se.ok)return{response:se.response,errored:!1,errorMessage:null};let zr=ts(s,se.input,g,w,f,p,a,d,c);return Jo(o,zr,n,s,w,a,d,{method:f,path:p,rawInput:se.input})})),{executionId:a,deploymentId:d,routeOrJob:V,startedAt:m,startMs:l,userId:c,flags:W})})}async function Wo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{$e({...t,errored:r,errorMessage:n}),await Me()}}async function zo(e,t){try{return{ok:!0,input:await Wt(e,t)}}catch(r){let n=es(e,r);if(n)return{ok:!1,response:n};throw r}}async function Jo(e,t,r,n,o,s,i,a){return R.startActiveSpan("function",{root:!0,kind:$o.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async c=>{t.traceId=c.spanContext().traceId;let d=it(Ur(n)),l=c.spanContext().spanId;x(l,"input",a.rawInput),x(l,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let m=!1,f=null,p,g;try{let w=await wt.run(t,()=>e(t));if(p=w,w==null)n.node.res.statusCode=204,g="";else if(w instanceof Response)g=w;else if(r){let V=r.safeParse(w);if(!V.success){let W=Object.keys(V.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:W,executionId:s}),u.outputValidationFailed(W)}g=V.data}else g=w}catch(w){m=!0,f=w instanceof Error?w.message:String(w),C("hasError"),g=Yo(w,n,o,s)}finally{Go(c,n,{errored:m,errorMessage:f,handlerResult:p,response:g})}return{response:g,errored:m,errorMessage:f}})}function Yo(e,t,r,n){if(e instanceof Z)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(vt(e))return jr(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 Go(e,t,r){let n=e.spanContext().spanId;e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&x(n,"output",r.handlerResult),x(n,"response",r.response);let o=me.getStore();e.setAttribute("hasAuth",o?.hasAuth??!1),e.setAttribute("hasExternal",o?.hasExternal??!1),e.setAttribute("hasDb",o?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let s=r.errored||(o?.hasError??!1);e.setStatus({code:s?Nr.ERROR:Nr.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Xo(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 Zo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:Br(t,"x-tray-execution-id"))??Mo(),o=(r?e.userId:Br(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Qo(){try{return E().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function es(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 ts(e,t,r,n,o,s,i,a,c){return{input:t,method:o,path:s,headers:it(Ur(e)),http:rr(),db:d=>We(d),kv:()=>yr(),files:()=>Lr(),log:n,config:r,status:Jt(e),error:Yt(),state:{},request:e,executionId:i,deploymentId:a,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function rs(e){return e}import{resolve as at}from"path";import{existsSync as $r}from"fs";import{loadConfig as ss}from"c12";import{z as S}from"zod";import{z as ns}from"zod";var os=["production"],Ie=ns.string().refine(e=>gt(e),e=>({message:`Invalid enum value. Expected ${yt().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var ct=S.string().uuid("projectId must be a valid UUID"),ut=S.string().min(1,"workspaceId must be a non-empty string"),is=S.object({name:S.string().min(1,"name is required"),projectId:ct.optional(),workspaceId:ut.optional(),env:Ie.default("production"),authentications:S.record(S.string()).optional().default({}),config:S.record(S.unknown()).optional().default({})}),Mr=S.object({name:S.string().min(1,"name is required"),workspaceId:ut.optional(),env:Ie,authentications:S.record(S.string()),config:S.record(S.unknown())}),as=S.discriminatedUnion("kind",[Mr.extend({kind:S.literal("provisioned"),projectId:ct}),Mr.extend({kind:S.literal("unprovisioned")})]),Hr=["helix","tray"],Kr=["ts","mts","cts","js","mjs","cjs"];function Pe(e){for(let t of Hr)for(let r of Kr){let n=at(e,`${t}.config.${r}`);if($r(n))return n}}function cs(e){for(let t of Hr)if(Kr.some(r=>$r(at(e,`${t}.config.${r}`))))return t;return"helix"}function dt(e){return{name:cs(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function lt(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=is.safeParse(e);if(!r.success){let d=r.error.issues.map(l=>l.message).join("; ");throw u.configLoadFailed(`Invalid helix.config.ts at ${t}: ${d}`)}let{projectId:n,workspaceId:o,...s}=r.data,i=o!==void 0?{workspaceId:o}:{},a=ht(),c=a!==void 0?{...s,env:a}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...i}:{kind:"unprovisioned",...c,...i}}async function oe(e){let t=e??process.cwd(),r;try{r=await ss(dt(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 ${at(t,"helix.config.ts")}`);return lt(r.config,n)}var qr="WORKSPACE_ID_REQUIRED";function us(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:qr});return e.workspaceId}import{existsSync as ds,watch as ls,writeSync as fs}from"fs";import{join as ps,resolve as ms}from"path";import{watchConfig as gs}from"c12";function ys(e,t){let r=e instanceof Error?e.message:String(e);fs(2,`[helix-watch] ${t.phase} error: ${r}
8
+ `)}function ft(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var hs=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,Vr=new Set;function Wr(e){return Pe(e)!==void 0}async function ws(e,t){if(Wr(e.cwd))try{return{current:await oe(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:ft(),initialLoadSucceeded:!1}}if(e.watch){let r=ms(e.cwd);Vr.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
+ `),Vr.add(r))}return{current:ft(),initialLoadSucceeded:!1}}var pt=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=gs({...dt(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=lt(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=ls(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();hs.test(n)&&ds(ps(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await oe(this.cwd)}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function vs(e){let t=e.onError??ys,r=new Set,n=await ws(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 pt(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!Wr(e.cwd)){let a=ft();return s(a),a}try{let a=await oe(e.cwd);return s(a),a}catch(a){return t(a,{phase:"reload"}),o}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}export{os as ENVIRONMENT_VALUES,qr as WORKSPACE_ID_REQUIRED_CODE,vs as createConfigService,rs as defineConfig,Vo as defineFunction,Ie as environmentSchema,Jr as getContext,y as getSdkConfig,oe as loadConfig,as as loadedTrayConfigSchema,ct as projectIdSchema,us as requireWorkspaceId,Pe as resolveConfigFile,En as runWithinAppSpan,ut as workspaceIdSchema};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.69.0",
3
+ "version": "0.69.2",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",