@trayai/helix-sdk 0.101.0 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,20 @@ general availability, minor versions may include breaking changes.
9
9
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
10
10
  released together and share a version — install matching versions.
11
11
 
12
+ ## 0.103.0
13
+
14
+ ### Added
15
+
16
+ - **Signed S3 URLs.** `ctx.http.authed(alias).s3Sign(url, options?)` mints a
17
+ presigned S3 URL for an AWS/S3 authentication — a time-limited URL used
18
+ against S3 directly, with no credentials attached. Sign `GET` for downloads
19
+ (the default), `PUT` for uploads (also `POST`/`DELETE`/`HEAD`), with a
20
+ configurable `expiresIn` (default 15 minutes, max one week). Because the
21
+ transfer goes straight to S3, the 16 MB request-body cap on authed calls
22
+ does not apply. Returns `{ url, method, expiresAt }`. New exported types:
23
+ `S3SignOptions`, `S3SignResult` (plus `BrokerAuthedClient`,
24
+ `BrokerCallOptions`, `BrokerCallResult`, which were previously unexported).
25
+
12
26
  ## 0.100.0
13
27
 
14
28
  ### Added
package/README.md CHANGED
@@ -111,6 +111,38 @@ Each method returns `{ status, body?, headers }`. An upstream non-2xx response i
111
111
  - Redirects are not followed: a 3xx response is returned to your code with its `location` header, and following it is your decision.
112
112
  - An unknown alias throws `SdkError.unknownAlias` (the error lists the configured aliases).
113
113
 
114
+ ### Signed S3 URLs — `s3Sign`
115
+
116
+ For AWS/S3 authentications, the authed client can mint a **presigned S3 URL** — a time-limited URL your code (or anyone you hand it to) uses against S3 directly, with no credentials attached:
117
+
118
+ ```typescript
119
+ export default defineFunction(async (ctx) => {
120
+ const aws = ctx.http.authed('aws-s3'); // an AWS/S3 alias from helix.config.ts
121
+
122
+ // Download link (GET is the default), valid 15 minutes:
123
+ const download = await aws.s3Sign(
124
+ 'https://my-bucket.s3.eu-west-1.amazonaws.com/reports/summary.pdf',
125
+ );
126
+
127
+ // Upload link, valid one hour:
128
+ const upload = await aws.s3Sign(
129
+ 'https://my-bucket.s3.eu-west-1.amazonaws.com/incoming/video.mp4',
130
+ { method: 'PUT', expiresIn: 3600 },
131
+ );
132
+
133
+ return { downloadUrl: download.url, uploadUrl: upload.url, expiresAt: download.expiresAt };
134
+ });
135
+ ```
136
+
137
+ `s3Sign(url, options?)` returns `{ url, method, expiresAt }`. Notes:
138
+
139
+ - Works with AWS/S3 authentications only — an authentication for any other service is rejected.
140
+ - `url` is the full `https:` object URL, path-style (`https://s3.<region>.amazonaws.com/<bucket>/<key>`) or virtual-hosted (`https://<bucket>.s3.<region>.amazonaws.com/<key>`).
141
+ - `options.method` is the HTTP method the URL will be signed for — `GET` (default), `PUT`, `POST`, `DELETE`, or `HEAD`. Using the URL with any other method fails.
142
+ - `options.expiresIn` is the lifetime in seconds — default 900 (15 minutes), maximum 604800 (one week, an AWS limit).
143
+ - Transfers with the signed URL go straight to S3, so the 16 MB request-body cap on authed calls does not apply — presigned `PUT` URLs are the way to move large objects.
144
+ - The URL grants access to that object until it expires: treat it like a secret.
145
+
114
146
  ## Capability modules
115
147
 
116
148
  ### Key-value store — `ctx.kv()`
