eve 0.31.1 → 0.31.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/src/compiled/.vendor-stamp.json +6 -6
  3. package/dist/src/compiled/@workflow/core/_quickjs-wasi.d.ts +8 -0
  4. package/dist/src/compiled/@workflow/core/correlation-id.d.ts +109 -0
  5. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +1 -0
  6. package/dist/src/compiled/@workflow/core/index.js +2 -2
  7. package/dist/src/compiled/@workflow/core/private.d.ts +17 -1
  8. package/dist/src/compiled/@workflow/core/private.js +1 -1
  9. package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +19 -0
  10. package/dist/src/compiled/@workflow/core/runtime/deployment-guard.d.ts +99 -0
  11. package/dist/src/compiled/@workflow/core/runtime/quickjs-assets.generated.d.ts +14 -0
  12. package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +124 -0
  13. package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +193 -0
  14. package/dist/src/compiled/@workflow/core/runtime/run.d.ts +2 -0
  15. package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +18 -1
  16. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +7 -0
  17. package/dist/src/compiled/@workflow/core/runtime/vm-mode.d.ts +44 -0
  18. package/dist/src/compiled/@workflow/core/runtime/vm-serde-bundle.generated.d.ts +14 -0
  19. package/dist/src/compiled/@workflow/core/runtime.d.ts +1 -1
  20. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  21. package/dist/src/compiled/@workflow/core/serialization/codec-devalue-vm.d.ts +9 -0
  22. package/dist/src/compiled/@workflow/core/serialization/reducers/class-vm.d.ts +20 -0
  23. package/dist/src/compiled/@workflow/core/serialization/reducers/common-vm.d.ts +15 -0
  24. package/dist/src/compiled/@workflow/core/serialization/reducers/step-function-vm.d.ts +44 -0
  25. package/dist/src/compiled/@workflow/core/serialization/vm-bundle-entry.d.ts +12 -0
  26. package/dist/src/compiled/@workflow/core/serialization/workflow-vm.d.ts +24 -0
  27. package/dist/src/compiled/@workflow/core/serialization.d.ts +2 -1
  28. package/dist/src/compiled/@workflow/core/source-map.d.ts +20 -0
  29. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +78 -0
  30. package/dist/src/compiled/@workflow/core/telemetry.d.ts +5 -0
  31. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  32. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  33. package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
  34. package/dist/src/compiled/@workflow/errors/index.d.ts +24 -0
  35. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  36. package/dist/src/compiled/@workflow/world/analytics.d.ts +2 -0
  37. package/dist/src/compiled/@workflow/world/events.d.ts +51 -1
  38. package/dist/src/compiled/@workflow/world/hooks.d.ts +1 -0
  39. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  40. package/dist/src/compiled/@workflow/world/interfaces.d.ts +28 -1
  41. package/dist/src/compiled/@workflow/world/queue.d.ts +8 -0
  42. package/dist/src/compiled/@workflow/world/runs.d.ts +83 -0
  43. package/dist/src/compiled/@workflow/world-local/index.js +5 -4
  44. package/dist/src/compiled/@workflow/world-vercel/index.js +15 -15
  45. package/dist/src/compiled/_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js +1 -0
  46. package/dist/src/compiled/_chunks/workflow/{attribute-changes-DROfGk6l.js → attribute-changes-Du5ztewf.js} +2 -2
  47. package/dist/src/compiled/_chunks/workflow/{dist-D5bR13zs.js → dist-CNXUKQCp.js} +1 -1
  48. package/dist/src/compiled/_chunks/workflow/dist-CRTn4Sg8.js +3 -0
  49. package/dist/src/compiled/_chunks/workflow/dist-tJoQXAF6.js +1 -0
  50. package/dist/src/compiled/_chunks/workflow/functions-ClJbpZhR.js +1 -0
  51. package/dist/src/compiled/_chunks/workflow/{private-BcwCGTV5.js → private-CiWVdS5v.js} +1 -1
  52. package/dist/src/compiled/_chunks/workflow/resume-hook-CT0keOww.js +1 -0
  53. package/dist/src/compiled/_chunks/workflow/run-DBheaFhH.js +1 -0
  54. package/dist/src/compiled/_chunks/workflow/signal-exit-C8vsI6zj.js +1 -0
  55. package/dist/src/compiled/_chunks/workflow/sleep-BeH4B0Cd.js +1 -0
  56. package/dist/src/compiled/_chunks/workflow/{token-hiUWkDKe.js → token-DtCUEpJs.js} +1 -1
  57. package/dist/src/compiled/_chunks/workflow/{token-util-DURSL1l8.js → token-util-DNwIAn_u.js} +9 -9
  58. package/dist/src/compiled/_chunks/workflow/undici-CUIybhQ2.js +95 -0
  59. package/dist/src/compiled/_chunks/workflow/wait-until-CMX5LUWJ.js +15 -0
  60. package/dist/src/compiler/extension-compatibility.d.ts +4 -4
  61. package/dist/src/compiler/extension-compatibility.js +1 -1
  62. package/dist/src/internal/application/package.js +1 -1
  63. package/dist/src/internal/authored-definition/connection.js +1 -1
  64. package/dist/src/public/channels/linear/linearChannel.d.ts +2 -0
  65. package/dist/src/public/channels/linear/linearChannel.js +1 -1
  66. package/dist/src/public/channels/linear/verify.js +1 -1
  67. package/dist/src/public/connections/index.d.ts +1 -0
  68. package/dist/src/public/definitions/connections/mcp.d.ts +9 -0
  69. package/dist/src/public/definitions/connections/openapi.d.ts +9 -0
  70. package/dist/src/public/definitions/connections/tool-call.d.ts +21 -0
  71. package/dist/src/public/definitions/connections/tool-call.js +1 -0
  72. package/dist/src/runtime/connections/mcp-client.js +1 -1
  73. package/dist/src/runtime/connections/openapi-client.js +1 -1
  74. package/dist/src/runtime/connections/provided-arguments.d.ts +9 -0
  75. package/dist/src/runtime/connections/provided-arguments.js +1 -0
  76. package/dist/src/runtime/resolve-connection.js +1 -1
  77. package/dist/src/runtime/types.d.ts +2 -0
  78. package/dist/src/setup/scaffold/create/project.js +1 -1
  79. package/docs/channels/linear.mdx +3 -1
  80. package/docs/connections/mcp.mdx +29 -1
  81. package/docs/connections/openapi.mdx +24 -0
  82. package/package.json +6 -6
  83. package/dist/src/compiled/_chunks/workflow/dist-B-vbuNqP.js +0 -1
  84. package/dist/src/compiled/_chunks/workflow/dist-dNxTT6nO.js +0 -3
  85. package/dist/src/compiled/_chunks/workflow/functions-CiVUVDNB.js +0 -1
  86. package/dist/src/compiled/_chunks/workflow/resume-hook-bc-OQVI0.js +0 -1
  87. package/dist/src/compiled/_chunks/workflow/run-DM3ouA3U.js +0 -1
  88. package/dist/src/compiled/_chunks/workflow/sleep-D5iWly6-.js +0 -1
  89. package/dist/src/compiled/_chunks/workflow/undici-DWL_MYmT.js +0 -95
  90. package/dist/src/compiled/_chunks/workflow/wait-until-DoW76jdb.js +0 -15
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{toInputSchema}from"#shared/tool-schema.js";import{tool}from"ai";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const log=createLogger(`runtime.connections.openapi-client`),SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,t,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(t)?t:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),t=this.#a(e),o=this.#s(e),s=this.#n.tools,c=s===void 0?o:o.filter(e=>passesToolFilter(e.toolName,s)),l=[],u=new Map,d={};for(let e of c){let a;try{a=toInputSchema(e.inputSchema)}catch(t){log.warn(`omitting OpenAPI operation with an invalid input schema`,{connectionName:this.#n.connectionName,error:t,toolName:e.toolName});continue}u.set(e.toolName,e),l.push({description:e.description,inputSchema:e.inputSchema,name:e.toolName}),d[e.toolName]=tool({description:e.description,inputSchema:a,execute:async(r,i)=>this.#f(e,t,isObject(r)?r:{},{abortSignal:i?.abortSignal})})}return{metadata:l,operations:u,tools:d,baseUrl:t}}#a(e){let t=this.#n.url,n=typeof t==`string`&&t.trim().length>0?t:extractServerUrl(e,this.#n.spec);if(n===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" has no base URL: set "baseUrl" or ensure the document declares an absolute "servers" entry or Swagger "host".`);return assertSecureUrl(n,this.#n.connectionName,`base`),n}async#o(){let e=this.#n.spec;if(e===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" is missing its "spec" source.`);if(typeof e!=`string`)return e;assertSecureUrl(e,this.#n.connectionName,`spec`);let t;try{t=await fetch(e,{headers:{accept:`application/json, application/yaml, text/yaml, */*`}})}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": ${String(t)}`)}if(t.redirected&&assertSecureUrl(t.url,this.#n.connectionName,`spec`),!t.ok)throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": HTTP ${t.status}.`);let r=await t.text(),i;try{i=parseSpecDocument(r)}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" could not be parsed as JSON or YAML: ${String(t)}`)}if(!isObject(i))throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" is not an OpenAPI document object.`);return i}#s(e){let t=e.paths;if(!isObject(t))return[];let r=[],i=new Set;for(let[a,o]of Object.entries(t)){if(!isObject(o))continue;let t=isArray(o.parameters)?o.parameters:[];for(let f of HTTP_METHODS){let s=o[f];if(!isObject(s))continue;let p=uniqueName(operationName(s,f,a),i),m=isArray(s.parameters)?s.parameters:[],h=[...t,...m],g=this.#c(e,h),_=this.#l(e,s.requestBody,h);r.push({toolName:p,method:f,pathTemplate:a,description:operationDescription(s),parameters:g,requestBody:_,inputSchema:buildInputSchema(g,_),security:resolveSecurity(e,s)})}}return r}#c(e,t){let r=[];for(let i of t){let t=isObject(i)?deref(e,i):i;if(!isObject(t))continue;let a=t.in;if(a!==`path`&&a!==`query`&&a!==`header`&&a!==`cookie`||typeof t.name!=`string`)continue;let o=this.#u(e,t);r.push({name:t.name,location:a,required:t.required===!0||a===`path`,schema:o,description:typeof t.description==`string`?t.description:void 0})}return r}#l(e,t,r=[]){if(isObject(t)){let r=deref(e,t);if(isObject(r)&&isObject(r.content)){let t=r.content,i=`application/json`in t?`application/json`:Object.keys(t)[0];if(i!==void 0){let a=t[i],o=isObject(a)&&isObject(a.schema)?derefSchema(e,a.schema):{};return{required:r.required===!0,contentType:i,schema:o}}}}return this.#d(e,r)}#u(e,t){if(isObject(t.schema))return derefSchema(e,t.schema);let r={};for(let e of SWAGGER_PARAMETER_SCHEMA_KEYS)t[e]!==void 0&&(r[e]=t[e]);return derefSchema(e,r)}#d(e,t){for(let r of t){let t=isObject(r)?deref(e,r):r;if(!isObject(t)||t.in!==`body`)continue;let i=isObject(t.schema)?derefSchema(e,t.schema):{};return{required:t.required===!0,contentType:`application/json`,schema:i}}}async#f(e,t,n,r){let i=await resolveHeaders(this.#n),a=e.pathTemplate,s=new URLSearchParams,c=[];for(let t of e.parameters){let e=n[t.name];e!=null&&(t.location===`path`?a=a.replace(`{${t.name}}`,encodeURIComponent(String(e))):t.location===`query`?appendQuery(s,t.name,e):t.location===`cookie`?c.push(`${t.name}=${encodeURIComponent(String(e))}`):i[t.name]=String(e))}if(applySecurity(e.security,this.#n,i,s,c),c.length>0){let e=i.cookie??i.Cookie;delete i.Cookie,i.cookie=[e,...c].filter(e=>!!e).join(`; `)}let l=new URL(joinPath(t,a));l.search=s.toString();let u;e.requestBody!==void 0&&n.body!==void 0&&(u=JSON.stringify(n.body),i[`content-type`]=e.requestBody.contentType);let d=await fetch(l,{method:e.method.toUpperCase(),headers:i,body:u,signal:r?.abortSignal});return{status:d.status,statusText:d.statusText,body:await readResponseBody(d)}}};function appendQuery(e,t,n){if(isArray(n)){for(let r of n)e.append(t,String(r));return}e.append(t,String(n))}function joinPath(e,t){return`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`}function assertSecureUrl(e,n,r){let i;try{i=new URL(e)}catch{throw Error(`OpenAPI connection "${n}" has an invalid ${r} URL "${e}".`)}if(i.protocol!==`https:`&&!(i.protocol===`http:`&&isLoopbackHostname(i.hostname)))throw Error(`OpenAPI connection "${n}" must use https for its ${r} (got "${i.protocol}//${i.host}").`)}async function readResponseBody(e){let t=await e.text();if(t.length===0)return null;if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return JSON.parse(t)}catch{return t}return t}export{OpenApiConnectionClient};
1
+ import{createLogger}from"#internal/logging.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{toInputSchema}from"#shared/tool-schema.js";import{tool}from"ai";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const log=createLogger(`runtime.connections.openapi-client`),SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,t,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(t)?t:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),t=this.#a(e),o=this.#s(e),c=this.#n.tools,l=c===void 0?o:o.filter(e=>passesToolFilter(e.toolName,c)),u=[],d=new Map,f={},p=Object.keys(this.#n.toolCall?.providedArguments??{});for(let e of l){let o=omitProvidedArgumentsFromSchema(e.inputSchema,p),s;try{s=toInputSchema(o)}catch(t){log.warn(`omitting OpenAPI operation with an invalid input schema`,{connectionName:this.#n.connectionName,error:t,toolName:e.toolName});continue}d.set(e.toolName,e),u.push({description:e.description,inputSchema:o,name:e.toolName}),f[e.toolName]=tool({description:e.description,inputSchema:s,execute:async(r,i)=>this.#f(e,t,isObject(r)?r:{},{abortSignal:i?.abortSignal})})}return{metadata:u,operations:d,tools:f,baseUrl:t}}#a(e){let t=this.#n.url,n=typeof t==`string`&&t.trim().length>0?t:extractServerUrl(e,this.#n.spec);if(n===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" has no base URL: set "baseUrl" or ensure the document declares an absolute "servers" entry or Swagger "host".`);return assertSecureUrl(n,this.#n.connectionName,`base`),n}async#o(){let e=this.#n.spec;if(e===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" is missing its "spec" source.`);if(typeof e!=`string`)return e;assertSecureUrl(e,this.#n.connectionName,`spec`);let t;try{t=await fetch(e,{headers:{accept:`application/json, application/yaml, text/yaml, */*`}})}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": ${String(t)}`)}if(t.redirected&&assertSecureUrl(t.url,this.#n.connectionName,`spec`),!t.ok)throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": HTTP ${t.status}.`);let r=await t.text(),i;try{i=parseSpecDocument(r)}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" could not be parsed as JSON or YAML: ${String(t)}`)}if(!isObject(i))throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" is not an OpenAPI document object.`);return i}#s(e){let t=e.paths;if(!isObject(t))return[];let r=[],i=new Set;for(let[a,o]of Object.entries(t)){if(!isObject(o))continue;let t=isArray(o.parameters)?o.parameters:[];for(let s of HTTP_METHODS){let c=o[s];if(!isObject(c))continue;let l=uniqueName(operationName(c,s,a),i),m=isArray(c.parameters)?c.parameters:[],h=[...t,...m],g=this.#c(e,h),_=this.#l(e,c.requestBody,h);r.push({toolName:l,method:s,pathTemplate:a,description:operationDescription(c),parameters:g,requestBody:_,inputSchema:buildInputSchema(g,_),security:resolveSecurity(e,c)})}}return r}#c(e,t){let r=[];for(let i of t){let t=isObject(i)?deref(e,i):i;if(!isObject(t))continue;let a=t.in;if(a!==`path`&&a!==`query`&&a!==`header`&&a!==`cookie`||typeof t.name!=`string`)continue;let o=this.#u(e,t);r.push({name:t.name,location:a,required:t.required===!0||a===`path`,schema:o,description:typeof t.description==`string`?t.description:void 0})}return r}#l(e,t,r=[]){if(isObject(t)){let r=deref(e,t);if(isObject(r)&&isObject(r.content)){let t=r.content,i=`application/json`in t?`application/json`:Object.keys(t)[0];if(i!==void 0){let a=t[i],o=isObject(a)&&isObject(a.schema)?derefSchema(e,a.schema):{};return{required:r.required===!0,contentType:i,schema:o}}}}return this.#d(e,r)}#u(e,t){if(isObject(t.schema))return derefSchema(e,t.schema);let r={};for(let e of SWAGGER_PARAMETER_SCHEMA_KEYS)t[e]!==void 0&&(r[e]=t[e]);return derefSchema(e,r)}#d(e,t){for(let r of t){let t=isObject(r)?deref(e,r):r;if(!isObject(t)||t.in!==`body`)continue;let i=isObject(t.schema)?derefSchema(e,t.schema):{};return{required:t.required===!0,contentType:`application/json`,schema:i}}}async#f(e,t,n,r){let i=await resolveProvidedArguments({args:n,connection:this.#n,toolName:e.toolName}),a=await resolveHeaders(this.#n),s=e.pathTemplate,l=new URLSearchParams,u=[];for(let t of e.parameters){let e=i[t.name];e!=null&&(t.location===`path`?s=s.replace(`{${t.name}}`,encodeURIComponent(String(e))):t.location===`query`?appendQuery(l,t.name,e):t.location===`cookie`?u.push(`${t.name}=${encodeURIComponent(String(e))}`):a[t.name]=String(e))}if(applySecurity(e.security,this.#n,a,l,u),u.length>0){let e=a.cookie??a.Cookie;delete a.Cookie,a.cookie=[e,...u].filter(e=>!!e).join(`; `)}let d=new URL(joinPath(t,s));d.search=l.toString();let f;e.requestBody!==void 0&&i.body!==void 0&&(f=JSON.stringify(i.body),a[`content-type`]=e.requestBody.contentType);let p=await fetch(d,{method:e.method.toUpperCase(),headers:a,body:f,signal:r?.abortSignal});return{status:p.status,statusText:p.statusText,body:await readResponseBody(p)}}};function appendQuery(e,t,n){if(isArray(n)){for(let r of n)e.append(t,String(r));return}e.append(t,String(n))}function joinPath(e,t){return`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`}function assertSecureUrl(e,n,r){let i;try{i=new URL(e)}catch{throw Error(`OpenAPI connection "${n}" has an invalid ${r} URL "${e}".`)}if(i.protocol!==`https:`&&!(i.protocol===`http:`&&isLoopbackHostname(i.hostname)))throw Error(`OpenAPI connection "${n}" must use https for its ${r} (got "${i.protocol}//${i.host}").`)}async function readResponseBody(e){let t=await e.text();if(t.length===0)return null;if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return JSON.parse(t)}catch{return t}return t}export{OpenApiConnectionClient};
@@ -0,0 +1,9 @@
1
+ import type { ResolvedConnectionDefinition } from "#runtime/types.js";
2
+ /** Resolves and merges application-provided arguments, with application values winning. */
3
+ export declare function resolveProvidedArguments(input: {
4
+ readonly args: unknown;
5
+ readonly connection: ResolvedConnectionDefinition;
6
+ readonly toolName: string;
7
+ }): Promise<Record<string, unknown>>;
8
+ /** Removes application-provided top-level properties from a remote tool schema. */
9
+ export declare function omitProvidedArgumentsFromSchema<TSchema extends Record<string, unknown>>(schema: TSchema, names: readonly string[]): TSchema;
@@ -0,0 +1 @@
1
+ import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";async function resolveProvidedArguments(r){if(!isObject(r.args))throw Error(`Tool "${r.toolName}" in connection "${r.connection.connectionName}" expected object arguments.`);let i=r.connection.toolCall?.providedArguments;if(i===void 0||Object.keys(i).length===0)return r.args;let a,getContext=()=>a??={...buildCallbackContext(),toolName:r.toolName},o={};for(let[e,n]of Object.entries(i)){let i=typeof n==`function`?await n(getContext()):await n;try{o[e]=parseJsonValue(i)}catch{throw Error(`Connection "${r.connection.connectionName}" provided argument "${e}" must resolve to a JSON-serializable value.`)}}return{...r.args,...o}}function omitProvidedArgumentsFromSchema(t,n){if(n.length===0)return t;let r=new Set(n),i={...t};return isObject(t.properties)&&(i.properties=Object.fromEntries(Object.entries(t.properties).filter(([e])=>!r.has(e)))),Array.isArray(t.required)&&(i.required=t.required.filter(e=>typeof e!=`string`||!r.has(e))),i}export{omitProvidedArgumentsFromSchema,resolveProvidedArguments};
@@ -1 +1 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{registerDefinitionSource,stampDefinitionKey}from"#public/tool-result-narrowing.js";async function resolveConnectionDefinition(t,n,r){try{let i=expectObjectRecord(await loadResolvedModuleExport({definition:t,kindLabel:`connection`,moduleMap:n,nodeId:r}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to return an object.`),a={kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName},o=`connection-source:${t.sourceId}`;stampDefinitionKey(i,o),registerDefinitionSource(o,a),registerDefinitionSource(`connection:${t.url}`,a);let s=i.auth!==void 0,c=i.headers!==void 0,l=t.protocol===`openapi`?i.operations:i.tools,u={connectionName:t.connectionName,description:t.description,exportName:t.exportName,logicalPath:t.logicalPath,protocol:t.protocol,sourceId:t.sourceId,sourceKind:`module`,url:t.url};if(s)if(typeof i.auth==`function`)u.authorization=i.auth;else try{u.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${t.connectionName}" at "${t.logicalPath}":`)}catch(e){throw new ResolveAgentError(toErrorMessage(e),{logicalPath:t.logicalPath,sourceId:t.sourceId})}return c&&(u.headers=i.headers),l!==void 0&&(u.tools=l),t.protocol===`openapi`&&i.spec!==void 0&&(u.spec=i.spec),typeof i.approval==`function`&&(u.approval=i.approval),u}catch(e){throw e instanceof ResolveAgentError?e:new ResolveAgentError(`Failed to resolve connection "${t.connectionName}" from "${t.logicalPath}": ${toErrorMessage(e)}`,{logicalPath:t.logicalPath,sourceId:t.sourceId})}}export{resolveConnectionDefinition};
1
+ import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{registerDefinitionSource,stampDefinitionKey}from"#public/tool-result-narrowing.js";async function resolveConnectionDefinition(t,n,r){try{let i=expectObjectRecord(await loadResolvedModuleExport({definition:t,kindLabel:`connection`,moduleMap:n,nodeId:r}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to return an object.`),a={kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName},o=`connection-source:${t.sourceId}`;stampDefinitionKey(i,o),registerDefinitionSource(o,a),registerDefinitionSource(`connection:${t.url}`,a);let s=i.auth!==void 0,c=i.headers!==void 0,l=t.protocol===`openapi`?i.operations:i.tools,u={connectionName:t.connectionName,description:t.description,exportName:t.exportName,logicalPath:t.logicalPath,protocol:t.protocol,sourceId:t.sourceId,sourceKind:`module`,url:t.url};if(s)if(typeof i.auth==`function`)u.authorization=i.auth;else try{u.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${t.connectionName}" at "${t.logicalPath}":`)}catch(e){throw new ResolveAgentError(toErrorMessage(e),{logicalPath:t.logicalPath,sourceId:t.sourceId})}return c&&(u.headers=i.headers),i.toolCall!==void 0&&(u.toolCall=i.toolCall),l!==void 0&&(u.tools=l),t.protocol===`openapi`&&i.spec!==void 0&&(u.spec=i.spec),typeof i.approval==`function`&&(u.approval=i.approval),u}catch(e){throw e instanceof ResolveAgentError?e:new ResolveAgentError(`Failed to resolve connection "${t.connectionName}" from "${t.logicalPath}": ${toErrorMessage(e)}`,{logicalPath:t.logicalPath,sourceId:t.sourceId})}}export{resolveConnectionDefinition};
@@ -10,6 +10,7 @@ import type { OutboundAuthFn } from "#public/agents/auth.js";
10
10
  import type { StreamEventHook } from "#public/definitions/hook.js";