@@ -65,5 +65,49 @@ type BrokerDevCallResult = {
65
65
  * the env, dev token, and authentication UUID explicitly.
66
66
  */
67
67
  declare function callBrokerDev(params: BrokerDevCallParams): Promise<BrokerDevCallResult>;
68
+ interface S3SignDevCallParams {
69
+ /** Target Tray environment — selects the broker base URL. */
70
+ env: BrokerEnvironment;
71
+ /** Personal dev token (the user's local Tray login) sent as `Authorization: Bearer`. */
72
+ devToken: string;
73
+ /** Credential record UUID of an AWS/S3 authentication. */
74
+ authenticationId: string;
75
+ /** Full https S3 object URL, path-style or virtual-hosted. */
76
+ url: string;
77
+ /** Method the presigned URL will be used with (GET/PUT/POST/DELETE/HEAD; default GET). */
78
+ method?: string;
79
+ /** Seconds until the URL expires (broker default 900; max one week). */
80
+ expiresIn?: number;
81
+ timeoutMs?: number;
82
+ }
83
+ /**
84
+ * Result of a one-shot dev s3-sign call.
85
+ * - `signed` — the presigned URL envelope; the URL is used against S3 directly.
86
+ * - `brokerError` — a broker-generated error. `code` is the wire error code
87
+ * when the body parsed as the broker envelope.
88
+ */
89
+ type S3SignDevCallResult = {
90
+ kind: "signed";
91
+ signed: {
92
+ url: string;
93
+ method: string;
94
+ expiresAt: string;
95
+ };
96
+ } | {
97
+ kind: "brokerError";
98
+ brokerStatus: number;
99
+ code?: string;
100
+ body: unknown;
101
+ };
102
+ /**
103
+ * Stateless, one-shot call to the credential broker's s3-sign dev endpoint
104
+ * (`POST /private/v1/helix/broker/s3/sign/dev`).
105
+ *
106
+ * The dev twin of `ctx.http.authed(...).s3Sign(...)`, factored out so CLI
107
+ * tooling can mint a presigned S3 URL without booting the dev server. Reads
108
+ * no module-global state: env, dev token, and authentication UUID are passed
109
+ * explicitly.
110
+ */
111
+ declare function callS3SignDev(params: S3SignDevCallParams): Promise<S3SignDevCallResult>;
68
112
 
69
- export { type BrokerDevCallParams, type BrokerDevCallResult, type BrokerEnvironment, type UpstreamResponse, callBrokerDev };
113
+ export { type BrokerDevCallParams, type BrokerDevCallResult, type BrokerEnvironment, type S3SignDevCallParams, type S3SignDevCallResult, type UpstreamResponse, callBrokerDev, callS3SignDev };
@@ -1 +1 @@
1
- import{p as t,q as o,r as n,s}from"../chunk-Q6GJ4HQZ.js";async function u(e){let i=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),r=await s({proxyUrl:t(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:i,timeoutMs:e.timeoutMs??n});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"upstream",upstream:r.response}}export{u as callBrokerDev};
1
+ import{p as n,q as o,r as i,s,t as d,u,v as l}from"../chunk-D5GPRK2D.js";async function a(e){let r=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),t=await s({proxyUrl:n(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:r,timeoutMs:e.timeoutMs??i});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"upstream",upstream:t.response}}async function k(e){d(e.url);let r=await l({signUrl:u(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"signed",signed:r.result}}export{a as callBrokerDev,k as callS3SignDev};
@@ -0,0 +1,7 @@
1
+ import{d as _,l as c,n as tt,o as se,p as Ce,q as V,s as rt,t as nt,u as Ae,v as ot}from"./chunk-D5GPRK2D.js";var E="X-Helix-Project-Execution-Token",P="X-Tray-Token",xr={mode:"dev",deploymentId:null},ke={...xr},F={};function wo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(F.internalJwt=t),"helixExecutionJwt"in e&&(F.helixExecutionJwt=r),"devToken"in e&&(F.devToken=n),ke={...ke,...o}}function w(){return ke}function I(){return F.internalJwt}function v(){return F.helixExecutionJwt}function ae(){return F.devToken}var So="tray-config-bridge",xo="tray-dev-token-bridge",ce=null;function Eo(e){ce=e}function b(){if(!ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ce}function vo(){ce=null}import{AsyncLocalStorage as Rt}from"async_hooks";import{trace as Nr,SpanKind as Lr,SpanStatusCode as _e}from"@opentelemetry/api";import{ExportResultCode as Br,W3CTraceContextPropagator as Mr}from"@opentelemetry/core";import{NodeTracerProvider as Ur,SimpleSpanProcessor as jr,BatchSpanProcessor as Kr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Er}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as vr}from"@opentelemetry/exporter-logs-otlp-proto";function De(e){return _(e).hosts.ingest}function Rr(){return v()??""}function it(){return{[E]:Rr()}}function st(){let e=De(b().env);return new Er({url:`${e}/v1/traces`,headers:()=>Promise.resolve(it())})}function at(){let e=De(b().env);return new vr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(it())})}import{logs as ut,SeverityNumber as le}from"@opentelemetry/api-logs";import{LoggerProvider as Ir,BatchLogRecordProcessor as Cr}from"@opentelemetry/sdk-logs";function J(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Tr(e){return new TextEncoder().encode(e).length}var ct="\u2026[truncated]",Pr=Tr(ct),z=4096;function D(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Pr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+ct}function g(e,t=z){return D(J(e),t)}var Ar="@trayai/helix-sdk",q,lt={debug:{number:le.DEBUG,text:"DEBUG"},info:{number:le.INFO,text:"INFO"},warn:{number:le.WARN,text:"WARN"},error:{number:le.ERROR,text:"ERROR"}};function kr(){return w().mode==="lambda"?[new Cr({exporter:at()})]:[]}function dt(){if(q!==void 0)return;let e=kr();e.length!==0&&(q=new Ir({processors:e}),ut.setGlobalLoggerProvider(q))}function Dr(e,t,r){let n=lt[e]??lt.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function ft(e,t,r){ut.getLogger(Ar).emit(Dr(e,t,r))}async function mt(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
+ `)}finally{t!==void 0&&clearTimeout(t)}}function Oe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Or(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function R(e,t){return Or()?`\x1B[${e}m${t}\x1B[0m`:t}var _r=5,Fr={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},pt="32",gt="31",ue="2",yt="1";function de(e){return R(Fr[e]??"0",e.padEnd(_r))}function ht(e,t){return`${de("FN")} ${R(yt,`${e} ${t}`.trim())}`}function wt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${R(ue,n)} `:""}${de(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${R(ue,J(r))}`),s}function bt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function St(e){return`${de("AUTH")} ${e}`}function xt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=R(o==="error"?gt:pt,i);return`${de("API")} ${e} ${t} \u2192 ${s} ${R(ue,`${n}ms`)}`}function Et(e,t,r){let n=t?gt:pt,o=R(n,"\u25CF"),i=R(n,t?"error":"success");return`${o} ${R(yt,e)} ${i} ${R(ue,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var Tt=new Rt,$r=new Rt;function S(e){let t=$r.getStore();t&&(t[e]=!0)}var Hr=/^[0-9a-f]{32}$/;function Vr(e){let t=e.replace(/-/g,"").toLowerCase();return Hr.test(t)?t:null}var Jr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},L=new Map;function Pt(e,t,r){let n=L.get(e);n?n[t]=r:L.set(e,{[t]:r})}function T(e,t,r){e.setAttribute(t,g(r))}var Y;function vt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function zr(e){return Math.round(e[0]*1e3+e[1]/1e6)}function It(e){try{process.stdout.write(J(e)+`
4
+ `)}catch{}}var Fe=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=L.get(o),s={...n.attributes};if(i!==void 0){for(let[u,d]of Object.entries(i))typeof d=="string"?s[u]=D(d):typeof d=="object"&&d!==null?s[u]=g(d):s[u]=d;L.delete(o)}let a=Tt.getStore(),l=a?Vr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:vt(n.startTime),endTimeUnixNano:vt(n.endTime),attributes:s,status:{code:Jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:D(n.status.message)}:{}}})}r({code:Br.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t,r){}onEnd(t){L.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
+ `+ht(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=L.get(n)?.properties;N(wt(String(r.level??"info"),String(r.message??""),o,bt(t.startTime)));break}case"auth":N(St(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(xt(String(r.method??""),String(r.host??""),n,zr(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Be=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function qr(){let t=[Oe()?new Le:new jr(new Fe)];return w().mode==="lambda"&&t.push(new Be(new Kr(st()))),t.push(new Ne),t}function Yr(){Y===void 0&&(Y=new Ur({spanProcessors:qr()}),Y.register({propagator:new Mr}),dt())}async function Xr(e=2e3){let t=[mt(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
+ `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var x=Nr.getTracer("@trayai/helix-sdk");function Gr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-i;if(Oe()){N(`
7
+ `+Et(n,s,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?D(a):null})}async function Wo(e,t){let r=e.startMs??Date.now();Yr();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>x.startActiveSpan("App",{kind:Lr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?_e.ERROR:_e.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:_e.ERROR,message:o}),s}finally{i.end()}}))}finally{Gr({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await Xr()}}var kt=1024,C=100*1024*1024,Ct=250,Wr=3600,Qr=Wr*1e3,At=new TextEncoder,Zr=/(^|\/)\.\.(\/|$)/,en=/[?#]/;function tn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=kt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Me(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=kt){if(e.length===0)return;if(Zr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(en.test(e)||tn(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=At.encode(o).length;if(i>Ct)throw c.filesPathInvalid(`Path segment exceeds ${Ct} UTF-8 bytes (got ${i})`)}let n=At.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Dt(e){if(e>C)throw c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got ${e})`,C)}function B(e){let t=e!==void 0?e*1e3:Qr;return new Date(Date.now()+t)}import{join as G}from"path";var rn="files",nn="files-meta",on=1023,sn=1,an=5;function Ot(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,on-t-sn-an)}function me(e){return G(e,".helix",rn)}function X(e){return G(e,".helix",nn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function _t(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Ft="helix-schedule",A=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ni(e){if(typeof e!="object"||e===null)throw new A("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new A("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new A(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!cn(r))throw new A(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new A("`concurrent` must be a boolean");if(typeof o!="function")throw new A("`handler` must be a function");return Object.freeze({kind:Ft,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function oi(e){return typeof e=="object"&&e!==null&&e.kind===Ft&&typeof e.handler=="function"}function cn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as ln}from"@opentelemetry/api";function ye(e,t,r){let n=x.startSpan("log",{kind:ln.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),ft(e,t,r)}function li(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function fi(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import un from"ky";import{context as Ue,trace as dn,SpanKind as Z,SpanStatusCode as Lt}from"@opentelemetry/api";async function he(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(i[P]=a),d&&(i[E]=l),r.deploymentId&&(i[tt]=r.deploymentId),o=Ce(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Ce(n,"dev")}let s;try{s=await rt({proxyUrl:o,credentialHeaders:i,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===se?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.response}async function Nt(e){nt(e.url);let t=w(),{env:r}=b(),n,o={},i={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[E]=l),t.deploymentId&&(i.deploymentId=t.deploymentId),n=Ae(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=Ae(r,"dev")}let s;try{s=await ot({signUrl:n,credentialHeaders:o,body:i,timeoutMs:e.timeout,executionId:t.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.result}var fn=["get","post","put","patch","delete","head","options"],Mt="[stream body omitted]";function Ut(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Mt:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function je(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n){let o=je(t),i="externalApi",s={kind:Z.CLIENT};return x.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),T(a,"request",{url:t,method:e,...r!==void 0?{body:Ut(r)}:{}}),n(a)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Lt.OK}:{code:Lt.ERROR,message:r}),e.end()}var mn=16;async function pn(e,t){let r=e.clone().body;return r?jt(r,t):new Uint8Array(0)}async function jt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=mn)break;continue}i=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Kt(e,t,r){if("kyResponse"in r)try{let n=await pn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",Ut(r.bodyValue))}async function gn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await jt(o,z);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Mt}}}return typeof t=="string"?{body:t}:{}}function Bi(){let e=un.create({});function t(n){return(o,i)=>{let s=Ue.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await gn(f,m.body),ie=p.body;if(a||(a=x.startSpan("externalApi",{kind:Z.CLIENT},s)),a.setAttributes({method:f.method.toUpperCase(),host:je(f.url)}),T(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,S("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Kt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(S("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(S("hasError"),u("error",f.message),f)]}});return a=x.startSpan("externalApi",{kind:Z.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:je(String(o))}),Ue.with(dn.setSpan(Ue.active(),a),()=>{let f=n==="options"?d(o,{...i,method:"OPTIONS"}):d[n](o,i);return f.catch(m=>{S("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(fn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return yn(n)}}}function yn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return Bt(u,a,l.body,async d=>{S("hasAuth");let f=x.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=V({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Kt(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw S("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function i(s,a={}){let l=a.method??"GET";return Bt(l,s,void 0,async u=>{S("hasAuth");let d=x.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Nt({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw S("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as Tn,SpanStatusCode as Jt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var hn=18e4,$t=hn-1e4,wn=2e3;async function Ht(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<$t;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(wn,200*2**i),u=l/2+Math.random()*(l/2),d=$t-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var bn=new Set(["SELECT","WITH","SHOW"]),Sn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function xn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function En(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?D(t):g(t);return c.dbCallFailed(i)}function vn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Rn(e,t){return typeof t!="number"||t<0?{}:bn.has(e)?{rowsRead:t}:Sn.has(e)?{rowsWritten:t}:{}}function Vt(e){async function t(r,n,o){let i=V({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await he(i);if(s>=400)throw En(s,a);return vn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:xn,async execute(r,n){let o=ee(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Ht(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Rn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var Ke=64*1024;function Pn(e){return e.length>Ke?`${e.slice(0,Ke)}...[truncated]`:e}function In(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Cn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Ke?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function An(e,t,r){let n=ee(r),o=Pn(r);return x.startActiveSpan("database",{kind:Tn.CLIENT},async i=>{In(i,e,t,n,o);try{S("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Cn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Jt.OK}),l}catch(s){S("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:Jt.ERROR,message:a}),s}finally{i.end()}})}function kn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Vt(n);function i(s,a){return o.validate(s),An(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Nn}from"unstorage";var zt=1024,$e=250*1024,Dn=new TextEncoder,On=/(^|\/)\.\.(\/|$)/,_n=/[?#]/,Fn=/[\u0000-\u001F\u007F]/;function qt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(On.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(_n.test(e)||Fn.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Dn.encode(e).length;if(t<1||t>zt)throw c.kvKeyInvalid(`Key must be between 1 and ${zt} UTF-8 bytes (got ${t})`)}function Yt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Xt(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>$e)throw c.kvValueTooLarge(`Value exceeds maximum size of ${$e} bytes (got ${r})`,$e)}function te(e){qt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Gt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return te(s),t(s,a)},setItem(s,a,l){return te(s),r(s,a,l)},removeItem(s,a){return te(s),n(s,a)},hasItem(s,a){return te(s),o(s,a)},getKeys(s,a){return s.length>0&&te(s),i(s,a)}}}function be(e){return Nn({driver:Gt(e)})}import{defineDriver as Ln}from"unstorage";function Bn(e){try{return JSON.parse(e)}catch{return e}}var Mn=Ln(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Bn(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Wt(e){return Mn({client:e})}import Kn from"ky";import{z as h}from"zod";async function M(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function Qt(e){return _(e).hosts.api}function Un(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function jn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${Un(t)}/${jn(r)}`}var $n=6e4,He=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(He),h.record(He)])),Hn=h.object({projectId:h.string(),key:h.string(),value:He,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function Vn(){let e=I(),t=v(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[E]=t),o}function Jn(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,Jn(t),g(t))}async function xe(e,t,r={}){try{let n=await Kn(t,{method:e,headers:Vn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:$n}),o=e==="head"?void 0:await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function Zt(e){let t=Qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await xe("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,i);let s=Hn.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await xe("put",re(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&Se(s,a)},async delete(n){let{status:o,body:i}=await xe("delete",re(t,r,n));o!==204&&Se(o,i)},async has(n){let{status:o,body:i}=await xe("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,i)}}}function Ee(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Xt(r),o!==void 0&&Yt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function zn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function er(e){let t=zn(),r=e??Zt(t),n=be(Wt(r));return Ee(n)}import{defineDriver as qn}from"unstorage";var Yn=qn(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl;t.set(n,{value:o,expiresAt:s!==void 0?Date.now()+s*1e3:void 0})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function tr(){return Yn({})}var Ve;function Xn(){return Ve||(Ve=be(tr())),Ve}function rr(){return Ee(Xn())}function Gn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function $s(){return Gn()?er():rr()}import{createHash as Zn}from"crypto";import{mkdir as eo,readFile as ar,readdir as cr,rm as or,unlink as to,writeFile as ir}from"fs/promises";import{dirname as ro}from"path";async function Wn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>C)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got more than ${C})`,C);r.push(i)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Wn(e):Buffer.from(e)}var Qn={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},nr="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return nr;let r=e.slice(t+1).toLowerCase();return Qn[r]??nr}function K(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Je(e){try{let t=await ar(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function sr(e){await eo(ro(e),{recursive:!0})}async function no(e,t){let r=ge(e,t),n;try{n=await cr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function lr(e,t){let r=ge(e,t),n;try{n=await cr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await lr(e,s)):i.isFile()&&o.push(s)}return o}function ur(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await U(t),i=r?.contentType??ve(e),s=Zn("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await sr(l),await ir(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},d=pe(n,e);return await sr(d),await ir(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await Je(e);return t?{data:await ar(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await Je(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await to(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await lr(t,e);return await Promise.all([or(ge(t,e),{recursive:!0,force:!0}),or(_t(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,i=(await no(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Je(a);return l?Re(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}}}}import{createHash as uo}from"crypto";function Te(e){return _(e).hosts.api}function oo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${oo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Pe(e,t,r){return`${$(e,t,r)}/upload`}function dr(e,t,r){return`${$(e,t,r)}/download`}function fr(e,t,r){return`${$(e,t,r)}/signed-url`}function mr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function pr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import qe from"ky";import{z as y}from"zod";var Ye=6e4,gr=y.object({id:y.string(),workspaceId:y.string(),projectId:y.string(),parentFolder:y.string().nullable().optional(),name:y.string(),size:y.number().nullable().optional(),objectType:y.enum(["Folder","File"]),contentType:y.string().nullable().optional(),createdAt:y.string(),updatedAt:y.string()}),io=y.object({signedURL:y.string()}),so=y.object({path:y.array(y.object({id:y.string(),name:y.string()})),elements:y.array(gr)});function Xe(){let e=I(),t=v(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[P]=e),n&&(o[E]=t),o}function yr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function k(e,t){throw c.filesCallFailed(e,yr(t),g(t))}function ao(e,t){return e===400&&yr(t).toLowerCase()==="resource not found"}async function co(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await qe(t,{method:e,headers:Xe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ye}),o=await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function ze(e,t){let r=gr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function hr(e){let t=Te(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&k(o,i),ze(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",mr(t,r,n,o));return i===404||ao(i,s)?null:((i<200||i>=300)&&k(i,s),ze(i,s))},async getById(n){let{status:o,body:i}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&k(o,i),ze(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",pr(t,r,n,o));(i<200||i>=300)&&k(i,s);let a=so.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",g(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await co(a),d;try{d=await qe(Pe(t,r,n),{method:"post",headers:{...Xe(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Ye})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await M(d);(d.status<200||d.status>=300)&&k(d.status,f)},async downloadContent(n){let o;try{o=await qe(dr(t,r,n),{method:"get",headers:Xe(),throwHttpErrors:!1,timeout:Ye})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await M(o);k(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",fr(t,r,n));(o<200||o>=300)&&k(o,i);let s=io.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&k(o,i)}}}function Ge(e){return e.split("/").filter(t=>t.length>0)}function We(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function lo(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Qe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await lo(e,o,i)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function Ze(e,t){if(t.length===0)return;let r=Ge(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var fo=500,mo=8;async function po(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function go(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function yo(e){return uo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Ie(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:yo(t)}}async function wr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function br(e,t){let{elements:r}=await e.listChildren(t,fo);return(await po(r,mo,async o=>{let i=o.objectType==="Folder"?await br(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function Sr(e){let t=go(),r=e??hr(t),n=Te(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Qe(r,i),d=await U(s),f=a?.contentType??ve(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await wr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Ie(i,ie??p,f)},async get(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Ie(i,a)}},async head(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Ie(i,a)},async delete(i){let s=await oe(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await Ze(r,i);if(s===null)return{deleted:0};let a=await br(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Ze(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Ie(i?`${i}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Qe(r,i),d=await r.getByName(a,l)??await wr(r,a,l,s?.contentType);return{url:Pe(n,o,d.id),expiresAt:B(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await oe(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:B(s?.expiresIn)}}}}function et(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){O(n,r);let s=await U(o);return Dt(s.byteLength),e.put(n,s,i)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Me(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let i=Me(n??"");return fe(i,r),e.list(i,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function ho(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Fa(){if(ho())return et(Sr());let e=w().projectRoot;return et(ur(),{maxPathBytes:e?Ot(e):void 0})}export{wo as a,w as b,So as c,xo as d,Eo as e,b as f,vo as g,Tt as h,$r as i,S as j,T as k,Yr as l,Xr as m,x as n,Gr as o,Wo as p,li as q,fi as r,Bi as s,kn as t,$s as u,O as v,W as w,pe as x,Fa as y,Ft as z,A,ni as B,oi as C};
@@ -1 +1 @@
1
- var w=new Set(["production"]),s=new Map,l={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};s.set(l.name,l);var v=["api","broker","ingest","weaver","app","projectHost","dashboard"],k=["auth"],_=["storePrefix","appUrl","cookieName","cookieDomain"];function S(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let r of v)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string`);for(let r of k){let n=e.hosts[r];if(n!==void 0&&(typeof n!="string"||!n))throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string when set`)}for(let r of _)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`EnvironmentProfile.login.${r} must be a non-empty string`)}function R(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&v.every(n=>e.hosts[n]===r.hosts[n])&&k.every(n=>e.hosts[n]===r.hosts[n])&&_.every(n=>e.login[n]===r.login[n])}function L(e){S(e);let r=s.get(e.name);if(r){if(R(r,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let n of s.values())if(n.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${n.name}"`);s.set(e.name,e)}function P(e){return s.has(e)}function K(e){return s.get(e)}function h(e){let r=s.get(e);if(!r)throw new Error(`Unknown environment: ${e}`);return r}function V(){return[...s.keys()]}function M(){return[...s.values()].map(e=>e.exposedName)}function N(e){for(let r of s.values())if(r.exposedName===e)return r.name}var p=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function T(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[p];return}let n=e.trim(),t=N(n);if(t){r[p]=t;return}if(P(n)){r[p]=n;return}throw new Error(`Unknown environment: ${n}`)}function Y(){return globalThis[p]}function J(){return[...s.values()].filter(e=>!w.has(e.name))}function G(){T(void 0),s.clear(),s.set(l.name,{...l,hosts:{...l.hosts},login:{...l.login}})}var c=class e extends Error{detail;constructor(r){super(I(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,t,a){return new e({kind:"broker_error",status:r,message:n,body:t,code:a})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvTtlInvalid(r){return new e({kind:"kv_ttl_invalid",message:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,t){return new e({kind:"kv_call_failed",status:r,message:n,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,t){return new e({kind:"files_call_failed",status:r,message:n,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function Q(e){return e instanceof c}function I(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}import{z as u}from"zod";var E="x-helix-destination-url",x="x-helix-authentication-id",D="x-helix-deployment-id",b="x-execution-id",U="x-helix-broker-error",re="route_not_found",$=new Set([E,x,D,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",b]);function A(e){let r=e.toLowerCase();return $.has(r)||r.startsWith("x-tray-internal-")}var q=u.object({error:u.object({code:u.string(),message:u.string(),issues:u.array(u.unknown()).optional()})});function ne(e,r){let n=`${h(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${n}/dev`:n}function O(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function te(e){let r=new URL(e.url);if(r.protocol!=="https:")throw c.unsupportedScheme(r.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[o,i]of e.query.entries())r.searchParams.append(o,i);else for(let[o,i]of Object.entries(e.query))for(let m of Array.isArray(i)?i:[i])r.searchParams.append(o,m);let n;e.headers===void 0?n=[]:e.headers instanceof Headers?n=Array.from(e.headers.entries()):Array.isArray(e.headers)?n=e.headers:n=Object.entries(e.headers);let t=n.filter(([o])=>!A(o)),a=e.body!==void 0&&e.body!==null,d,f,g=!1;return a&&(O(e.body)?(d=e.body,g=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([i])=>i.toLowerCase()==="content-type")||(f="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:t,body:d,isStreamBody:g,defaultContentType:f}}var C=6e4;function j(e){return e.includes("json")}function B(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function H(e,r){if(e.byteLength===0)return;let n=r.toLowerCase();if(j(n)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return B(n)?new TextDecoder("utf-8").decode(e):e}function F(e){let r={};for(let[n,t]of e.entries())r[n.toLowerCase()]=t;return r}async function ie(e){let{request:r}=e,n=new Headers;for(let[o,i]of r.headers)n.append(o,i);r.defaultContentType&&!n.has("content-type")&&n.set("content-type",r.defaultContentType),n.set(E,r.destinationUrl),n.set(x,r.authenticationId);for(let[o,i]of Object.entries(e.credentialHeaders))n.set(o,i);e.executionId&&n.set(b,e.executionId);let t={method:r.method,headers:n,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??C)};r.body!==void 0&&(t.body=r.body,r.isStreamBody&&(t.duplex="half"));let a=await fetch(e.proxyUrl,t),d=a.headers.get(U);if(d!==null){let o=await a.text(),i=o,m=o||d;try{i=JSON.parse(o);let y=q.safeParse(i);y.success&&(m=y.data.error.message)}catch{}return{kind:"brokerError",status:a.status,code:d,message:m,body:i}}let f=new Uint8Array(await a.arrayBuffer()),g=a.headers.get("content-type")??"";return{kind:"upstream",response:{status:a.status,headers:F(a.headers),body:H(f,g)}}}export{L as a,P as b,K as c,h as d,V as e,M as f,N as g,T as h,Y as i,J as j,G as k,c as l,Q as m,D as n,re as o,ne as p,te as q,C as r,ie as s};
1
+ var R=new Set(["production"]),a=new Map,g={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};a.set(g.name,g);var E=["api","broker","ingest","weaver","app","projectHost","dashboard"],x=["auth"],b=["storePrefix","appUrl","cookieName","cookieDomain"];function P(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let r of E)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string`);for(let r of x){let n=e.hosts[r];if(n!==void 0&&(typeof n!="string"||!n))throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string when set`)}for(let r of b)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`EnvironmentProfile.login.${r} must be a non-empty string`)}function I(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&E.every(n=>e.hosts[n]===r.hosts[n])&&x.every(n=>e.hosts[n]===r.hosts[n])&&b.every(n=>e.login[n]===r.login[n])}function V(e){P(e);let r=a.get(e.name);if(r){if(I(r,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let n of a.values())if(n.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${n.name}"`);a.set(e.name,e)}function N(e){return a.has(e)}function G(e){return a.get(e)}function y(e){let r=a.get(e);if(!r)throw new Error(`Unknown environment: ${e}`);return r}function J(){return[...a.keys()]}function Y(){return[...a.values()].map(e=>e.exposedName)}function T(e){for(let r of a.values())if(r.exposedName===e)return r.name}var p=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function D(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[p];return}let n=e.trim(),t=T(n);if(t){r[p]=t;return}if(N(n)){r[p]=n;return}throw new Error(`Unknown environment: ${n}`)}function z(){return globalThis[p]}function X(){return[...a.values()].filter(e=>!R.has(e.name))}function Q(){D(void 0),a.clear(),a.set(g.name,{...g,hosts:{...g.hosts},login:{...g.login}})}var u=class e extends Error{detail;constructor(r){super(U(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,t,o){return new e({kind:"broker_error",status:r,message:n,body:t,code:o})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvTtlInvalid(r){return new e({kind:"kv_ttl_invalid",message:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,t){return new e({kind:"kv_call_failed",status:r,message:n,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,t){return new e({kind:"files_call_failed",status:r,message:n,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function Z(e){return e instanceof u}function U(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}import{z as f}from"zod";var w="x-helix-destination-url",S="x-helix-authentication-id",O="x-helix-deployment-id",v="x-execution-id",A="x-helix-broker-error",oe="route_not_found",$=new Set([w,S,O,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",v]);function q(e){let r=e.toLowerCase();return $.has(r)||r.startsWith("x-tray-internal-")}var _=f.object({error:f.object({code:f.string(),message:f.string(),issues:f.array(f.unknown()).optional()})});function ie(e,r){let n=`${y(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${n}/dev`:n}function H(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function se(e){let r=new URL(e.url);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[s,i]of e.query.entries())r.searchParams.append(s,i);else for(let[s,i]of Object.entries(e.query))for(let m of Array.isArray(i)?i:[i])r.searchParams.append(s,m);let n;e.headers===void 0?n=[]:e.headers instanceof Headers?n=Array.from(e.headers.entries()):Array.isArray(e.headers)?n=e.headers:n=Object.entries(e.headers);let t=n.filter(([s])=>!q(s)),o=e.body!==void 0&&e.body!==null,d,l,c=!1;return o&&(H(e.body)?(d=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([i])=>i.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:t,body:d,isStreamBody:c,defaultContentType:l}}var B=6e4;function C(e){return e.includes("json")}function j(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function L(e,r){if(e.byteLength===0)return;let n=r.toLowerCase();if(C(n)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return j(n)?new TextDecoder("utf-8").decode(e):e}function F(e){let r={};for(let[n,t]of e.entries())r[n.toLowerCase()]=t;return r}async function ae(e){let{request:r}=e,n=new Headers;for(let[s,i]of r.headers)n.append(s,i);r.defaultContentType&&!n.has("content-type")&&n.set("content-type",r.defaultContentType),n.set(w,r.destinationUrl),n.set(S,r.authenticationId);for(let[s,i]of Object.entries(e.credentialHeaders))n.set(s,i);e.executionId&&n.set(v,e.executionId);let t={method:r.method,headers:n,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??B)};r.body!==void 0&&(t.body=r.body,r.isStreamBody&&(t.duplex="half"));let o=await fetch(e.proxyUrl,t),d=o.headers.get(A);if(d!==null){let s=await o.text(),i=s,m=s||d;try{i=JSON.parse(s);let h=_.safeParse(i);h.success&&(m=h.data.error.message)}catch{}return{kind:"brokerError",status:o.status,code:d,message:m,body:i}}let l=new Uint8Array(await o.arrayBuffer()),c=o.headers.get("content-type")??"";return{kind:"upstream",response:{status:o.status,headers:F(o.headers),body:L(l,c)}}}import{z as k}from"zod";var M=3e4;function fe(e){let r=new URL(e);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""))}function me(e,r){let n=`${y(e).hosts.api}/private/v1/helix/broker/s3/sign`;return r==="dev"?`${n}/dev`:n}var K=k.object({url:k.string(),method:k.string(),expiresAt:k.string()});async function pe(e){let r=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))r.set(l,c);e.executionId&&r.set(v,e.executionId);let n=await fetch(e.signUrl,{method:"POST",headers:r,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??M)}),t=await n.text(),o=t;try{o=JSON.parse(t)}catch{}if(n.ok){let l=K.safeParse(o);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:n.status,message:"malformed s3-sign response from credential broker",body:o}}let d=_.safeParse(o);return d.success?{kind:"brokerError",status:n.status,code:d.data.error.code,message:d.data.error.message,body:o}:{kind:"brokerError",status:n.status,message:t||`s3-sign request failed with status ${n.status}`,body:o}}export{V as a,N as b,G as c,y as d,J as e,Y as f,T as g,D as h,z as i,X as j,Q as k,u as l,Z as m,O as n,oe as o,ie as p,se as q,B as r,ae as s,fe as t,me as u,pe as v};
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
- import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DCCVrmZ3.js';
4
- export { b as DbCallParameters, c as DbClient, d as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, e as ScheduleContext, f as ScheduleHandler, g as ScheduleTrigger, h as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DCCVrmZ3.js';
3
+ import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-Dspz1laT.js';
4
+ export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-Dspz1laT.js';
5
5
  import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-vY_-Reh3.js';
6
6
  export { C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, e as resolveConfigOverride, w as workspaceIdSchema } from './sdk-config-vY_-Reh3.js';
7
7
  export { a as ENVIRONMENT_VALUES, E as Environment, e as environmentSchema } from './env-schema-DkgTG5b0.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{A as we,B as ke,C as Se,b as R,h as M,i as F,j as Z,k as E,l as K,m as B,n as V,o as z,p as Ce,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as Ee}from"./chunk-BVNQVFSR.js";import{a as G,b as ve}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-Q6GJ4HQZ.js";import{randomUUID as Le}from"crypto";import{SpanStatusCode as ae,SpanKind as Oe}from"@opentelemetry/api";import{defineEventHandler as je,getMethod as De,getRequestURL as He,getHeaders as ce,getHeader as de}from"h3";import{readBody as xe,getQuery as Ie,getRouterParams as _e}from"h3";async function ne(e,t){let r=await be(e),n=Ie(e),o=_e(e)??{},i={...n,...r,...o};return t?Te(i,t):i}async function be(e){try{let t=await xe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Te(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function oe(e){return t=>{e.node.res.statusCode=t}}function ie(){return(e,t)=>{throw new w(e,t)}}function se(e,t){let{statusCode:r,message:n}=Re(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Re(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Fe=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Pe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Fe.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Pe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ae(e,t){let{inputSchema:r,outputSchema:n}=Me(t),o=e;return je(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ze(d,i),p=Date.now(),v=new Date().toISOString(),h=De(i),l=He(i).pathname,u=Q(),y=J(),S=`${h} ${l}`;K();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return We(()=>F.run(N,()=>M.run(s,async()=>{let x=await Ne(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ye=Be(i,x.input,u,y,h,l,s,f,a);return Ue(o,ye,n,i,y,s,f,{method:h,path:l,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:S,startedAt:v,startMs:p,userId:a,flags:N})})}async function We(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await B()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Ke(e,r);if(n)return{ok:!1,response:n};throw r}}async function Ue(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:Oe.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ce(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let p=!1,v=null,h,l;try{let u=await G.run(t,()=>e(t));if(h=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let y=r.safeParse(u);if(!y.success){let S=Object.keys(y.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:S,executionId:i}),g.outputValidationFailed(S)}l=y.data}else l=u}catch(u){p=!0,v=u instanceof Error?u.message:String(u),Z("hasError"),l=$e(u,n,o,i)}finally{qe(a,n,{errored:p,errorMessage:v,handlerResult:h,response:l})}return{response:l,errored:p,errorMessage:v}})}function $e(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return se(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function qe(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=F.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ae.ERROR:ae.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Me(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:de(t,"x-tray-execution-id"))??Le(),o=(r?e.userId:de(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Ke(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 Be(e,t,r,n,o,i,d,s,a){return{input:t,method:o,path:i,headers:P(ce(e)),http:Y(),db:f=>ee(f),kv:()=>te(),files:()=>re(),log:n,config:r,status:oe(e),error:ie(),state:{},request:e,executionId:d,deploymentId:s,userId:a,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ve(e){return e}import{resolve as m}from"path";import{existsSync as _,realpathSync as ue}from"fs";import{loadConfig as Je}from"c12";import{z as c}from"zod";import{z as ze}from"zod";var Ge=["production"],I=ze.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Qe=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:I.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),fe=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:I,authentications:c.record(c.string()),config:c.record(c.unknown())}),Xe=c.discriminatedUnion("kind",[fe.extend({kind:c.literal("provisioned"),projectId:L}),fe.extend({kind:c.literal("unprovisioned")})]),le=["helix","tray"],pe=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function C(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=C(t?.configFile);if(r!==void 0){let n=m(e,r);return _(n)?n:void 0}for(let n of le)for(let o of pe){let i=m(e,`${n}.config.${o}`);if(_(i))return i}}function Ye(e){for(let t of le)if(pe.some(r=>_(m(e,`${t}.config.${r}`))))return t;return"helix"}function et(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=C(t?.configFile);return{name:Ye(e),cwd:e,...r!==void 0?{configFile:et(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function H(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Qe.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=C(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!_(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Je(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=ue(o);if(ue(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return H(i.config,d)}var ge="WORKSPACE_ID_REQUIRED";function tt(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ge});return e.workspaceId}import{existsSync as rt,watch as nt,writeSync as ot}from"fs";import{basename as it,dirname as st,join as at,resolve as T}from"path";import{watchConfig as dt}from"c12";function ct(e,t){let r=e instanceof Error?e.message:String(e);ot(2,`[helix-watch] ${t.phase} error: ${r}
1
+ import{A as we,B as ke,C as Se,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ce,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as Ee}from"./chunk-2XHMIUW3.js";import{a as G,b as ve}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-D5GPRK2D.js";import{randomUUID as Le}from"crypto";import{SpanStatusCode as ae,SpanKind as Oe}from"@opentelemetry/api";import{defineEventHandler as je,getMethod as De,getRequestURL as He,getHeaders as ce,getHeader as de}from"h3";import{readBody as xe,getQuery as Ie,getRouterParams as _e}from"h3";async function ne(e,t){let r=await be(e),n=Ie(e),o=_e(e)??{},i={...n,...r,...o};return t?Te(i,t):i}async function be(e){try{let t=await xe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Te(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function oe(e){return t=>{e.node.res.statusCode=t}}function ie(){return(e,t)=>{throw new w(e,t)}}function se(e,t){let{statusCode:r,message:n}=Re(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Re(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Fe=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Pe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Fe.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Pe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ae(e,t){let{inputSchema:r,outputSchema:n}=Me(t),o=e;return je(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ze(d,i),p=Date.now(),v=new Date().toISOString(),h=De(i),l=He(i).pathname,u=Q(),y=J(),S=`${h} ${l}`;B();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return We(()=>F.run(N,()=>M.run(s,async()=>{let x=await Ne(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ye=Ke(i,x.input,u,y,h,l,s,f,a);return Ue(o,ye,n,i,y,s,f,{method:h,path:l,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:S,startedAt:v,startMs:p,userId:a,flags:N})})}async function We(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await K()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Be(e,r);if(n)return{ok:!1,response:n};throw r}}async function Ue(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:Oe.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ce(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let p=!1,v=null,h,l;try{let u=await G.run(t,()=>e(t));if(h=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let y=r.safeParse(u);if(!y.success){let S=Object.keys(y.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:S,executionId:i}),g.outputValidationFailed(S)}l=y.data}else l=u}catch(u){p=!0,v=u instanceof Error?u.message:String(u),Z("hasError"),l=$e(u,n,o,i)}finally{qe(a,n,{errored:p,errorMessage:v,handlerResult:h,response:l})}return{response:l,errored:p,errorMessage:v}})}function $e(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return se(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function qe(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=F.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ae.ERROR:ae.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Me(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:de(t,"x-tray-execution-id"))??Le(),o=(r?e.userId:de(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Be(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Ke(e,t,r,n,o,i,d,s,a){return{input:t,method:o,path:i,headers:P(ce(e)),http:Y(),db:f=>ee(f),kv:()=>te(),files:()=>re(),log:n,config:r,status:oe(e),error:ie(),state:{},request:e,executionId:d,deploymentId:s,userId:a,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ve(e){return e}import{resolve as m}from"path";import{existsSync as _,realpathSync as ue}from"fs";import{loadConfig as Je}from"c12";import{z as c}from"zod";import{z as ze}from"zod";var Ge=["production"],I=ze.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Qe=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:I.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),fe=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:I,authentications:c.record(c.string()),config:c.record(c.unknown())}),Xe=c.discriminatedUnion("kind",[fe.extend({kind:c.literal("provisioned"),projectId:L}),fe.extend({kind:c.literal("unprovisioned")})]),le=["helix","tray"],pe=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function C(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=C(t?.configFile);if(r!==void 0){let n=m(e,r);return _(n)?n:void 0}for(let n of le)for(let o of pe){let i=m(e,`${n}.config.${o}`);if(_(i))return i}}function Ye(e){for(let t of le)if(pe.some(r=>_(m(e,`${t}.config.${r}`))))return t;return"helix"}function et(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=C(t?.configFile);return{name:Ye(e),cwd:e,...r!==void 0?{configFile:et(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function H(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Qe.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=C(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!_(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Je(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=ue(o);if(ue(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return H(i.config,d)}var ge="WORKSPACE_ID_REQUIRED";function tt(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ge});return e.workspaceId}import{existsSync as rt,watch as nt,writeSync as ot}from"fs";import{basename as it,dirname as st,join as at,resolve as T}from"path";import{watchConfig as dt}from"c12";function ct(e,t){let r=e instanceof Error?e.message:String(e);ot(2,`[helix-watch] ${t.phase} error: ${r}
2
2
  `)}function A(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ut=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,me=new Set;function he(e,t){return b(e,{configFile:t})!==void 0}async function ft(e,t,r){if(he(e.cwd,t))try{return{current:await k(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:A(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?T(e.cwd,t):T(e.cwd);me.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${T(e.cwd,t)} not found; tray running with default config
3
3
  `:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
4
4
  `),me.add(n))}return{current:A(),initialLoadSucceeded:!1}}var W=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=dt({...D(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=H(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,i)=>{n.once("ready",o),n.once("error",i)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?T(this.cwd,this.configFile):void 0,r=t!==void 0?st(t):this.cwd;try{this.directoryWatcher=nt(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let i=o.toString();if(t!==void 0){if(i!==it(t))return}else if(!ut.test(i))return;rt(at(r,i))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await k(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function lt(e){let t=e.onError??ct,r=new Set,n=C(e.configFile),o=await ft(e,n,t),i=o.current;function d(a){i=a;for(let f of[...r])try{f(a)}catch(p){t(p,{phase:"reload"})}}let s=new W(e.cwd,n,t,d);return e.watch&&s.start(o.initialLoadSucceeded),{get(){return i},async reload(){if(!he(e.cwd,n)){let a=A();return d(a),a}try{let a=await k(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),i}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await s.stop()},ready(){return s.watcherReady()}}}export{Ge as ENVIRONMENT_VALUES,j as HELIX_CONFIG_ENV,Ee as SCHEDULE_DEFINITION_KIND,we as ScheduleConfigError,ge as WORKSPACE_ID_REQUIRED_CODE,lt as createConfigService,Ve as defineConfig,Ae as defineFunction,ke as defineSchedule,I as environmentSchema,ve as getContext,R as getSdkConfig,Se as isScheduleDefinition,k as loadConfig,Xe as loadedTrayConfigSchema,L as projectIdSchema,tt as requireWorkspaceId,b as resolveConfigFile,C as resolveConfigOverride,Ce as runWithinAppSpan,O as workspaceIdSchema};
@@ -1 +1 @@
1
- import{C as N,a as H,b as m,c as L,d as T,e as G,f as J,g as U,h,i as p,j as g,k as E,l as S,m as x,n as y,o as A,q as w,r as I,s as C,t as v,u as D,v as oe,w as ne,x as se,y as F}from"../chunk-BVNQVFSR.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as B,c as q,d as z,e as Q,f as W,g as X,h as Y,i as Z,j as ee,k as te,m as re}from"../chunk-Q6GJ4HQZ.js";import{randomUUID as ie}from"crypto";import{SpanStatusCode as P,SpanKind as ae}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function le(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new t("`isManual` must be a boolean");if(!N(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let k=O("scheduledAt",e.scheduledAt),M=O("firedAt",e.firedAt),d=m(),a=d.executionId??ie(),l=d.deploymentId??null,R=Date.now(),j=new Date().toISOString(),$=I(),K=w();S();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ae.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let _={type:"schedule",scheduledAt:k,firedAt:M,isManual:e.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:_};E(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?P.ERROR:P.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:j,startMs:R,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function O(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{L as CONFIG_BRIDGE_CHANNEL,T as DEV_TOKEN_BRIDGE_CHANNEL,t as ScheduleInvocationError,oe as assertValidPath,U as clearActiveConfig,ne as contentFilePath,J as getActiveConfig,ee as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,B as isKnownEnvironment,re as isSdkError,Q as listEnvironmentNames,W as listExposedEnvNames,se as metaFilePath,X as parseExposedEnvironment,V as registerEnvironmentProfile,z as requireEnvironmentProfile,te as resetEnvironmentRegistryForTests,Z as resolveForcedEnvironment,le as runScheduledFunction,G as setActiveConfig,Y as setForcedEnvironment,H as setSdkConfig};
1
+ import{C as N,a as H,b as m,c as L,d as T,e as G,f as J,g as U,h,i as p,j as g,k as E,l as S,m as x,n as y,o as A,q as w,r as I,s as C,t as v,u as D,v as oe,w as ne,x as se,y as F}from"../chunk-2XHMIUW3.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as B,c as q,d as z,e as Q,f as W,g as X,h as Y,i as Z,j as ee,k as te,m as re}from"../chunk-D5GPRK2D.js";import{randomUUID as ie}from"crypto";import{SpanStatusCode as P,SpanKind as ae}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function le(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new t("`isManual` must be a boolean");if(!N(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let k=O("scheduledAt",e.scheduledAt),M=O("firedAt",e.firedAt),d=m(),a=d.executionId??ie(),l=d.deploymentId??null,R=Date.now(),j=new Date().toISOString(),$=I(),K=w();S();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ae.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let _={type:"schedule",scheduledAt:k,firedAt:M,isManual:e.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:_};E(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?P.ERROR:P.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:j,startMs:R,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function O(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{L as CONFIG_BRIDGE_CHANNEL,T as DEV_TOKEN_BRIDGE_CHANNEL,t as ScheduleInvocationError,oe as assertValidPath,U as clearActiveConfig,ne as contentFilePath,J as getActiveConfig,ee as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,B as isKnownEnvironment,re as isSdkError,Q as listEnvironmentNames,W as listExposedEnvNames,se as metaFilePath,X as parseExposedEnvironment,V as registerEnvironmentProfile,z as requireEnvironmentProfile,te as resetEnvironmentRegistryForTests,Z as resolveForcedEnvironment,le as runScheduledFunction,G as setActiveConfig,Y as setForcedEnvironment,H as setSdkConfig};
@@ -1,4 +1,4 @@
1
- import { P as PlatformContext } from '../types-DCCVrmZ3.js';
1
+ import { P as PlatformContext } from '../types-Dspz1laT.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
@@ -136,6 +136,27 @@ interface BrokerCallResult {
136
136
  body?: unknown;
137
137
  headers: Record<string, string | string[]>;
138
138
  }
139
+ interface S3SignOptions {
140
+ /** HTTP method the URL will be used with: GET (download, the default),
141
+ PUT (upload), POST (multipart initiation/completion), DELETE, HEAD. */
142
+ method?: "GET" | "PUT" | "POST" | "DELETE" | "HEAD";
143
+ /** Seconds until the URL expires. Default 900 (15 minutes); max 604800
144
+ (one week, AWS-imposed). */
145
+ expiresIn?: number;
146
+ /** Per-call timeout in ms (default 30s — signing is broker-local, no
147
+ upstream hop). */
148
+ timeout?: number;
149
+ }
150
+ interface S3SignResult {
151
+ /** The presigned S3 URL — use it directly against S3 (no broker, no auth
152
+ headers needed). It embeds a live capability on the authentication's
153
+ AWS credential: treat it like a secret until it expires. */
154
+ url: string;
155
+ /** The HTTP method the URL was signed for — using any other method fails. */
156
+ method: string;
157
+ /** ISO-8601 instant after which S3 refuses the URL. */
158
+ expiresAt: string;
159
+ }
139
160
  interface BrokerAuthedClient {
140
161
  get(url: string, options?: BrokerCallOptions): Promise<BrokerCallResult>;
141
162
  post(url: string, options?: BrokerCallOptions): Promise<BrokerCallResult>;
@@ -144,6 +165,12 @@ interface BrokerAuthedClient {
144
165
  delete(url: string, options?: BrokerCallOptions): Promise<BrokerCallResult>;
145
166
  head(url: string, options?: BrokerCallOptions): Promise<BrokerCallResult>;
146
167
  options(url: string, options?: BrokerCallOptions): Promise<BrokerCallResult>;
168
+ /** Presign an S3 object URL with this authentication's AWS credentials
169
+ (AWS/S3 authentications only). The returned URL is used against S3
170
+ directly, so the broker's 16 MB body cap does not apply. `url` is the
171
+ full https object URL, path-style or virtual-hosted
172
+ (e.g. https://my-bucket.s3.eu-west-1.amazonaws.com/path/key.bin). */
173
+ s3Sign(url: string, options?: S3SignOptions): Promise<S3SignResult>;
147
174
  }
148
175
  interface HttpClient extends KyInstance {
149
176
  authed(alias: string): BrokerAuthedClient;
@@ -270,4 +297,4 @@ interface ScheduleDefinition {
270
297
  handler: ScheduleHandler;
271
298
  }
272
299
 
273
- export type { DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, DbCallParameters as b, DbClient as c, FileSystemClient as d, ScheduleContext as e, ScheduleHandler as f, ScheduleTrigger as g, SqlBuilder as h };
300
+ export type { BrokerAuthedClient as B, DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, BrokerCallOptions as b, BrokerCallResult as c, DbCallParameters as d, DbClient as e, FileSystemClient as f, S3SignOptions as g, S3SignResult as h, ScheduleContext as i, ScheduleHandler as j, ScheduleTrigger as k, SqlBuilder as l };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.101.0",
3
+ "version": "0.103.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -1,7 +0,0 @@
1
- import{d as D,l as c,n as Qe,o as Ze,p as Te,q as V,s as et}from"./chunk-Q6GJ4HQZ.js";var R="X-Helix-Project-Execution-Token",F="X-Tray-Token",yr={mode:"dev",deploymentId:null},Pe={...yr},O={};function po(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(O.internalJwt=t),"helixExecutionJwt"in e&&(O.helixExecutionJwt=r),"devToken"in e&&(O.devToken=n),Pe={...Pe,...o}}function w(){return Pe}function _(){return O.internalJwt}function T(){return O.helixExecutionJwt}function tt(){return O.devToken}var yo="tray-config-bridge",ho="tray-dev-token-bridge",oe=null;function wo(e){oe=e}function b(){if(!oe)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return oe}function bo(){oe=null}import{AsyncLocalStorage as xt}from"async_hooks";import{trace as kr,SpanKind as Dr,SpanStatusCode as Ae}from"@opentelemetry/api";import{ExportResultCode as Or,W3CTraceContextPropagator as Fr}from"@opentelemetry/core";import{NodeTracerProvider as _r,SimpleSpanProcessor as Lr,BatchSpanProcessor as Nr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as hr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as wr}from"@opentelemetry/exporter-logs-otlp-proto";function Ce(e){return D(e).hosts.ingest}function br(){return T()??""}function rt(){return{[R]:br()}}function nt(){let e=Ce(b().env);return new hr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(rt())})}function ot(){let e=Ce(b().env);return new wr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(rt())})}import{logs as at,SeverityNumber as ie}from"@opentelemetry/api-logs";import{LoggerProvider as Er,BatchLogRecordProcessor as vr}from"@opentelemetry/sdk-logs";function z(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Sr(e){return new TextEncoder().encode(e).length}var it="\u2026[truncated]",xr=Sr(it),J=4096;function A(e,t=J){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-xr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+it}function y(e,t=J){return A(z(e),t)}var Rr="@trayai/helix-sdk",q,st={debug:{number:ie.DEBUG,text:"DEBUG"},info:{number:ie.INFO,text:"INFO"},warn:{number:ie.WARN,text:"WARN"},error:{number:ie.ERROR,text:"ERROR"}};function Tr(){return w().mode==="lambda"?[new vr({exporter:ot()})]:[]}function ct(){if(q!==void 0)return;let e=Tr();e.length!==0&&(q=new Er({processors:e}),at.setGlobalLoggerProvider(q))}function Pr(e,t,r){let n=st[e]??st.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":y(r)}}:{}}}function lt(e,t,r){at.getLogger(Rr).emit(Pr(e,t,r))}async function ut(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
- `)}finally{t!==void 0&&clearTimeout(t)}}function Ie(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Cr(){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 S(e,t){return Cr()?`\x1B[${e}m${t}\x1B[0m`:t}var Ir=5,Ar={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},dt="32",ft="31",se="2",mt="1";function ae(e){return S(Ar[e]??"0",e.padEnd(Ir))}function pt(e,t){return`${ae("FN")} ${S(mt,`${e} ${t}`.trim())}`}function gt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${S(se,n)} `:""}${ae(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${S(se,z(r))}`),s}function yt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function ht(e){return`${ae("AUTH")} ${e}`}function wt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=S(o==="error"?ft:dt,i);return`${ae("API")} ${e} ${t} \u2192 ${s} ${S(se,`${n}ms`)}`}function bt(e,t,r){let n=t?ft:dt,o=S(n,"\u25CF"),i=S(n,t?"error":"success");return`${o} ${S(mt,e)} ${i} ${S(se,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Et=new xt,Mr=new xt;function x(e){let t=Mr.getStore();t&&(t[e]=!0)}var Br=/^[0-9a-f]{32}$/;function Ur(e){let t=e.replace(/-/g,"").toLowerCase();return Br.test(t)?t:null}var jr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},N=new Map;function vt(e,t,r){let n=N.get(e);n?n[t]=r:N.set(e,{[t]:r})}function v(e,t,r){e.setAttribute(t,y(r))}var Y;function St(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function Kr(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Rt(e){try{process.stdout.write(z(e)+`
4
- `)}catch{}}var ke=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=N.get(o),s={...n.attributes};if(i!==void 0){for(let[u,f]of Object.entries(i))typeof f=="string"?s[u]=A(f):typeof f=="object"&&f!==null?s[u]=y(f):s[u]=f;N.delete(o)}let a=Et.getStore(),l=a?Ur(a):null;Rt({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:St(n.startTime),endTimeUnixNano:St(n.endTime),attributes:s,status:{code:jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:A(n.status.message)}:{}}})}r({code:Or.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},De=class{onStart(t,r){}onEnd(t){N.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Oe=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
- `+pt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=N.get(n)?.properties;L(gt(String(r.level??"info"),String(r.message??""),o,yt(t.startTime)));break}case"auth":L(ht(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(wt(String(r.method??""),String(r.host??""),n,Kr(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Fe=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 $r(){let t=[Ie()?new Oe:new Lr(new ke)];return w().mode==="lambda"&&t.push(new Fe(new Nr(nt()))),t.push(new De),t}function Hr(){Y===void 0&&(Y=new _r({spanProcessors:$r()}),Y.register({propagator:new Fr}),ct())}async function Vr(e=2e3){let t=[ut(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
- `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var E=kr.getTracer("@trayai/helix-sdk");function zr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let f=new Date().toISOString(),d=Date.now()-i;if(Ie()){L(`
7
- `+bt(n,s,d));return}Rt({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:f,durationMs:d,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?A(a):null})}async function qo(e,t){let r=e.startMs??Date.now();Hr();let n=!1,o=null;try{return await Et.run(e.executionId,()=>E.startActiveSpan("App",{kind:Dr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ae.ERROR:Ae.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ae.ERROR,message:o}),s}finally{i.end()}}))}finally{zr({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 Vr()}}var Ct=1024,P=100*1024*1024,Tt=250,Jr=3600,qr=Jr*1e3,Pt=new TextEncoder,Yr=/(^|\/)\.\.(\/|$)/,Xr=/[?#]/;function Gr(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function k(e,t=Ct){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");ce(e,t)}function _e(e){return e.endsWith("/")?e.slice(0,-1):e}function ce(e,t=Ct){if(e.length===0)return;if(Yr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(Xr.test(e)||Gr(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=Pt.encode(o).length;if(i>Tt)throw c.filesPathInvalid(`Path segment exceeds ${Tt} UTF-8 bytes (got ${i})`)}let n=Pt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function It(e){if(e>P)throw c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got ${e})`,P)}function M(e){let t=e!==void 0?e*1e3:qr;return new Date(Date.now()+t)}import{join as G}from"path";var Wr="files",Qr="files-meta",Zr=1023,en=1,tn=5;function At(e){let t=Math.max(Buffer.byteLength(le(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,Zr-t-en-tn)}function le(e){return G(e,".helix",Wr)}function X(e){return G(e,".helix",Qr)}function W(e,t){return G(le(e),...t.split("/"))}function ue(e,t){return G(X(e),...t.split("/"))+".json"}function de(e,t){return t.length===0?le(e):W(e,t)}function kt(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Dt="helix-schedule",C=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Zo(e){if(typeof e!="object"||e===null)throw new C("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new C("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new C(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!rn(r))throw new C(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new C("`concurrent` must be a boolean");if(typeof o!="function")throw new C("`handler` must be a function");return Object.freeze({kind:Dt,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function ei(e){return typeof e=="object"&&e!==null&&e.kind===Dt&&typeof e.handler=="function"}function rn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as nn}from"@opentelemetry/api";function fe(e,t,r){let n=E.startSpan("log",{kind:nn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&vt(n.spanContext().spanId,"properties",r),n.end(),lt(e,t,r)}function ii(){return{info:(e,t)=>fe("info",e,t),warn:(e,t)=>fe("warn",e,t),error:(e,t)=>fe("error",e,t),debug:(e,t)=>fe("debug",e,t)}}function ci(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import on from"ky";import{context as Le,trace as sn,SpanKind as pe,SpanStatusCode as Ot}from"@opentelemetry/api";async function me(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=_(),l=T(),u=!!(a&&a.trim().length>0),f=!!(l&&l.trim().length>0);if(!u&&!f)throw c.missingExecutionCredentials();u&&(i[F]=a),f&&(i[R]=l),r.deploymentId&&(i[Qe]=r.deploymentId),o=Te(n,"runtime")}else{let a=tt();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Te(n,"dev")}let s;try{s=await et({proxyUrl:o,credentialHeaders:i,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===Ze?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,y(s.body),s.code)}return s.response}var an=["get","post","put","patch","delete","head","options"],Ft="[stream body omitted]";function _t(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Ft:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Ne(e){try{return new URL(e).hostname}catch{return e}}function cn(e,t,r,n){let o=Ne(t),i="externalApi",s={kind:pe.CLIENT};return E.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),v(a,"request",{url:t,method:e,...r!==void 0?{body:_t(r)}:{}}),n(a)))}function Me(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ot.OK}:{code:Ot.ERROR,message:r}),e.end()}var ln=16;async function un(e,t){let r=e.clone().body;return r?Lt(r,t):new Uint8Array(0)}async function Lt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=ln)break;continue}i=0;let f=t+1-o;if(u.byteLength>=f){n.push(u.slice(0,f)),o+=f;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Nt(e,t,r){if("kyResponse"in r)try{let n=await un(r.kyResponse,J),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}v(e,"response",i)}catch{v(e,"response",{status:t})}else v(e,"response",_t(r.bodyValue))}async function dn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await Lt(o,J);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Ft}}}return typeof t=="string"?{body:t}:{}}function Ti(){let e=on.create({});function t(n){return(o,i)=>{let s=Le.active(),a,l=!1,u=(d,m)=>{a&&!l&&(l=!0,Me(a,d,m))},f=e.extend({hooks:{beforeRequest:[async(d,m)=>{let p=await dn(d,m.body),ne=p.body;if(a||(a=E.startSpan("externalApi",{kind:pe.CLIENT},s)),a.setAttributes({method:d.method.toUpperCase(),host:Ne(d.url)}),v(a,"request",{url:d.url,method:d.method.toUpperCase(),...ne!==void 0?{body:ne}:{}}),l=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[d=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(d,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Nt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[d=>(x("hasError"),u("error",d.message),d)]}});return a=E.startSpan("externalApi",{kind:pe.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:Ne(String(o))}),Le.with(sn.setSpan(Le.active(),a),()=>{let d=n==="options"?f(o,{...i,method:"OPTIONS"}):f[n](o,i);return d.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),d})}}let r=Object.fromEntries(an.map(n=>[n,t(n)]));return{...e,...r,authed(n){return fn(n)}}}function fn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(s,a={})=>{let l=i.toUpperCase();return cn(l,s,a.body,async u=>{x("hasAuth");let f=E.startSpan("auth",{kind:pe.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let d=V({authenticationId:n,method:l,url:s,body:a.body,headers:a.headers,query:a.query}),m=await me(d,{timeout:a.timeout});return u.setAttribute("statusCode",m.status),await Nt(u,m.status,{bodyValue:m.body}),Me(u,"success"),m}catch(d){throw x("hasError"),d instanceof c&&d.detail.kind==="broker_error"&&d.detail.status>0&&u.setAttribute("statusCode",d.detail.status),Me(u,"error",d instanceof Error?d.message:String(d)),d}})}}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 xn,SpanStatusCode as jt}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var mn=18e4,Mt=mn-1e4,pn=2e3;async function Bt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Mt;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(pn,200*2**i),u=l/2+Math.random()*(l/2),f=Mt-(Date.now()-o);await new Promise(d=>setTimeout(d,Math.min(u,f))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var gn=new Set(["SELECT","WITH","SHOW"]),yn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function hn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function wn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?A(t):y(t);return c.dbCallFailed(i)}function bn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Sn(e,t){return typeof t!="number"||t<0?{}:gn.has(e)?{rowsRead:t}:yn.has(e)?{rowsWritten:t}:{}}function Ut(e){async function t(r,n,o){let i=V({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await me(i);if(s>=400)throw wn(s,a);return bn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:hn,async execute(r,n){let o=Q(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=y(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Bt(t,r.region,l),f=u.Status;if(f==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(f==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let d=Sn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:d}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:d}}}}var Be=64*1024;function En(e){return e.length>Be?`${e.slice(0,Be)}...[truncated]`:e}function vn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Rn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Be?v(e,"result",{truncated:!0,size:n.length}):v(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Tn(e,t,r){let n=Q(r),o=En(r);return E.startActiveSpan("database",{kind:xn.CLIENT},async i=>{vn(i,e,t,n,o);try{x("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Rn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:jt.OK}),l}catch(s){x("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:jt.ERROR,message:a}),s}finally{i.end()}})}function Pn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Ut(n);function i(s,a){return o.validate(s),Tn(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Dn}from"unstorage";var Kt=1024,Ue=250*1024,Cn=new TextEncoder,In=/(^|\/)\.\.(\/|$)/,An=/[?#]/,kn=/[\u0000-\u001F\u007F]/;function $t(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(In.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(An.test(e)||kn.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Cn.encode(e).length;if(t<1||t>Kt)throw c.kvKeyInvalid(`Key must be between 1 and ${Kt} UTF-8 bytes (got ${t})`)}function Ht(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Vt(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>Ue)throw c.kvValueTooLarge(`Value exceeds maximum size of ${Ue} bytes (got ${r})`,Ue)}function Z(e){$t(e)}function ge(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function zt(e){let t=ge(e,"getItem"),r=ge(e,"setItem"),n=ge(e,"removeItem"),o=ge(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return Z(s),t(s,a)},setItem(s,a,l){return Z(s),r(s,a,l)},removeItem(s,a){return Z(s),n(s,a)},hasItem(s,a){return Z(s),o(s,a)},getKeys(s,a){return s.length>0&&Z(s),i(s,a)}}}function ye(e){return Dn({driver:zt(e)})}import{defineDriver as On}from"unstorage";function Fn(e){try{return JSON.parse(e)}catch{return e}}var _n=On(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Fn(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Jt(e){return _n({client:e})}import Mn from"ky";import{z as h}from"zod";async function B(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function qt(e){return D(e).hosts.api}function Ln(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Nn(e){return e.split("/").map(encodeURIComponent).join("/")}function ee(e,t,r){return`${e}${Ln(t)}/${Nn(r)}`}var Bn=6e4,je=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(je),h.record(je)])),Un=h.object({projectId:h.string(),key:h.string(),value:je,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function jn(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function Kn(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 he(e,t){throw c.kvCallFailed(e,Kn(t),y(t))}async function we(e,t,r={}){try{let n=await Mn(t,{method:e,headers:jn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Bn}),o=e==="head"?void 0:await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function Yt(e){let t=qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await we("get",ee(t,r,n));if(o===404)return null;(o<200||o>=300)&&he(o,i);let s=Un.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",y(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await we("put",ee(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&he(s,a)},async delete(n){let{status:o,body:i}=await we("delete",ee(t,r,n));o!==204&&he(o,i)},async has(n){let{status:o,body:i}=await we("head",ee(t,r,n));if(o===200)return!0;if(o===404)return!1;he(o,i)}}}function be(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Vt(r),o!==void 0&&Ht(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function $n(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Xt(e){let t=$n(),r=e??Yt(t),n=ye(Jt(r));return be(n)}import{defineDriver as Hn}from"unstorage";var Vn=Hn(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl;t.set(n,{value:o,expiresAt:s!==void 0?Date.now()+s*1e3:void 0})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function Gt(){return Vn({})}var Ke;function zn(){return Ke||(Ke=ye(Gt())),Ke}function Wt(){return be(zn())}function Jn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function ks(){return Jn()?Xt():Wt()}import{createHash as Xn}from"crypto";import{mkdir as Gn,readFile as rr,readdir as nr,rm as Zt,unlink as Wn,writeFile as er}from"fs/promises";import{dirname as Qn}from"path";async function qn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>P)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got more than ${P})`,P);r.push(i)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?qn(e):Buffer.from(e)}var Yn={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"},Qt="application/octet-stream";function Se(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Qt;let r=e.slice(t+1).toLowerCase();return Yn[r]??Qt}function K(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xe(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function $e(e){try{let t=await rr(ue(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function tr(e){await Gn(Qn(e),{recursive:!0})}async function Zn(e,t){let r=de(e,t),n;try{n=await nr(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 or(e,t){let r=de(e,t),n;try{n=await nr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await or(e,s)):i.isFile()&&o.push(s)}return o}function ir(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await U(t),i=r?.contentType??Se(e),s=Xn("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await tr(l),await er(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},f=ue(n,e);return await tr(f),await er(f,JSON.stringify(u)),xe(e,u)})},async get(e){return j(async()=>{let t=await $e(e);return t?{data:await rr(W(K(),e)),metadata:xe(e,t)}:null})},async head(e){return j(async()=>{let t=await $e(e);return t?xe(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),ue(t,e)].map(async r=>{try{await Wn(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await or(t,e);return await Promise.all([Zt(de(t,e),{recursive:!0,force:!0}),Zt(kt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,i=(await Zn(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await $e(a);return l?xe(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}}}}import{createHash as so}from"crypto";function Ee(e){return D(e).hosts.api}function eo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function te(e,t){return`${e}${eo(t)}`}function $(e,t,r){return`${te(e,t)}/${encodeURIComponent(r)}`}function ve(e,t,r){return`${$(e,t,r)}/upload`}function sr(e,t,r){return`${$(e,t,r)}/download`}function ar(e,t,r){return`${$(e,t,r)}/signed-url`}function cr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${te(e,t)}/file?${o.toString()}`}function lr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${te(e,t)}?${o.toString()}`}import Ve from"ky";import{z as g}from"zod";var ze=6e4,ur=g.object({id:g.string(),workspaceId:g.string(),projectId:g.string(),parentFolder:g.string().nullable().optional(),name:g.string(),size:g.number().nullable().optional(),objectType:g.enum(["Folder","File"]),contentType:g.string().nullable().optional(),createdAt:g.string(),updatedAt:g.string()}),to=g.object({signedURL:g.string()}),ro=g.object({path:g.array(g.object({id:g.string(),name:g.string()})),elements:g.array(ur)});function Je(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function dr(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 I(e,t){throw c.filesCallFailed(e,dr(t),y(t))}function no(e,t){return e===400&&dr(t).toLowerCase()==="resource not found"}async function oo(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await Ve(t,{method:e,headers:Je(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ze}),o=await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function He(e,t){let r=ur.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",y(t));return r.data}function fr(e){let t=Ee(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",te(t,r),{json:n});return(o<200||o>=300)&&I(o,i),He(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",cr(t,r,n,o));return i===404||no(i,s)?null:((i<200||i>=300)&&I(i,s),He(i,s))},async getById(n){let{status:o,body:i}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&I(o,i),He(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",lr(t,r,n,o));(i<200||i>=300)&&I(i,s);let a=ro.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",y(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await oo(a),f;try{f=await Ve(ve(t,r,n),{method:"post",headers:{...Je(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ze})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let d=await B(f);(f.status<200||f.status>=300)&&I(f.status,d)},async downloadContent(n){let o;try{o=await Ve(sr(t,r,n),{method:"get",headers:Je(),throwHttpErrors:!1,timeout:ze})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await B(o);I(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",ar(t,r,n));(o<200||o>=300)&&I(o,i);let s=to.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",y(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&I(o,i)}}}function qe(e){return e.split("/").filter(t=>t.length>0)}function Ye(e){return e instanceof c&&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(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Xe(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await io(e,o,i)).id;return{parentFolder:o,name:n}}async function re(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function Ge(e,t){if(t.length===0)return;let r=qe(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var ao=500,co=8;async function lo(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function uo(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function fo(e){return so("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Re(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 mr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function pr(e,t){let{elements:r}=await e.listChildren(t,ao);return(await lo(r,co,async o=>{let i=o.objectType==="Folder"?await pr(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function gr(e){let t=uo(),r=e??fr(t),n=Ee(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Xe(r,i),f=await U(s),d=a?.contentType??Se(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await mr(r,l,u,d);await r.uploadContent(p.id,f,u,d);let ne=await r.getById(p.id);return Re(i,ne??p,d)},async get(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Re(i,a)}},async head(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Re(i,a)},async delete(i){let s=await re(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await Ge(r,i);if(s===null)return{deleted:0};let a=await pr(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Ge(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(d=>d.objectType==="File").map(d=>Re(i?`${i}/${d.name}`:d.name,d)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Xe(r,i),f=await r.getByName(a,l)??await mr(r,a,l,s?.contentType);return{url:ve(n,o,f.id),expiresAt:M(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await re(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:M(s?.expiresIn)}}}}function We(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){k(n,r);let s=await U(o);return It(s.byteLength),e.put(n,s,i)},async get(n){return k(n,r),e.get(n)},async head(n){return k(n,r),e.head(n)},async delete(n){return k(n,r),e.delete(n)},async deleteMany(n){let o=_e(n);return ce(o,r),e.deleteMany(o)},async list(n,o){let i=_e(n??"");return ce(i,r),e.list(i,o)},async getUploadUrl(n,o){return k(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return k(n,r),e.getDownloadUrl(n,o)}}}function mo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Ea(){if(mo())return We(gr());let e=w().projectRoot;return We(ir(),{maxPathBytes:e?At(e):void 0})}export{po as a,w as b,yo as c,ho as d,wo as e,b as f,bo as g,Et as h,Mr as i,x as j,v as k,Hr as l,Vr as m,E as n,zr as o,qo as p,ii as q,ci as r,Ti as s,Pn as t,ks as u,k as v,W as w,ue as x,Ea as y,Dt as z,C as A,Zo as B,ei as C};