11
11
  import type { Approval } from "#public/definitions/approval.js";
12
12
  import type { ToolModelOutput } from "#public/definitions/tool.js";
13
+ import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
13
14
  import type { AuthorizationDefinition, ConnectionAuthResolver, ConnectionProtocol, HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
14
15
  import type { OpenAPISpecSource } from "#public/definitions/connections/openapi.js";
15
16
  import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
@@ -78,6 +79,7 @@ export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
78
79
  readonly connectionName: string;
79
80
  readonly description: string;
80
81
  readonly headers?: Readonly<HeadersDefinition>;
82
+ readonly toolCall?: Readonly<ConnectionToolCallDefinition>;
81
83
  /**
82
84
  * Wire protocol. Selects the runtime client implementation. `tools`
83
85
  * carries the connection's operation/tool filter regardless of
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.3`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -48,6 +48,8 @@ export default linearChannel({
48
48
  });
49
49
  ```
50
50
 
51
+ Direct webhook verification accepts timestamps within 60 seconds by default, as Linear recommends. Set `maxSkewMs` to a larger number of milliseconds only when you intentionally accept delayed retries. Use the narrowest window that fits your retry policy.
52
+
51
53
  ```bash
52
54
  LINEAR_AGENT_ACCESS_TOKEN=lin_api_... # posts Agent Activities and creates proactive sessions
53
55
  LINEAR_WEBHOOK_SECRET=... # verifies Linear-Signature
@@ -63,7 +65,7 @@ https://<deployment>/eve/v1/linear
63
65
 
64
66
  For Linear's agent surface, configure the OAuth authorize URL with `actor=app` and grant the app scopes that let it appear as an agent in Linear, including `app:assignable` and `app:mentionable`. Subscribe to the `AgentSessionEvent` webhook category so Linear sends `created` events when the agent is delegated or mentioned and `prompted` events when the user continues the session.
65
67
 
66
- Linear sends webhook signatures in `Linear-Signature`; eve verifies the HMAC over the raw body and rejects stale `webhookTimestamp` values. If a trusted gateway verifies Linear before the request reaches eve, pass `credentials.webhookVerifier` instead of a webhook secret.
68
+ Linear sends webhook signatures in `Linear-Signature`; eve verifies the HMAC over the raw body and rejects stale `webhookTimestamp` values. If a trusted gateway verifies Linear before the request reaches eve, pass `credentials.webhookVerifier` instead of a webhook secret. Your custom verifier must enforce its timestamp policy because `maxSkewMs` does not apply.
67
69
 
68
70
  ## How the channel handles messages
69
71
 
@@ -89,6 +89,34 @@ export default defineMcpClientConnection({
89
89
 
90
90
  `auth` and `headers` can also be functions that receive the active session context. Use that when credentials, tenants, or routing depend on the caller.
91
91
 
92
+ ## Application-provided tool arguments
93
+
94
+ Some MCP servers require arguments that belong to the application rather than the model. For example, UCP servers expect the agent profile in `arguments.meta` on every tool call. Configure those values with `toolCall.providedArguments`:
95
+
96
+ ```ts title="agent/connections/storefront.ts"
97
+ import { defineMcpClientConnection } from "eve/connections";
98
+
99
+ const profileUrl = "https://agent.example.com/.well-known/ucp";
100
+
101
+ export default defineMcpClientConnection({
102
+ url: "https://store.example.com/api/ucp/mcp",
103
+ description: "Storefront catalog, carts, checkouts, and orders.",
104
+ toolCall: {
105
+ providedArguments: {
106
+ meta: ({ session }) => ({
107
+ "ucp-agent": {
108
+ profile: `${profileUrl}?session=${encodeURIComponent(session.id)}`,
109
+ },
110
+ }),
111
+ },
112
+ },
113
+ });
114
+ ```
115
+
116
+ Values may be JSON values, promises, or callbacks. Callbacks receive the active session context plus the bare remote `toolName`.
117
+
118
+ eve treats configured keys as application-owned: it removes them from every remote tool's model-facing input schema and adds their resolved values immediately before execution. They apply to every tool call on the connection and replace any conflicting model value. Approval policies continue to receive only the model-authored input.
119
+
92
120
  ## No auth
93
121
 
94
122
  Omit `auth` and `headers` only for intentionally public or local-only servers:
@@ -193,7 +221,7 @@ Return `"user-approval"` (or `true`) to pause for a person and `"not-applicable"
193
221
  | `principal_required` | A user-scoped `connect("...")` ran without an authenticated user. Return `principalType: "user"` from route auth, or use app-scoped auth. |
194
222
  | The model does not find the remote tool | Improve the connection `description`, then check `tools.allow` / `tools.block`. |
195
223
  | OAuth works locally but fails after deploy | Attach the Connect connector to the deployed Vercel project and verify the UID in `connect("...")`. |
196
- | The server rejects requests | Confirm the MCP URL, transport support, auth scheme, and any required headers. |
224
+ | The server rejects requests | Confirm the MCP URL, transport support, auth scheme, required headers, and application-provided arguments. |
197
225
 
198
226
  ## What to read next
199
227
 
@@ -117,6 +117,30 @@ export default defineOpenAPIConnection({
117
117
 
118
118
  `auth` and `headers` can also be functions that receive the active session context. Use that when credentials, tenants, or routing depend on the caller.
119
119
 
120
+ ## Application-provided operation arguments
121
+
122
+ Some APIs declare operation parameters that should come from the application rather than the model, such as a tenant or organization ID. Configure those values with `toolCall.providedArguments`:
123
+
124
+ ```ts title="agent/connections/crm.ts"
125
+ import { defineOpenAPIConnection } from "eve/connections";
126
+
127
+ export default defineOpenAPIConnection({
128
+ spec: "https://api.example.com/openapi.json",
129
+ description: "CRM accounts, contacts, and opportunities.",
130
+ toolCall: {
131
+ providedArguments: {
132
+ tenantId: ({ session }) => String(session.auth.current?.attributes.tenant ?? ""),
133
+ },
134
+ },
135
+ });
136
+ ```
137
+
138
+ Values may be JSON values, promises, or callbacks. Callbacks receive the active session context plus the bare operation `toolName`.
139
+
140
+ eve removes configured keys from every operation's model-facing input schema and adds their resolved values immediately before constructing the HTTP request. Values apply to every operation on the connection and replace any conflicting model value. The keys correspond to the generated top-level operation inputs: path, query, header, and cookie parameter names, plus `body` for a request body.
141
+
142
+ Use `headers` for transport-wide headers that are not operation inputs. Use `providedArguments` when the OpenAPI document declares the value as an operation parameter and it should remain outside model control. Approval policies continue to receive only the model-authored input.
143
+
120
144
  ## Operation filters
121
145
 
122
146
  Most OpenAPI specs describe far more than the model should use. Narrow generated tools with exactly one of `operations.allow` or `operations.block`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eve",
3
- "version": "0.31.1",
3
+ "version": "0.31.3",
4
4
  "private": false,
5
5
  "description": "Filesystem-first framework for durable backend AI agents that run anywhere.",
6
6
  "keywords": [
@@ -320,13 +320,13 @@
320
320
  "@vercel/otel": "2.1.3",
321
321
  "@vercel/sandbox": "2.8.0",
322
322
  "@vercel/sdk": "1.28.8",
323
- "@workflow/core": "5.0.0-beta.39",
324
- "@workflow/errors": "5.0.0-beta.15",
323
+ "@workflow/core": "5.0.0-beta.40",
324
+ "@workflow/errors": "5.0.0-beta.16",
325
325
  "@workflow/serde": "5.0.0-beta.2",
326
326
  "@workflow/utils": "5.0.0-beta.8",
327
- "@workflow/world": "5.0.0-beta.24",
328
- "@workflow/world-local": "5.0.0-beta.33",
329
- "@workflow/world-vercel": "5.0.0-beta.35",
327
+ "@workflow/world": "5.0.0-beta.25",
328
+ "@workflow/world-local": "5.0.0-beta.34",
329
+ "@workflow/world-vercel": "5.0.0-beta.36",
330
330
  "ai": "^7.0.38",
331
331
  "autoevals": "0.0.132",
332
332
  "chat": "4.34.0",
@@ -1 +0,0 @@
1
- import{o as e,t}from"./rolldown-runtime-DaDcL9Zw.js";var n=e(t(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}}))(),1);function r(e){if(typeof e==`string`){let t=(0,n.default)(e);if(typeof t!=`number`||t<0)throw Error(`Invalid duration: "${e}". Expected a valid duration string like "1s", "1m", "1h", etc.`);return new Date(Date.now()+t)}else if(typeof e==`number`){if(e<0||!Number.isFinite(e))throw Error(`Invalid duration: ${e}. Expected a non-negative finite number of milliseconds.`);return new Date(Date.now()+e)}else if(e instanceof Date||e&&typeof e==`object`&&typeof e.getTime==`function`)return e instanceof Date?e:new Date(e.getTime());else throw Error(`Invalid duration parameter. Expected a duration string, number (milliseconds), or Date object.`)}export{r as t};
@@ -1,3 +0,0 @@
1
- import{t as e}from"./dist-B-vbuNqP.js";const t={USER_ERROR:`USER_ERROR`,RUNTIME_ERROR:`RUNTIME_ERROR`,CORRUPTED_EVENT_LOG:`CORRUPTED_EVENT_LOG`,REPLAY_DIVERGENCE:`REPLAY_DIVERGENCE`,MAX_DELIVERIES_EXCEEDED:`MAX_DELIVERIES_EXCEEDED`,MAX_EVENTS_EXCEEDED:`MAX_EVENTS_EXCEEDED`,REPLAY_TIMEOUT:`REPLAY_TIMEOUT`,WORLD_CONTRACT_ERROR:`WORLD_CONTRACT_ERROR`};function n(e){return typeof e==`object`&&!!e&&`name`in e&&`message`in e}function r(e,t){if(t.length===0)return e;let n=[e];return t.forEach((e,r)=>{let i=r===t.length-1,a=i?`╰▶ `:`├▶ `,o=i?` `:`│ `;`${e.label}: ${e.value}`.split(`
2
- `).forEach((e,t)=>{n.push(`${t===0?a:o}${e}`)})}),n.join(`
3
- `)}function i(e,t){let n=[];return e&&n.push({label:`hint`,value:e}),t&&n.push({label:`docs`,value:`https://workflow-sdk.dev/err/${t}`}),n}const a={NODE_JS_MODULE_IN_WORKFLOW:`node-js-module-in-workflow`,START_INVALID_WORKFLOW_FUNCTION:`start-invalid-workflow-function`,SERIALIZATION_FAILED:`serialization-failed`,WEBHOOK_INVALID_RESPOND_WITH_VALUE:`webhook-invalid-respond-with-value`,WEBHOOK_RESPONSE_NOT_SENT:`webhook-response-not-sent`,FETCH_IN_WORKFLOW_FUNCTION:`fetch-in-workflow`,TIMEOUT_FUNCTIONS_IN_WORKFLOW:`timeout-in-workflow`,HOOK_CONFLICT:`hook-conflict`,CORRUPTED_EVENT_LOG:`corrupted-event-log`,REPLAY_DIVERGENCE:`replay-divergence`,STEP_NOT_REGISTERED:`step-not-registered`,WORKFLOW_NOT_REGISTERED:`workflow-not-registered`,RUNTIME_DECRYPTION_FAILED:`runtime-decryption-failed`};var o=class extends Error{cause;constructor(e,t){let n=r(e,i(void 0,t?.slug));super(n,{cause:t?.cause}),t?.cause!==void 0&&(this.cause=t.cause),t?.cause instanceof Error&&(this.stack=`${this.stack}\nCaused by: ${t.cause.stack}`)}static is(e){return n(e)&&e.name===`WorkflowError`}},s=class extends o{status;code;url;retryAfter;constructor(e,t){super(e,{cause:t?.cause}),this.name=`WorkflowWorldError`,this.status=t?.status,this.code=t?.code,this.url=t?.url,this.retryAfter=t?.retryAfter}static is(e){return n(e)&&e.name===`WorkflowWorldError`}},c=class extends o{runId;errorCode;constructor(e,t,n={}){let r=t instanceof Error?t.message:typeof t==`string`?t:t&&typeof t==`object`&&`message`in t?String(t.message):`Unknown error`;super(`Workflow run "${e}" failed: ${r}`,{cause:t}),this.name=`WorkflowRunFailedError`,this.runId=e,n.errorCode!==void 0&&(this.errorCode=n.errorCode)}static is(e){return n(e)&&e.name===`WorkflowRunFailedError`}},l=class extends o{runId;status;constructor(e,t){super(`Workflow run "${e}" has not completed`,{}),this.name=`WorkflowRunNotCompletedError`,this.runId=e,this.status=t}static is(e){return n(e)&&e.name===`WorkflowRunNotCompletedError`}},u=class extends o{constructor(e,t){super(e,{...t}),this.name=`WorkflowRuntimeError`}static is(e){return n(e)&&e.name===`WorkflowRuntimeError`}},d=class extends u{constructor(e,t){super(e,{...t,slug:a.CORRUPTED_EVENT_LOG}),this.name=`CorruptedEventLogError`}static is(e){return n(e)&&e.name===`CorruptedEventLogError`}},f=class extends u{eventId;constructor(e,t){super(e,{...t,slug:a.REPLAY_DIVERGENCE}),this.name=`ReplayDivergenceError`,this.eventId=t.eventId}static is(e){return n(e)&&e.name===`ReplayDivergenceError`&&typeof e.eventId==`string`}},p=class extends o{eventCount;limit;constructor(e,t,n){super(`Workflow exceeded the maximum of ${t} events per run`,n),this.name=`MaxEventsExceededError`,this.eventCount=e,this.limit=t}static is(e){return n(e)&&e.name===`MaxEventsExceededError`}},m=class extends u{constructor(e,t){super(e,{cause:t?.cause,slug:a.RUNTIME_DECRYPTION_FAILED}),this.name=`RuntimeDecryptionError`,t?.context!==void 0&&(this.context=t.context)}static is(e){return n(e)&&e.name===`RuntimeDecryptionError`}},h=class extends o{hint;constructor(e,t){let n=r(e,i(t?.hint,void 0));super(n,{cause:t?.cause}),this.name=`WorkflowBuildError`,this.hint=t?.hint}static is(e){return n(e)&&e.name===`WorkflowBuildError`}},g=class extends o{hint;fatal=!0;constructor(e,t){let n=r(e,i(t?.hint,void 0));super(n,{cause:t?.cause}),this.name=`SerializationError`,this.hint=t?.hint}static is(e){return n(e)&&e.name===`SerializationError`}},_=class extends u{stepName;constructor(e){super(`Step "${e}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`,{slug:a.STEP_NOT_REGISTERED}),this.name=`StepNotRegisteredError`,this.stepName=e}static is(e){return n(e)&&e.name===`StepNotRegisteredError`}},v=class extends u{workflowName;constructor(e){super(`Workflow "${e}" is not registered in the current deployment. This usually means a run was started against a deployment that does not have this workflow, or there was a build/bundling issue.`,{slug:a.WORKFLOW_NOT_REGISTERED}),this.name=`WorkflowNotRegisteredError`,this.workflowName=e}static is(e){return n(e)&&e.name===`WorkflowNotRegisteredError`}},y=class extends o{runId;constructor(e){super(`Workflow run "${e}" not found`,{}),this.name=`WorkflowRunNotFoundError`,this.runId=e}static is(e){return n(e)&&e.name===`WorkflowRunNotFoundError`}},b=class extends o{token;conflictingRunId;constructor(e,t){super(`Hook token "${e}" is already in use by another workflow${t?` (run "${t}")`:``}`,{slug:a.HOOK_CONFLICT}),this.name=`HookConflictError`,this.token=e,t!==void 0&&(this.conflictingRunId=t)}static is(e){return n(e)&&e.name===`HookConflictError`}},x=class extends o{token;constructor(e){super(`Hook not found`,{}),this.name=`HookNotFoundError`,this.token=e}static is(e){return n(e)&&e.name===`HookNotFoundError`}},S=class extends s{constructor(e){super(e),this.name=`EntityConflictError`}static is(e){return n(e)&&e.name===`EntityConflictError`}},C=class extends s{constructor(e){super(e),this.name=`RunExpiredError`}static is(e){return n(e)&&e.name===`RunExpiredError`}},w=class extends s{constructor(e,t){super(e,{retryAfter:t?.retryAfter}),this.name=`TooEarlyError`}static is(e){return n(e)&&e.name===`TooEarlyError`}},T=class extends s{retryAfter;constructor(e,t){super(e),this.name=`ThrottleError`,this.retryAfter=t?.retryAfter}static is(e){return n(e)&&e.name===`ThrottleError`}},E=class extends s{details;constructor(e,t){super(e,{status:412,retryAfter:t?.retryAfter}),this.name=`PreconditionFailedError`,this.details=t?.details}static is(e){return n(e)&&e.name===`PreconditionFailedError`}},D=class extends o{runId;constructor(e){super(`Workflow run "${e}" cancelled`,{}),this.name=`WorkflowRunCancelledError`,this.runId=e}static is(e){return n(e)&&e.name===`WorkflowRunCancelledError`}},O=class extends o{runSpecVersion;worldSpecVersion;constructor(e,t){super(`Run requires spec version ${e}, but world supports version ${t}. Please upgrade 'workflow' package.`),this.name=`RunNotSupportedError`,this.runSpecVersion=e,this.worldSpecVersion=t}static is(e){return n(e)&&e.name===`RunNotSupportedError`}},k=class extends Error{fatal=!0;constructor(e){super(e),this.name=`FatalError`}static is(e){return n(e)?e.name===`FatalError`||e.fatal===!0:!1}},A=class extends Error{retryAfter;constructor(t,n={}){super(t),this.name=`RetryableError`,n.retryAfter===void 0?this.retryAfter=new Date(Date.now()+1e3):this.retryAfter=e(n.retryAfter)}static is(e){return n(e)&&e.name===`RetryableError`}};const j="Your current vercel account does not have access to this resource. Use `vercel login` or `vercel switch` to ensure you are linked to the right account.",M=Symbol.for(`@workflow/errors//FatalError`),N=Symbol.for(`@workflow/errors//RetryableError`),P=Symbol.for(`@workflow/errors//HookConflictError`),F=Symbol.for(`@workflow/errors//RuntimeDecryptionError`);typeof globalThis<`u`&&(Object.hasOwn(globalThis,M)||Object.defineProperty(globalThis,M,{value:k,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,N)||Object.defineProperty(globalThis,N,{value:A,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,P)||Object.defineProperty(globalThis,P,{value:b,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,F)||Object.defineProperty(globalThis,F,{value:m,writable:!1,enumerable:!1,configurable:!1}));export{c as C,s as D,u as E,t as O,D as S,y as T,w as _,b as a,o as b,E as c,C as d,O as f,T as g,_ as h,k as i,f as l,g as m,a as n,x as o,m as p,S as r,p as s,d as t,A as u,j as v,l as w,v as x,h as y};
@@ -1 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-DaDcL9Zw.js";var t=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{CITY_HEADER_NAME:()=>u,COUNTRY_HEADER_NAME:()=>d,EMOJI_FLAG_UNICODE_STARTING_POSITION:()=>v,IP_HEADER_NAME:()=>f,LATITUDE_HEADER_NAME:()=>p,LONGITUDE_HEADER_NAME:()=>m,POSTAL_CODE_HEADER_NAME:()=>g,REGION_HEADER_NAME:()=>h,REQUEST_ID_HEADER_NAME:()=>_,geolocation:()=>w,ipAddress:()=>S}),t.exports=c(l);let u=`x-vercel-ip-city`,d=`x-vercel-ip-country`,f=`x-real-ip`,p=`x-vercel-ip-latitude`,m=`x-vercel-ip-longitude`,h=`x-vercel-ip-country-region`,g=`x-vercel-ip-postal-code`,_=`x-vercel-id`,v=127397;function y(e,t){return e.get(t)??void 0}function b(e,t){let n=y(e.headers,t);return n?decodeURIComponent(n):void 0}function x(e){let t=RegExp(`^[A-Z]{2}$`).test(e);if(!(!e||!t))return String.fromCodePoint(...e.split(``).map(e=>v+e.charCodeAt(0)))}function S(e){return y(`headers`in e?e.headers:e,f)}function C(e){return e?e.split(`:`)[0]:`dev1`}function w(e){return{city:b(e,u),country:y(e.headers,d),flag:x(y(e.headers,d)),countryRegion:y(e.headers,h),region:C(y(e.headers,_)),latitude:y(e.headers,p),longitude:y(e.headers,m),postalCode:y(e.headers,g)}}0&&(t.exports={CITY_HEADER_NAME:u,COUNTRY_HEADER_NAME:d,EMOJI_FLAG_UNICODE_STARTING_POSITION:v,IP_HEADER_NAME:f,LATITUDE_HEADER_NAME:p,LONGITUDE_HEADER_NAME:m,POSTAL_CODE_HEADER_NAME:g,REGION_HEADER_NAME:h,REQUEST_ID_HEADER_NAME:_,geolocation:w,ipAddress:S})})),n=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{getEnv:()=>u}),t.exports=c(l);let u=(e=process.env)=>({VERCEL:d(e,`VERCEL`),CI:d(e,`CI`),VERCEL_ENV:d(e,`VERCEL_ENV`),VERCEL_URL:d(e,`VERCEL_URL`),VERCEL_BRANCH_URL:d(e,`VERCEL_BRANCH_URL`),VERCEL_PROJECT_PRODUCTION_URL:d(e,`VERCEL_PROJECT_PRODUCTION_URL`),VERCEL_REGION:d(e,`VERCEL_REGION`),VERCEL_DEPLOYMENT_ID:d(e,`VERCEL_DEPLOYMENT_ID`),VERCEL_SKEW_PROTECTION_ENABLED:d(e,`VERCEL_SKEW_PROTECTION_ENABLED`),VERCEL_AUTOMATION_BYPASS_SECRET:d(e,`VERCEL_AUTOMATION_BYPASS_SECRET`),VERCEL_GIT_PROVIDER:d(e,`VERCEL_GIT_PROVIDER`),VERCEL_GIT_REPO_SLUG:d(e,`VERCEL_GIT_REPO_SLUG`),VERCEL_GIT_REPO_OWNER:d(e,`VERCEL_GIT_REPO_OWNER`),VERCEL_GIT_REPO_ID:d(e,`VERCEL_GIT_REPO_ID`),VERCEL_GIT_COMMIT_REF:d(e,`VERCEL_GIT_COMMIT_REF`),VERCEL_GIT_COMMIT_SHA:d(e,`VERCEL_GIT_COMMIT_SHA`),VERCEL_GIT_COMMIT_MESSAGE:d(e,`VERCEL_GIT_COMMIT_MESSAGE`),VERCEL_GIT_COMMIT_AUTHOR_LOGIN:d(e,`VERCEL_GIT_COMMIT_AUTHOR_LOGIN`),VERCEL_GIT_COMMIT_AUTHOR_NAME:d(e,`VERCEL_GIT_COMMIT_AUTHOR_NAME`),VERCEL_GIT_PREVIOUS_SHA:d(e,`VERCEL_GIT_PREVIOUS_SHA`),VERCEL_GIT_PULL_REQUEST_ID:d(e,`VERCEL_GIT_PULL_REQUEST_ID`)}),d=(e,t)=>{let n=e[t];return n===``?void 0:n};0&&(t.exports={getEnv:u})})),r=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),i=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{waitUntil:()=>f}),t.exports=l(u);var d=r();let f=e=>{if(typeof e!=`object`||!e||typeof e.then!=`function`)throw TypeError(`waitUntil can only be called with a Promise, got ${typeof e}`);return(0,d.getContext)().waitUntil?.(e)};0&&(t.exports={waitUntil:f})})),a=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{next:()=>f,rewrite:()=>d}),t.exports=c(l);function u(e,t){if(e?.request?.headers){if(!(e.request.headers instanceof Headers))throw Error(`request.headers must be an instance of Headers`);let n=[];for(let[r,i]of e.request.headers)t.set(`x-middleware-request-`+r,i),n.push(r);t.set(`x-middleware-override-headers`,n.join(`,`))}}function d(e,t){let n=new Headers(t?.headers??{});return n.set(`x-middleware-rewrite`,String(e)),u(t,n),new Response(null,{...t,headers:n})}function f(e){let t=new Headers(e?.headers??{});return t.set(`x-middleware-next`,`1`),u(e,t),new Response(null,{...e,headers:t})}0&&(t.exports={next:f,rewrite:d})})),o=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{InMemoryCache:()=>u}),t.exports=c(l);var u=class{constructor(){this.cache={}}async get(e){let t=this.cache[e];return t?t.ttl&&t.lastModified+t.ttl*1e3<Date.now()?(await this.delete(e),null):JSON.parse(t.value):null}async set(e,t,n){let r=JSON.stringify(t??null);this.cache[e]={value:r,lastModified:Date.now(),ttl:n?.ttl,tags:new Set(n?.tags||[])}}async delete(e){delete this.cache[e]}async expireTag(e){let t=Array.isArray(e)?e:[e];for(let e in this.cache)if(Object.prototype.hasOwnProperty.call(this.cache,e)){let n=this.cache[e];t.some(e=>n.tags.has(e))&&delete this.cache[e]}}};0&&(t.exports={InMemoryCache:u})})),s=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},l=e=>s(n({},`__esModule`,{value:!0}),e),u={};o(u,{BuildCache:()=>f}),t.exports=l(u);var d=c(),f=class{constructor({endpoint:e,headers:t,onError:n,timeout:r=500}){this.get=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let r=await fetch(`${this.endpoint}${e}`,{headers:this.headers,method:`GET`,signal:t.signal});if(r.status===404)return clearTimeout(n),null;if(r.status===200){if(r.headers.get(d.HEADERS_VERCEL_CACHE_STATE)!==d.PkgCacheState.Fresh)return r.body?.cancel?.(),clearTimeout(n),null;let e=await r.json();return clearTimeout(n),e}else throw clearTimeout(n),Error(`Failed to get cache: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e);return null}},this.set=async(e,t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeout);try{let a={};n?.ttl&&(a[d.HEADERS_VERCEL_REVALIDATE]=n.ttl.toString()),n?.tags&&n.tags.length>0&&(a[d.HEADERS_VERCEL_CACHE_TAGS]=n.tags.join(`,`)),n?.name&&(a[d.HEADERS_VERCEL_CACHE_ITEM_NAME]=n.name);let o=await fetch(`${this.endpoint}${e}`,{method:`POST`,headers:{...this.headers,...a},body:JSON.stringify(t),signal:r.signal});if(clearTimeout(i),o.status!==200)throw Error(`Failed to set cache: ${o.status} ${o.statusText}`)}catch(e){if(clearTimeout(i),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.delete=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let r=await fetch(`${this.endpoint}${e}`,{method:`DELETE`,headers:this.headers,signal:t.signal});if(clearTimeout(n),r.status!==200)throw Error(`Failed to delete cache: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.expireTag=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{Array.isArray(e)&&(e=e.join(`,`));let r=await fetch(`${this.endpoint}revalidate?tags=${e}`,{method:`POST`,headers:this.headers,signal:t.signal});if(clearTimeout(n),r.status!==200)throw Error(`Failed to revalidate tag: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.endpoint=e,this.headers=t,this.onError=n,this.timeout=r}};0&&(t.exports={BuildCache:f})})),c=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},u=(e,t,r,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of a(t))!c.call(e,s)&&s!==r&&n(e,s,{get:()=>t[s],enumerable:!(o=i(t,s))||o.enumerable});return e},d=e=>u(n({},`__esModule`,{value:!0}),e),f={};l(f,{HEADERS_VERCEL_CACHE_ITEM_NAME:()=>O,HEADERS_VERCEL_CACHE_STATE:()=>T,HEADERS_VERCEL_CACHE_TAGS:()=>D,HEADERS_VERCEL_REVALIDATE:()=>E,PkgCacheState:()=>w,getCache:()=>y}),t.exports=d(f);var p=r(),m=o(),h=s();let g=e=>{let t=5381;for(let n=0;n<e.length;n++)t=t*33^e.charCodeAt(n);return(t>>>0).toString(16)},_=null,v=null,y=e=>x(()=>{let e;return e=(0,p.getContext)().cache?(0,p.getContext)().cache:C(process.env.SUSPENSE_CACHE_DEBUG===`true`),e},b(e));function b(e){let t=e?.keyHashFunction||g;return n=>{if(!e?.namespace)return t(n);let r=e.namespaceSeparator||`$`;return`${e.namespace}${r}${t(n)}`}}function x(e,t){return{get:n=>e().get(t(n)),set:(n,r,i)=>e().set(t(n),r,{...i,name:i?.name??n}),delete:n=>e().delete(t(n)),expireTag:t=>e().expireTag(t)}}let S=!1;function C(e){if(_||=new m.InMemoryCache,process.env.RUNTIME_CACHE_DISABLE_BUILD_CACHE===`true`)return e&&console.log(`Using InMemoryCache as build cache is disabled`),_;let{RUNTIME_CACHE_ENDPOINT:t,RUNTIME_CACHE_HEADERS:n}=process.env;if(e&&console.log(`Runtime cache environment variables:`,{RUNTIME_CACHE_ENDPOINT:t,RUNTIME_CACHE_HEADERS:n}),!t||!n)return S||=(console.warn(`Runtime Cache unavailable in this environment. Falling back to in-memory cache.`),!0),_;if(!v){let e={};try{e=JSON.parse(n)}catch(e){return console.error(`Failed to parse RUNTIME_CACHE_HEADERS:`,e),_}let r=500;if(process.env.RUNTIME_CACHE_TIMEOUT){let e=parseInt(process.env.RUNTIME_CACHE_TIMEOUT,10);!isNaN(e)&&e>0?r=e:console.warn(`Invalid RUNTIME_CACHE_TIMEOUT value: "${process.env.RUNTIME_CACHE_TIMEOUT}". Using default: ${r}ms`)}v=new h.BuildCache({endpoint:t,headers:e,onError:e=>console.error(e),timeout:r})}return v}var w=(e=>(e.Fresh=`fresh`,e.Stale=`stale`,e.Expired=`expired`,e.NotFound=`notFound`,e.Error=`error`,e))(w||{});let T=`x-vercel-cache-state`,E=`x-vercel-revalidate`,D=`x-vercel-cache-tags`,O=`x-vercel-cache-item-name`;0&&(t.exports={HEADERS_VERCEL_CACHE_ITEM_NAME:O,HEADERS_VERCEL_CACHE_STATE:T,HEADERS_VERCEL_CACHE_TAGS:D,HEADERS_VERCEL_REVALIDATE:E,PkgCacheState:w,getCache:y})})),l=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{attachDatabasePool:()=>v,experimental_attachDatabasePool:()=>y}),t.exports=l(u);var d=r();let f=!!process.env.DEBUG;function p(e){if(`options`in e&&e.options){if(`idleTimeoutMillis`in e.options)return typeof e.options.idleTimeoutMillis==`number`?e.options.idleTimeoutMillis:1e4;if(`maxIdleTimeMS`in e.options)return typeof e.options.maxIdleTimeMS==`number`?e.options.maxIdleTimeMS:0;if(`status`in e)return 5e3;if(`connect`in e&&`execute`in e)return 3e4}if(`config`in e&&e.config){if(`connectionConfig`in e.config&&e.config.connectionConfig)return e.config.connectionConfig.idleTimeout||6e4;if(`idleTimeout`in e.config)return typeof e.config.idleTimeout==`number`?e.config.idleTimeout:6e4}return`poolTimeout`in e?typeof e.poolTimeout==`number`?e.poolTimeout:6e4:`idleTimeout`in e?typeof e.idleTimeout==`number`?e.idleTimeout:0:1e4}let m=null,h=()=>{},g=Date.now();function _(e){if(!process.env.VERCEL_URL||!process.env.VERCEL_REGION)return;m&&(clearTimeout(m),h());let t=new Promise(e=>{h=e}),n=Math.min(p(e)+100,Math.max(100,899e3-(Date.now()-g)));m=setTimeout(()=>{h?.(),f&&console.log(`Database pool idle timeout reached. Releasing connections.`)},n);let r=(0,d.getContext)();r?.waitUntil?r.waitUntil(t):console.warn(`Pool release event triggered outside of request scope.`)}function v(e){if(m&&(h?.(),clearTimeout(m)),`on`in e&&e.on&&`options`in e&&`idleTimeoutMillis`in e.options){e.on(`release`,()=>{f&&console.log(`Client released from pool`),_(e)});return}else if(`on`in e&&e.on&&`config`in e&&e.config&&`connectionConfig`in e.config){e.on(`release`,()=>{f&&console.log(`MySQL client released from pool`),_(e)});return}else if(`on`in e&&e.on&&`config`in e&&e.config&&`idleTimeout`in e.config){e.on(`release`,()=>{f&&console.log(`MySQL2/MariaDB client released from pool`),_(e)});return}if(`on`in e&&e.on&&`options`in e&&e.options&&`maxIdleTimeMS`in e.options){e.on(`connectionCheckedOut`,()=>{f&&console.log(`MongoDB connection checked out`),_(e)});return}if(`on`in e&&e.on&&`options`in e&&e.options&&`socket`in e.options){e.on(`end`,()=>{f&&console.log(`Redis connection ended`),_(e)});return}throw Error(`Unsupported database pool type`)}let y=v;0&&(t.exports={attachDatabasePool:v,experimental_attachDatabasePool:y})})),u=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{dangerouslyDeleteBySrcImage:()=>h,dangerouslyDeleteByTag:()=>p,invalidateBySrcImage:()=>m,invalidateByTag:()=>f}),t.exports=l(u);var d=r();let f=e=>{let t=(0,d.getContext)().purge;return t?t.invalidateByTag(e):Promise.resolve()},p=(e,t)=>{let n=(0,d.getContext)().purge;return n?n.dangerouslyDeleteByTag(e,t):Promise.resolve()},m=e=>{let t=(0,d.getContext)().purge;return t?t.invalidateBySrcImage(e):Promise.resolve()},h=(e,t)=>{let n=(0,d.getContext)().purge;return n?n.dangerouslyDeleteBySrcImage(e,t):Promise.resolve()};0&&(t.exports={dangerouslyDeleteBySrcImage:h,dangerouslyDeleteByTag:p,invalidateBySrcImage:m,invalidateByTag:f})})),d=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{addCacheTag:()=>f}),t.exports=l(u);var d=r();let f=e=>{let t=(0,d.getContext)().addCacheTag;return t?t(e):Promise.resolve()};0&&(t.exports={addCacheTag:f})})),f=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{experimental_upgradeWebSocket:()=>p}),t.exports=l(u);var d=r();async function f(){try{return(await import(`./wrapper-6mlyNCCb.js`)).WebSocketServer}catch{throw Error(`The "ws" package is required for experimental_upgradeWebSocket(). Install it with: npm install ws`)}}async function p(e,t={}){let n=(0,d.getContext)();if(typeof n.upgradeWebSocket!=`function`)throw Error(`experimental_upgradeWebSocket is not available in the current runtime environment. This feature requires a Vercel runtime that supports WebSocket upgrades.`);let r=await f(),{req:i,socket:a,head:o}=n.upgradeWebSocket(),s=new r({noServer:!0,maxPayload:t.maxPayload??262144}),c=await new Promise((e,t)=>{let n=()=>{a.removeListener(`error`,l),a.removeListener(`close`,u)},r=e=>{if(n(),e instanceof Error){t(e);return}let r=Error(`WebSocket upgrade failed`);r.cause=e,t(r)},c=t=>{n(),e(t)},l=e=>r(e),u=()=>r(Error(`socket closed before the WebSocket upgrade completed`));a.once(`error`,l),a.once(`close`,u);try{s.handleUpgrade(i,a,o,c)}catch(e){r(e)}});try{await e(c)}catch(e){throw c.close(1011,`WebSocket handler failed`),e}return new Response(null,{status:204})}0&&(t.exports={experimental_upgradeWebSocket:p})})),p=e(((e,r)=>{var o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,p=Object.getOwnPropertyNames,m=Object.prototype.hasOwnProperty,h=(e,t)=>{for(var n in t)o(e,n,{get:t[n],enumerable:!0})},g=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of p(t))!m.call(e,i)&&i!==n&&o(e,i,{get:()=>t[i],enumerable:!(r=s(t,i))||r.enumerable});return e},_=e=>g(o({},`__esModule`,{value:!0}),e),v={};h(v,{addCacheTag:()=>E.addCacheTag,attachDatabasePool:()=>w.attachDatabasePool,dangerouslyDeleteBySrcImage:()=>T.dangerouslyDeleteBySrcImage,dangerouslyDeleteByTag:()=>T.dangerouslyDeleteByTag,experimental_attachDatabasePool:()=>w.experimental_attachDatabasePool,experimental_upgradeWebSocket:()=>D.experimental_upgradeWebSocket,geolocation:()=>y.geolocation,getCache:()=>C.getCache,getEnv:()=>b.getEnv,invalidateBySrcImage:()=>T.invalidateBySrcImage,invalidateByTag:()=>T.invalidateByTag,ipAddress:()=>y.ipAddress,next:()=>S.next,rewrite:()=>S.rewrite,waitUntil:()=>x.waitUntil}),r.exports=_(v);var y=t(),b=n(),x=i(),S=a(),C=c(),w=l(),T=u(),E=d(),D=f();0&&(r.exports={addCacheTag,attachDatabasePool,dangerouslyDeleteBySrcImage,dangerouslyDeleteByTag,experimental_attachDatabasePool,experimental_upgradeWebSocket,geolocation,getCache,getEnv,invalidateBySrcImage,invalidateByTag,ipAddress,next,rewrite,waitUntil})}));export default p();export{};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-DaDcL9Zw.js";import{An as t,D as n,J as r,Mn as i,P as a,Sn as o,Un as s,Yn as c,a as l,en as u,ft as d,gt as f,it as p,ln as m,mt as h,n as g,nt as _,pt as v,t as y,x as b,xn as x,y as ee,yn as S}from"./wait-until-DoW76jdb.js";import{E as C,d as w,n as T,o as E,r as D}from"./dist-dNxTT6nO.js";import{j as O,o as k}from"./dist-D5bR13zs.js";import{t as A}from"./spec-version-C0hBsfu-.js";var j=e({getHookByToken:()=>R,resumeHook:()=>z,resumeWebhook:()=>V});const M=k();async function N(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function P(e){let t=e.executionContext?.workflowCoreVersion,n=e.executionContext?.traceCarrier,r=e.executionContext?.hookResumeInputVersion;return{deploymentId:e.deploymentId,workflowName:e.workflowName,runSpecVersion:e.specVersion,workflowCoreVersion:typeof t==`string`?t:void 0,traceCarrier:n&&typeof n==`object`?n:void 0,encryptionPublicKey:e.encryptionPublicKey,hookResumeInputVersion:typeof r==`number`?r:void 0}}async function F(e){if(e.resumeContext)return{resumeContext:e.resumeContext,source:`hook`};let t=await(await i()).runs.get(e.runId);return{resumeContext:P(t),source:`run_fallback`,run:t}}async function I(e,t){let n=await i(),r=t.run?await n.getEncryptionKeyForRun?.(t.run):await n.getEncryptionKeyForRun?.(e.runId,{deploymentId:t.resumeContext.deploymentId});return r?await c(r):void 0}async function L(e){let t=await i(),n=await t.hooks.getByToken(e),r;if(n.metadata!==void 0){let e=await F(n),i=e.run?await t.getEncryptionKeyForRun?.(e.run):await t.getEncryptionKeyForRun?.(n.runId,{deploymentId:e.resumeContext.deploymentId});r=i?await S(i):void 0,n.metadata=await a(n.metadata,n.runId,r)}return{hook:n,encryptionKey:r}}async function R(e){let{hook:t}=await L(e);return t}async function z(e,t,n){return B(e,t,n,!1)}async function B(e,a,s,c){return await g(()=>p(`hook.resume`,async p=>{let g=await i();try{let i=typeof e==`string`,d=i?await g.hooks.getByToken(e):e,S=i||c,C=await F(d),{resumeContext:T}=C;if(p?.setAttributes({...f(d.token),...v(d.hookId),...m(d.runId),"workflow.hook.resume_context_source":C.source}),C.run&&O(C.run.status))throw new E(d.token);let k=b(T.workflowCoreVersion),j,P=s?void 0:t(T.encryptionPublicKey);if(P)j=x(P);else{let e=s??await I(d,C);k.supportedFormats.has(o.ENCRYPTED)||(e=void 0),j=e}let L=(T.runSpecVersion??0)>=5&&k.supportedFormats.has(o.GZIP),R=[],z=A(d.specVersion),B=await n(a,d.runId,j,R,globalThis,z,k.framedByteStreams,L);y(Promise.all(R),e=>{e!==void 0&&r.warn(`Background flush of hook payload ops failed`,{workflowRunId:d.runId,hookId:d.hookId,error:e instanceof Error?e.message:String(e)})}),p?.setAttributes({...u(T.workflowName)});let V=await _(T.traceCarrier);V&&p?.addLink?.(V);let H={...z?{}:{token:d.token},payload:B},U=l(T.workflowName),W={deploymentId:T.deploymentId,specVersion:T.runSpecVersion??1},G=process.env.WORKFLOW_DISABLE_LAZY_HOOK_RESUME===`1`,K=(S?d.resumeCapabilities?.hookResumeDedupVersion??0:0)>=1||g.capabilities?.hookResumeDedup===!0,q=G?`disabled`:K?(T.hookResumeInputVersion??0)<1?`consumer_unsupported`:z?`legacy`:(T.runSpecVersion??0)<3?`non_cbor_transport`:B instanceof Uint8Array?B.byteLength>131072?`oversized`:null:`non_bytes`:`backend_unsupported`,J=q===null;p?.setAttributes({"workflow.hook.resume_strategy":J?`parallel`:`sequential`,...q?{"workflow.hook.resume_fallback_reason":q}:{}});let te=e=>E.is(e)||D.is(e)||w.is(e);if(!J){try{await g.events.create(d.runId,{eventType:`hook_received`,specVersion:5,correlationId:d.hookId,eventData:H},{v1Compat:z})}catch(e){throw te(e)?new E(d.token):e}return await g.queue(U,{runId:d.runId,traceCarrier:T.traceCarrier??void 0},W),d}let Y=M(),X=await N(B);p?.setAttributes({"workflow.hook.resume_id":Y});let[Z,Q]=await Promise.allSettled([g.events.create(d.runId,{eventType:`hook_received`,specVersion:5,correlationId:d.hookId,eventData:H},{v1Compat:z,resumeId:Y,resumePayloadDigest:X}),g.queue(U,{runId:d.runId,traceCarrier:T.traceCarrier??void 0,hookInput:{resumeId:Y,hookId:d.hookId,token:d.token,payload:B,payloadDigest:X}},W)]);if(Q.status===`rejected`)throw Q.reason;let $=!1;if(Z.status===`rejected`){let e=Z.reason;if(E.is(e)||w.is(e))throw new E(d.token);if(D.is(e)||ee(e))$=!0,p?.setAttributes({...h(!0),"workflow.hook.resume_event_write_recovered":!0,"workflow.hook.resume_event_write_error":e instanceof Error?e.name:`unknown`}),r.warn(`Hook resume event write failed, but the run was re-triggered via the queue. The hook_received event will be ensured by the queue consumer.`,{workflowRunId:d.runId,hookId:d.hookId,resumeId:Y,error:e instanceof Error?e.message:String(e)});else throw e}return $?{...d,resilientResume:!0}:d}catch(t){throw p?.setAttributes({...f(typeof e==`string`?e:e.token),...d(!1)}),t}}))}async function V(e,t){let{hook:n,encryptionKey:r}=await L(e);if(n.isWebhook===!1)throw new E(e);let i,a;if(n.metadata&&typeof n.metadata==`object`&&`respondWith`in n.metadata)if(n.metadata.respondWith===`manual`){let{readable:e,writable:n}=new TransformStream;a=e,t[s]=n}else if(n.metadata.respondWith instanceof Response)i=n.metadata.respondWith;else throw new C(`Invalid \`respondWith\` value: ${n.metadata.respondWith}`,{slug:T.WEBHOOK_INVALID_RESPOND_WITH_VALUE});else i=new Response(null,{status:202});if(await B(n,t,r,!0),a){let e=a.getReader(),t=await e.read();t.value&&(i=t.value),e.cancel()}if(!i)throw new C(`Workflow run did not send a response`,{slug:T.WEBHOOK_RESPONSE_NOT_SENT});return i}export{j as i,z as n,V as r,R as t};
@@ -1 +0,0 @@
1
- import{An as e,Dn as t,En as n,J as r,K as i,L as a,Mn as o,N as s,Nn as c,O as l,R as u,Sn as d,Yn as f,_ as ee,a as p,en as te,it as m,j as h,jn as ne,kn as re,ln as ie,n as g,q as _,qt as v,rr as y,rt as b,s as x,st as S,t as C,tn as ae,un as oe,x as se,xn as ce,y as le,yn as w}from"./wait-until-DoW76jdb.js";import{C as T,E,S as D,T as O,r as k,w as A}from"./dist-dNxTT6nO.js";import{t as j}from"./attribute-changes-DROfGk6l.js";import{G as M,K as N,i as P,o as F}from"./dist-D5bR13zs.js";import{t as I}from"./spec-version-C0hBsfu-.js";const L=F();function R(){let e=_.getStore(),t=e?.workflowMetadata?.workflowRunId;if(t)return{[N]:e.rootRunId??t,[M]:t}}let z=!1;async function B(t,n,i){"use step";return await g(()=>{let a=t?.workflowId;if(!a)throw new E(`'start' received an invalid workflow function. Ensure the Workflow SDK is configured correctly and the function includes a 'use workflow' directive.`,{slug:`start-invalid-workflow-function`});return m(`workflow.start ${y(a)}`,async t=>{t?.setAttributes({...te(a),...ae(`start`)});let s=[],u=i??{};Array.isArray(n)?s=n:typeof n==`object`&&(u=n),t?.setAttributes({...v(s.length)});let m=u.world??await o();c(m);let h=await m.getDeploymentId(),g=u.deploymentId??h;g===`latest`&&(m.resolveLatestDeploymentId?g=await m.resolveLatestDeploymentId():(z||(z=!0,r.warn(`deploymentId: 'latest' has no effect in this world and was ignored. It is only supported by worlds with atomic deployments, such as Vercel. The run will target the current deployment.`,{currentDeploymentId:h})),g=h));let _=`wrun_${m.createRunId?m.createRunId(u):L()}`,y,w,T,D;if(g===h)y=!0,w=!0,T=1;else if(typeof m.streams?.get!=`function`)y=!1,w=!1,T=void 0;else{let e=await x(m,{deploymentId:g,runId:_,timeout:2e3,namespace:u.namespace}).catch(()=>void 0);D=e?.encryptionPublicKey;let t=se(e?.workflowCoreVersion);y=t.framedByteStreams,w=t.supportedFormats.has(d.GZIP),T=e?.hookResumeInputVersion}let O=[],A=await b(),M=u.specVersion??m.specVersion,N=I(M),F=u.allowReservedAttributes===!0,B;if(u.attributes&&Object.keys(u.attributes).length>0){if(M<4)throw new E(`Initial workflow attributes require a World that supports spec version 4 or later.`);for(let[e,t]of Object.entries(u.attributes))if(typeof t!=`string`)throw new E(`Initial workflow attribute ${JSON.stringify(e)} must be a string value.`);let e=j(u.attributes,{allowReservedAttributes:F});B=Object.fromEntries(e.map(({key:e,value:t})=>[e,t]))}let V=M>=4?R():void 0,H=V?{...V,...B}:B,U=H?{attributes:H,...F||V!=null?{allowReservedAttributes:!0}:{}}:{};if(u.replayedFromRunId!==void 0&&!P.safeParse(u.replayedFromRunId).success)throw new E(`replayedFromRunId must be a run ID (wrun_<ulid>); received ${JSON.stringify(String(u.replayedFromRunId).slice(0,64))}.`);let W=e(D),G,K;if(W)G=ce(W),K=D;else{let e=await m.getEncryptionKeyForRun?.(_,{...u,deploymentId:g});G=e?await f(e):void 0,K=e?re((await ne(e)).publicKey):void 0}let q=await l(s,_,G,O,globalThis,N,y,w&&M>=5),Y=m.getEnvironment?.(),X={traceCarrier:A,workflowCoreVersion:ee,features:{encryption:!!G},...T===void 0?{}:{hookResumeInputVersion:T},...u.replayedFromRunId?{replayedFromRunId:u.replayedFromRunId}:{}},[Z,Q]=await Promise.allSettled([m.events.create(_,{eventType:`run_created`,specVersion:M,eventData:{deploymentId:g,workflowName:a,input:q,executionContext:X,...K?{encryptionPublicKey:K}:{},...U}},{v1Compat:N}),m.queue(p(a,u.namespace),{runId:_,traceCarrier:A,...M>=3?{runInput:{input:q,deploymentId:g,workflowName:a,specVersion:M,executionContext:X,...K?{encryptionPublicKey:K}:{},...Y===void 0?{}:{environment:Y},...U}}:{}},{deploymentId:g,specVersion:M,...u.region===void 0?{}:{region:u.region}})]);if(Q.status===`rejected`)throw Q.reason;let $=!1;if(Z.status===`rejected`){let e=Z.reason;if(!k.is(e))if(le(e))$=!0,r.warn(`Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.`,{workflowRunId:_,error:e.message});else throw e}else{let e=Z.value;if(!e.run)throw new E(`Missing 'run' in server response for 'run_created' event`);if(!N&&e.run.runId!==_)throw new E(`Server returned different runId than requested: expected ${_}, got ${e.run.runId}`)}return C(Promise.all(O),e=>{r.warn(`Background flush of workflow argument streams failed`,{workflowRunId:_,error:e instanceof Error?e.message:String(e)})}),t?.setAttributes({...ie(_),...S(g),...Z.status===`fulfilled`&&Z.value.run?oe(Z.value.run.status):{}}),new J(_,{resilientStart:$})})})}const V=e=>Array.isArray(e)?e:[e];async function H(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),o=i?await w(i):void 0,s=V(await a(r.input,t,o,globalThis)),c=n.specVersion??r.specVersion??1,l=n.deploymentId??r.deploymentId;return(await B({workflowId:r.workflowName},s,{deploymentId:l,world:e,specVersion:c,replayedFromRunId:t,namespace:n.namespace})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function U(e,t,n){try{let r=(await e.runs.get(t,{resolveData:`none`})).specVersion??1,i=I(r),a={eventType:`run_cancelled`,specVersion:r,...n?.cancelReason===void 0?{}:{eventData:{cancelReason:n.cancelReason}}};await e.events.create(t,a,{v1Compat:i})}catch(e){throw Error(`Failed to cancel run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function W(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`});await e.queue(p(r.workflowName,n?.namespace),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function G(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`}),i=I(r.specVersion),a=[],o=null;do{let n=await e.events.list({runId:t,pagination:{limit:1e3,...o?{cursor:o}:{}},resolveData:`none`});a.push(...n.data),o=n.hasMore?n.cursor:null}while(o);let s=a.filter(e=>e.eventType===`wait_created`),c=new Set(a.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),l=s.filter(e=>!c.has(e.correlationId));if(n?.correlationIds&&n.correlationIds.length>0){let e=new Set(n.correlationIds);l=l.filter(t=>t.correlationId&&e.has(t.correlationId))}let u=[],d=0;for(let n of l){if(!n.correlationId)continue;let a=i?{eventType:`wait_completed`,correlationId:n.correlationId}:{eventType:`wait_completed`,correlationId:n.correlationId,specVersion:r.specVersion,eventData:{resumeAt:n.eventData.resumeAt}};try{await e.events.create(t,a,{v1Compat:i}),d++}catch(e){k.is(e)?d++:u.push(e instanceof Error?e:Error(String(e)))}}if(d>0&&await e.queue(p(r.workflowName,n?.namespace),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1}),u.length>0)throw AggregateError(u,`Failed to complete ${u.length}/${l.length} pending wait(s) for run ${t}`);return{stoppedCount:d}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function K(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw Error(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function q(e,t){try{return await e.streams.list(t)}catch(e){throw Error(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}var J=class e{static[t](e){return{runId:e.runId,resilientStart:e.#r}}static[n](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=o(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(){return this.#n||=(async()=>{let e=await this.#t,t=await e.runs.get(this.runId),n=await e.getEncryptionKeyForRun?.(t);return n?await w(n):void 0})(),this.#n}#a(){return()=>this.#i()}async wakeUp(e){"use step";return G(await this.#t,this.runId,e)}async cancel(e){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:5,...e?.cancelReason===void 0?{}:{eventData:{cancelReason:e.cancelReason}}})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(O.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.status))}get returnValue(){"use step";return this.#o()}get workflowName(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.completedAt))}get readable(){return this.getReadable()}getReadable(e={}){"use step";let{ops:t=[],global:n=globalThis,startIndex:r,namespace:a}=e,o=i(this.runId,a),s=this.#a(),c=h(n,t,this.runId,s).ReadableStream({name:o,startIndex:r}),l=this.#t,u=this.runId;return Object.assign(c,{getTailIndex:async()=>(await(await l).streams.getInfo(u,o)).tailIndex})}async#o(){let e=await this.#t,t=0,n=this.#r?3:0,r=[1e3,3e3,6e3];for(;;)try{let t=await e.runs.get(this.runId);if(t.status===`completed`){let e=await this.#i();return await u(t.output,this.runId,e)}if(t.status===`cancelled`)throw new D(this.runId);if(t.status===`failed`){let e=await this.#i(),n;try{n=await s(t.error,this.runId,e)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new T(this.runId,n,{errorCode:t.errorCode})}throw new A(this.runId,t.status)}catch(e){if(A.is(e)){await new Promise(e=>setTimeout(e,1e3));continue}if(O.is(e)&&t<n){let e=r[t];t++,await new Promise(t=>setTimeout(t,e));continue}throw e}}};function Y(e){return new J(e)}export{K as a,G as c,q as i,B as l,Y as n,H as o,U as r,W as s,J as t};
@@ -1 +0,0 @@
1
- import{qn as e}from"./wait-until-DoW76jdb.js";import{i as t}from"./attribute-changes-DROfGk6l.js";async function n(r){let i=globalThis[e];return i||t(`sleep()`,`https://workflow-sdk.dev/docs/api-reference/workflow/sleep`,n),i(r)}export{n as t};