@oomol-lab/open-flow 0.1.0-beta.75 → 0.1.0-beta.76

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 (125) hide show
  1. package/README.md +2 -1
  2. package/dist/browser/{ContentIcon-FCpKiwjp.js → ContentIcon-Cm1hbVzW.js} +2 -2
  3. package/dist/browser/{FlowCanvas-dzRBnlUT.js → FlowCanvas-NzKtla_c.js} +62 -62
  4. package/dist/browser/{createResourceDialog-BeYDdUl-.js → createResourceDialog-BgdedQqu.js} +3 -3
  5. package/dist/browser/{dialog-ZtpsFbl4.js → dialog-aSElFFw2.js} +49 -24
  6. package/dist/browser/{exportSvg-DqXw1yf-.js → exportSvg-Dcz4HTo_.js} +2 -2
  7. package/dist/browser/{flowChanges-b_5UobFj.js → flowChanges-NZyS7HSp.js} +207 -396
  8. package/dist/browser/{flowWorkspace-ItojZbO4.js → flowWorkspace-Bl0SDehy.js} +90 -13
  9. package/dist/browser/preview.css +515 -649
  10. package/dist/browser/preview.js +454 -545
  11. package/dist/browser/theme.css +114 -262
  12. package/dist/browser/{tooltip-wZJRB9oP.js → tooltip-3XMK9jkr.js} +1 -1
  13. package/dist/browser/{typeScriptSession-CSRwWmZm.js → typeScriptSession-C9sBGOKZ.js} +1 -1
  14. package/dist/browser/ui.css +354 -460
  15. package/dist/browser/ui.js +1 -1
  16. package/dist/browser/workbench.css +515 -649
  17. package/dist/browser/workbench.js +7 -7
  18. package/dist/browser/{workbenchSelect-M441Lz0d.js → workbenchSelect-DBGP7Y4Z.js} +2 -2
  19. package/dist/command/index.js +33 -35
  20. package/dist/common/authoring.d.ts +3 -3
  21. package/dist/common/authoringSchema.d.ts +3 -0
  22. package/dist/common/connector-proxy.d.ts +1 -1
  23. package/dist/common/control-api-conformance.js +197 -136
  24. package/dist/common/control-api.d.ts +3 -2
  25. package/dist/common/control-api.js +192 -131
  26. package/dist/common/control-requests.js +126 -24
  27. package/dist/common/cron-trigger.d.ts +2 -1
  28. package/dist/common/decision.d.ts +4 -4
  29. package/dist/common/decision.js +5 -2
  30. package/dist/common/engine-contract.d.ts +5 -1
  31. package/dist/common/event-source-definition.d.ts +1 -1
  32. package/dist/common/event-source-view.d.ts +22 -0
  33. package/dist/common/event-source.d.ts +1 -1
  34. package/dist/common/event-source.js +24 -65
  35. package/dist/common/event-sources.d.ts +0 -21
  36. package/dist/common/flow-authoring.js +40 -18
  37. package/dist/common/flow-change-schema.d.ts +9 -1
  38. package/dist/common/flow-change.d.ts +7 -201
  39. package/dist/common/flow-change.js +46 -22
  40. package/dist/common/flow-encoding.js +40 -20
  41. package/dist/common/flow-input-value.d.ts +1 -1
  42. package/dist/common/flow-model.d.ts +121 -0
  43. package/dist/common/flow-notifications.d.ts +1 -1
  44. package/dist/common/flow-retry.d.ts +2 -4
  45. package/dist/common/flow-semantics.js +83 -86
  46. package/dist/common/flow-workflowReferences.d.ts +8 -0
  47. package/dist/common/flowInspection.d.ts +1 -1
  48. package/dist/common/http-hosts.d.ts +6 -0
  49. package/dist/common/http-request.d.ts +13 -5
  50. package/dist/common/http-request.js +23 -5
  51. package/dist/common/integration-trigger.d.ts +2 -1
  52. package/dist/common/mcp.js +195 -134
  53. package/dist/common/openapi.d.ts +4 -4
  54. package/dist/common/openapi.js +4 -1
  55. package/dist/common/poll-trigger.d.ts +2 -1
  56. package/dist/common/runtime-contract.d.ts +23 -1
  57. package/dist/common/runtime-contract.js +604 -72
  58. package/dist/common/runtime-nodejs-compat.d.ts +44 -0
  59. package/dist/common/runtime-nodejs-compat.js +5870 -0
  60. package/dist/common/scheduler-checkpoint.d.ts +1 -1
  61. package/dist/common/scheduler-node-execution.d.ts +1 -1
  62. package/dist/common/scheduler.d.ts +1 -1
  63. package/dist/common/scheduler.js +25 -4
  64. package/dist/common/trigger-catalog.d.ts +1 -7
  65. package/dist/common/trigger-config-options.d.ts +1 -1
  66. package/dist/common/trigger-config.d.ts +1 -1
  67. package/dist/common/trigger-contract.d.ts +2 -1
  68. package/dist/common/trigger-localization.d.ts +8 -2
  69. package/dist/common/trigger-model.d.ts +101 -0
  70. package/dist/common/webhook-response.d.ts +1 -1
  71. package/dist/common/webhook-trigger.d.ts +3 -1
  72. package/dist/common/workflow.d.ts +3 -12
  73. package/dist/common/workflow.js +25 -23
  74. package/dist/index.d.ts +41 -14
  75. package/package.json +5 -1
  76. package/src/base/common/json.ts +1 -1
  77. package/src/connector/common/proxy.ts +1 -1
  78. package/src/control/common/api.ts +6 -5
  79. package/src/control/common/authoringSchema.ts +9 -2
  80. package/src/control/common/authoringTools.ts +1 -1
  81. package/src/control/common/conformance.ts +1 -1
  82. package/src/control/common/connectorDecoders.ts +1 -1
  83. package/src/control/common/eventSources.ts +2 -29
  84. package/src/control/common/triggerCatalog.ts +1 -8
  85. package/src/decision/common/decision.ts +15 -7
  86. package/src/event-source/common/definition.ts +1 -1
  87. package/src/event-source/common/index.ts +1 -1
  88. package/src/event-source/common/view.ts +20 -0
  89. package/src/execution/common/checkpoint.ts +1 -1
  90. package/src/execution/common/node-execution.ts +1 -1
  91. package/src/execution/common/scheduler.ts +1 -1
  92. package/src/flow/common/change.ts +58 -192
  93. package/src/flow/common/changeSchema.ts +29 -4
  94. package/src/flow/common/connectionUsage.ts +1 -1
  95. package/src/flow/common/inputValue.ts +1 -1
  96. package/src/flow/common/model.ts +130 -0
  97. package/src/flow/common/modules.ts +1 -1
  98. package/src/flow/common/portChanges.ts +1 -1
  99. package/src/flow/common/retry.ts +2 -4
  100. package/src/flow/common/semantics.ts +11 -4
  101. package/src/flow/common/webhookResponse.ts +1 -1
  102. package/src/flow/common/workflowReferences.ts +31 -0
  103. package/src/http/common/authBindings.ts +6 -9
  104. package/src/http/common/hosts.ts +13 -0
  105. package/src/http/common/httpRequest.ts +30 -15
  106. package/src/openapi/common/openapi.ts +9 -5
  107. package/src/{execution → runtime}/common/engineContract.ts +20 -15
  108. package/src/runtime/common/nodejsCompat.ts +275 -0
  109. package/src/runtime/common/nodejsGuest.generated.json +47 -0
  110. package/src/runtime/common/runtime.ts +1138 -0
  111. package/src/trigger/common/config.ts +1 -1
  112. package/src/trigger/common/configOptions.ts +1 -1
  113. package/src/trigger/common/contract.ts +2 -1
  114. package/src/trigger/common/cron.ts +2 -1
  115. package/src/trigger/common/integration.ts +2 -1
  116. package/src/trigger/common/model.ts +87 -0
  117. package/src/trigger/common/poll.ts +2 -1
  118. package/src/trigger/common/webhook.ts +3 -1
  119. package/src/trigger/providers/fieldDescriptions.ts +1 -1
  120. package/src/trigger/providers/localization.ts +9 -2
  121. package/src/trigger/providers/remote.ts +1 -1
  122. package/src/types/index.ts +44 -15
  123. package/src/workflow/common/workflow.ts +3 -44
  124. package/src/execution/common/runtime.ts +0 -563
  125. /package/src/{control → connector}/common/providerIconSprite.ts +0 -0
@@ -22,22 +22,25 @@ function dequal(foo, bar) {
22
22
  return foo !== foo && bar !== bar;
23
23
  }
24
24
  //#endregion
25
- //#region src/execution/common/engineContract.ts
26
- var currentEngineContract = "open-flow-engine/v8";
25
+ //#region src/runtime/common/engineContract.ts
26
+ /** v9 is a single contract: the Node compatibility builtins, `context.fetch`, and no `context.egress`. */
27
+ var currentEngineContract = "open-flow-engine/v9";
28
+ /** The published v8 Node compatibility contract, retained for existing Publications and Runs. */
27
29
  var nodejsEngineContract = "open-flow-engine/v8/nodejs-compat-v1";
28
- var currentContract = {
30
+ var platformSource = (contract) => `export const engineContract = ${JSON.stringify(contract)}
31
+ export function identity(value) { return value }
32
+ `;
33
+ var v8Contract = {
29
34
  workflowTools: true,
30
35
  httpRequests: true,
31
36
  waitAutoContinue: true,
32
37
  webhookResponses: true,
33
38
  platformExports: /* @__PURE__ */ new Set(["engineContract", "identity"]),
34
39
  platformModule: "open-flow:platform",
35
- platformSource: `export const engineContract = ${JSON.stringify(currentEngineContract)}
36
- export function identity(value) { return value }
37
- `
40
+ platformSource: platformSource("open-flow-engine/v8")
38
41
  };
39
42
  var nodejsContract = {
40
- ...currentContract,
43
+ ...v8Contract,
41
44
  builtinModules: new Set([
42
45
  "assert",
43
46
  "assert/strict",
@@ -64,32 +67,34 @@ var nodejsContract = {
64
67
  "util",
65
68
  "zlib"
66
69
  ].flatMap((name) => [name, `node:${name}`])),
67
- platformSource: `export const engineContract = ${JSON.stringify(nodejsEngineContract)}
68
- export function identity(value) { return value }
69
- `
70
+ platformSource: platformSource(nodejsEngineContract)
71
+ };
72
+ var currentContract = {
73
+ ...nodejsContract,
74
+ codeFetch: true,
75
+ platformSource: platformSource(currentEngineContract)
70
76
  };
71
77
  function findEngineContract(contract) {
72
- if (contract == "open-flow-engine/v8") return currentContract;
78
+ if (contract == "open-flow-engine/v9") return currentContract;
79
+ if (contract == "open-flow-engine/v8") return v8Contract;
73
80
  if (contract == "open-flow-engine/v8/nodejs-compat-v1") return nodejsContract;
74
81
  if (contract == "open-flow-engine/v7" || contract == "open-flow-engine/v7/nodejs-compat-v1") return {
75
- ...contract.endsWith("/nodejs-compat-v1") ? nodejsContract : currentContract,
82
+ ...contract.endsWith("/nodejs-compat-v1") ? nodejsContract : v8Contract,
76
83
  workflowTools: false,
77
84
  httpRequests: false,
78
- platformSource: `export const engineContract = ${JSON.stringify(contract)}\nexport function identity(value) { return value }\n`
85
+ platformSource: platformSource(contract)
79
86
  };
80
87
  if (contract == "open-flow-engine/v6" || contract == "open-flow-engine/v6/nodejs-compat-v1") return {
81
- ...contract == "open-flow-engine/v6" ? currentContract : nodejsContract,
88
+ ...contract == "open-flow-engine/v6" ? v8Contract : nodejsContract,
82
89
  workflowTools: false,
83
90
  httpRequests: false,
84
91
  waitAutoContinue: false,
85
92
  webhookResponses: false,
86
- platformSource: `export const engineContract = ${JSON.stringify(contract)}
87
- export function identity(value) { return value }
88
- `
93
+ platformSource: platformSource(contract)
89
94
  };
90
95
  }
91
96
  //#endregion
92
- //#region src/execution/common/runtime.ts
97
+ //#region src/runtime/common/runtime.ts
93
98
  /** Snapshot a Task result before JSON transport can discard or coerce invalid values. */
94
99
  function snapshotRuntimeResult(value) {
95
100
  const parents = /* @__PURE__ */ new Set();
@@ -105,18 +110,18 @@ function snapshotRuntimeResult(value) {
105
110
  };
106
111
  return value === void 0 ? void 0 : copy(value, 0);
107
112
  }
108
- var nodejsRuntimeConformanceCases = [{
109
- name: "supports Node builtin imports and asynchronous virtual file operations",
110
- async verify(harness) {
111
- equal(await harness.invoke({
112
- capability: async () => ({
113
- body: null,
114
- status: 403
115
- }),
116
- input: null,
117
- invocationId: "nodejs-files",
118
- program: {
119
- ...program(harness, `import assert from 'node:assert/strict';
113
+ var nodejsRuntimeConformanceCases = [
114
+ {
115
+ name: "supports Node builtin imports and asynchronous virtual file operations",
116
+ async verify(harness) {
117
+ equal(await harness.invoke({
118
+ capability: async () => ({
119
+ body: null,
120
+ status: 403
121
+ }),
122
+ input: null,
123
+ invocationId: "nodejs-files",
124
+ program: program(harness, `import assert from 'node:assert/strict';
120
125
  import { Buffer } from 'node:buffer'; import path from 'node:path'; import fs from 'node:fs/promises';
121
126
  export default async () => {
122
127
  const file = path.join('/tmp', 'conformance.txt');
@@ -125,26 +130,24 @@ export default async () => {
125
130
  assert.equal(text, '你好');
126
131
  await fs.unlink(file);
127
132
  return { text, bytes: Buffer.byteLength(text) };
128
- }`),
129
- engineContract: nodejsEngineContract
130
- }
131
- }), {
132
- text: "你好",
133
- bytes: 6
134
- }, "Node virtual files");
135
- }
136
- }, {
137
- name: "preserves abort reasons and cancels Promise timers",
138
- async verify(harness) {
139
- equal(await harness.invoke({
140
- capability: async () => ({
141
- body: null,
142
- status: 403
143
- }),
144
- input: null,
145
- invocationId: "nodejs-abort",
146
- program: {
147
- ...program(harness, `import { setTimeout } from 'node:timers/promises';
133
+ }`)
134
+ }), {
135
+ text: "你好",
136
+ bytes: 6
137
+ }, "Node virtual files");
138
+ }
139
+ },
140
+ {
141
+ name: "preserves abort reasons and cancels Promise timers",
142
+ async verify(harness) {
143
+ equal(await harness.invoke({
144
+ capability: async () => ({
145
+ body: null,
146
+ status: 403
147
+ }),
148
+ input: null,
149
+ invocationId: "nodejs-abort",
150
+ program: program(harness, `import { setTimeout } from 'node:timers/promises';
148
151
  export default async () => {
149
152
  const controller = new AbortController(); const reason = { message: 'stop' };
150
153
  const combined = AbortSignal.any([controller.signal]);
@@ -154,15 +157,216 @@ export default async () => {
154
157
  try { await pending; return false; } catch (error) {
155
158
  return { sameReason: combined.reason === reason && thrown === reason, name: error.name };
156
159
  }
157
- }`),
158
- engineContract: nodejsEngineContract
159
- }
160
- }), {
161
- sameReason: true,
162
- name: "AbortError"
163
- }, "Node cancellation");
160
+ }`)
161
+ }), {
162
+ sameReason: true,
163
+ name: "AbortError"
164
+ }, "Node cancellation");
165
+ }
166
+ },
167
+ nodejsCase("resolves prefixed and bare builtin names to the same module and shares globals with their modules", `import { Buffer } from 'node:buffer'; import bare from 'buffer'; import processModule from 'node:process';
168
+ import { URL as ImportedURL, URLSearchParams as ImportedParams } from 'node:url'; import { ReadableStream as ImportedStream } from 'node:stream/web';
169
+ export default () => ({ buffer: Buffer === bare.Buffer && Buffer === globalThis.Buffer, process: process === processModule,
170
+ url: URL === ImportedURL && URLSearchParams === ImportedParams, stream: ReadableStream === ImportedStream,
171
+ cwd: process.cwd(), env: Object.keys(process.env) })`, {
172
+ buffer: true,
173
+ process: true,
174
+ url: true,
175
+ stream: true,
176
+ cwd: "/tmp",
177
+ env: []
178
+ }),
179
+ nodejsCase("supports events, string decoding, paths, query strings, URLs and promisify", `import { EventEmitter } from 'node:events'; import { StringDecoder } from 'node:string_decoder'; import { Buffer } from 'node:buffer';
180
+ import path from 'node:path'; import qs from 'node:querystring'; import { promisify } from 'node:util';
181
+ export default async () => {
182
+ const emitter = new EventEmitter(); let count = 0; emitter.once('value', (x) => (count += x)); emitter.emit('value', 7); emitter.emit('value', 9);
183
+ const decoder = new StringDecoder('utf8'); const bytes = Buffer.from('你好');
184
+ const incremental = new TextDecoder(); const partial = incremental.decode(new Uint8Array([0xe4, 0xbd]), { stream: true });
185
+ const url = new URL('../文件?a=1', 'https://example.com/a/b'); url.searchParams.append('b', 'x y');
186
+ return { count, text: decoder.write(bytes.subarray(0, 2)) + decoder.end(bytes.subarray(2)), partial, rest: incremental.decode(new Uint8Array([0xa0])),
187
+ path: path.join('/tmp', 'a', '..', 'b'), query: qs.parse('a=1&a=2').a, url: url.href, canParse: URL.canParse('not a url'),
188
+ value: await promisify((callback) => callback(null, 42))() };
189
+ }`, {
190
+ count: 7,
191
+ text: "你好",
192
+ partial: "",
193
+ rest: "你",
194
+ path: "/tmp/b",
195
+ query: ["1", "2"],
196
+ url: "https://example.com/%E6%96%87%E4%BB%B6?a=1&b=x+y",
197
+ canParse: false,
198
+ value: 42
199
+ }),
200
+ nodejsCase("encodes Buffers and computes hashes, HMACs, gzip and random values", `import { Buffer } from 'node:buffer'; import { createHash, createHmac, randomBytes } from 'node:crypto'; import { gzipSync, gunzipSync, deflateRawSync, inflateRawSync } from 'node:zlib';
201
+ export default () => ({ hex: Buffer.from('你好').toString('hex'), base64: Buffer.from('abc').toString('base64'), latin1: Buffer.from([0xe9]).toString('latin1'),
202
+ utf16: Buffer.from('a', 'utf16le').length, hash: createHash('sha256').update('a').update('bc').digest('hex'),
203
+ md5: createHash('md5').update('abc').digest('base64'), hmac: createHmac('sha256', 'key').update('message').digest('hex'),
204
+ gzip: gunzipSync(gzipSync(Buffer.from('你好'))).toString(), raw: inflateRawSync(deflateRawSync('raw')).toString(),
205
+ random: randomBytes(12).length, uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(crypto.randomUUID()),
206
+ values: crypto.getRandomValues(new Uint8Array(4)).length })`, {
207
+ hex: "e4bda0e5a5bd",
208
+ base64: "YWJj",
209
+ latin1: "é",
210
+ utf16: 2,
211
+ hash: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
212
+ md5: "kAFQmDzST7DWlj99KOF/cg==",
213
+ hmac: "6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a",
214
+ gzip: "你好",
215
+ raw: "raw",
216
+ random: 12,
217
+ uuid: true,
218
+ values: 4
219
+ }),
220
+ nodejsCase("provides an invocation-local filesystem with Node error codes", `import fs from 'node:fs'; import fsp from 'node:fs/promises';
221
+ export default async () => {
222
+ await fsp.mkdir('/tmp/nested', { recursive: true });
223
+ fs.writeFileSync('/tmp/nested/data', '你好');
224
+ const handle = await fsp.open('/tmp/nested/data', 'r'); const data = await handle.readFile('utf8'); await handle.close();
225
+ await fsp.rename('/tmp/nested/data', '/tmp/nested/moved');
226
+ let missing; try { fs.readFileSync('/etc/passwd'); } catch (error) { missing = error.code; }
227
+ return { data, size: fs.statSync('/tmp/nested/moved').size, entries: fs.readdirSync('/tmp/nested'), missing };
228
+ }`, {
229
+ data: "你好",
230
+ size: 6,
231
+ entries: ["moved"],
232
+ missing: "ENOENT"
233
+ }),
234
+ nodejsCase("runs timers, Node streams, pipelines and Web Streams", `import { setTimeout as delay } from 'node:timers/promises'; import { Readable, Writable } from 'node:stream'; import { pipeline } from 'node:stream/promises';
235
+ export default async () => {
236
+ let count = 0; const timer = setInterval(() => { count++; clearInterval(timer) }, 1); const removed = setTimeout(() => { count += 100 }, 1); clearTimeout(removed);
237
+ await delay(10);
238
+ const data = []; for await (const chunk of Readable.from(['a', 'b'])) data.push(chunk);
239
+ let piped = ''; await pipeline(Readable.from(['x', 'y']), new Writable({ write(chunk, _encoding, callback) { piped += chunk.toString(); callback() } }));
240
+ const reader = new ReadableStream({ start(controller) { controller.enqueue('web'); controller.close() } }).getReader();
241
+ return { count, data, piped, web: (await reader.read()).value };
242
+ }`, {
243
+ count: 1,
244
+ data: ["a", "b"],
245
+ piped: "xy",
246
+ web: "web"
247
+ }),
248
+ nodejsCase("supports AbortSignal timeout and pre-aborted signals", `import { setTimeout as delay } from 'node:timers/promises';
249
+ export default async () => { const timeout = AbortSignal.timeout(1); await delay(10); return { timeout: timeout.reason.name, aborted: AbortSignal.abort().aborted } }`, {
250
+ timeout: "TimeoutError",
251
+ aborted: true
252
+ }),
253
+ nodejsCase("encodes and decodes text larger than one builtin transfer and creates many decoders", `export default () => {
254
+ const text = '你😀a'.repeat(400000); const bytes = new TextEncoder().encode(text);
255
+ const decoder = new TextDecoder(); let streamed = '';
256
+ for (let offset = 0; offset < bytes.length; offset += 1000003) streamed += decoder.decode(bytes.subarray(offset, offset + 1000003), { stream: true });
257
+ streamed += decoder.decode();
258
+ let decoded = 0; for (let index = 0; index < 300; index++) decoded += new TextDecoder().decode(new Uint8Array([0x61])).length;
259
+ return { bytes: bytes.length, whole: new TextDecoder().decode(bytes) === text, streamed: streamed === text, decoded };
260
+ }`, {
261
+ bytes: 32e5,
262
+ whole: true,
263
+ streamed: true,
264
+ decoded: 300
265
+ }),
266
+ {
267
+ name: "isolates files, globals and builtin module state between Task invocations",
268
+ async verify(harness) {
269
+ const invoke = async (invocationId, source) => await harness.invoke({
270
+ capability: async () => ({
271
+ body: null,
272
+ status: 403
273
+ }),
274
+ input: null,
275
+ invocationId,
276
+ program: program(harness, source)
277
+ });
278
+ await invoke("nodejs-isolation-write", `import fs from 'node:fs'; import crypto from 'node:crypto';
279
+ export default () => { fs.writeFileSync('/tmp/marker', 'x'); URL.prototype.taskMarker = true; crypto.constants.taskMarker = true; globalThis.taskMarker = true }`);
280
+ equal(await invoke("nodejs-isolation-read", `import fs from 'node:fs'; import crypto from 'node:crypto';
281
+ export default () => ({ file: fs.existsSync('/tmp/marker'), url: 'taskMarker' in URL.prototype, module: 'taskMarker' in crypto.constants, global: 'taskMarker' in globalThis })`), {
282
+ file: false,
283
+ url: false,
284
+ module: false,
285
+ global: false
286
+ }, "Task isolation");
287
+ }
164
288
  }
165
- }];
289
+ ];
290
+ /** Reference Artifact Host for the guest chunk protocol; deployments own storage, identity and limits. */
291
+ function artifactHost() {
292
+ const chunkBytes = 524288;
293
+ const uploads = /* @__PURE__ */ new Map();
294
+ const artifacts = /* @__PURE__ */ new Map();
295
+ const kinds = [];
296
+ let nextUpload = 0;
297
+ const capability = async (call) => {
298
+ kinds.push(call.kind);
299
+ const payload = call.payload;
300
+ if (call.kind == "artifact.write") {
301
+ const upload = typeof payload.upload == "string" ? payload.upload : `u${++nextUpload}`;
302
+ uploads.set(upload, [...uploads.get(upload) ?? [], decodeBase64(payload.data)]);
303
+ return {
304
+ body: { upload },
305
+ status: 200
306
+ };
307
+ }
308
+ if (call.kind == "artifact.put") {
309
+ const parts = [...typeof payload.upload == "string" ? uploads.get(payload.upload) ?? [] : [], decodeBase64(payload.data)];
310
+ const bytes = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
311
+ parts.reduce((offset, part) => (bytes.set(part, offset), offset + part.length), 0);
312
+ const id = `a${artifacts.size + 1}`;
313
+ artifacts.set(id, bytes);
314
+ return {
315
+ body: {
316
+ kind: "artifact",
317
+ id,
318
+ name: payload.name,
319
+ size: bytes.length,
320
+ digest: artifactDigest(id),
321
+ ...payload.mediaType == null ? {} : { mediaType: payload.mediaType }
322
+ },
323
+ status: 200
324
+ };
325
+ }
326
+ if (call.kind == "artifact.read") {
327
+ const bytes = artifacts.get(String(payload.id));
328
+ const offset = Number(payload.offset);
329
+ return {
330
+ body: {
331
+ data: encodeBase64(bytes.subarray(offset, offset + chunkBytes)),
332
+ size: bytes.length
333
+ },
334
+ status: 200
335
+ };
336
+ }
337
+ throw new Error(`Unexpected Capability ${call.kind}.`);
338
+ };
339
+ return {
340
+ capability,
341
+ digest: artifactDigest,
342
+ kinds: () => kinds
343
+ };
344
+ }
345
+ function decodeBase64(text) {
346
+ return Uint8Array.from(atob(String(text)), (character) => character.charCodeAt(0));
347
+ }
348
+ function encodeBase64(bytes) {
349
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
350
+ }
351
+ function artifactDigest(id) {
352
+ return `sha256:${id.slice(1).padStart(64, "0")}`;
353
+ }
354
+ function nodejsCase(name, source, expected) {
355
+ return {
356
+ name,
357
+ async verify(harness) {
358
+ equal(await harness.invoke({
359
+ capability: async () => ({
360
+ body: null,
361
+ status: 403
362
+ }),
363
+ input: null,
364
+ invocationId: `nodejs-${name}`,
365
+ program: program(harness, source)
366
+ }), expected, name);
367
+ }
368
+ };
369
+ }
166
370
  function program(harness, source, modules = {}) {
167
371
  return {
168
372
  engineContract: currentEngineContract,
@@ -359,8 +563,8 @@ export default (input) => ({ engineContract, value: identity(double(input.value)
359
563
  }),
360
564
  input: null,
361
565
  invocationId: "closed-linker",
362
- program: program(harness, `import fs from 'node:fs'
363
- export default () => fs.readFileSync('/etc/passwd', 'utf8')`)
566
+ program: program(harness, `import { execSync } from 'node:child_process'
567
+ export default () => execSync('cat /etc/passwd').toString()`)
364
568
  }), /invalid|unsupported|cannot import|not part of/i, "Closed linker");
365
569
  }
366
570
  },
@@ -369,6 +573,11 @@ export default () => fs.readFileSync('/etc/passwd', 'utf8')`)
369
573
  async verify(harness) {
370
574
  const calls = [];
371
575
  equal(await harness.invoke({
576
+ capabilities: [{
577
+ kind: "connector",
578
+ action: "example.read",
579
+ connections: []
580
+ }],
372
581
  capability: async (call) => {
373
582
  calls.push(call);
374
583
  return {
@@ -381,16 +590,13 @@ export default () => fs.readFileSync('/etc/passwd', 'utf8')`)
381
590
  },
382
591
  input: { issue: 42 },
383
592
  invocationId: "async-capability",
384
- program: program(harness, `export default async (input, capability) => capability.artifact.put({ action: 'read', input })`)
593
+ program: program(harness, `export default async (input, context) => context.actions.example.read(input)`)
385
594
  }), {
386
- body: {
387
- accepted: true,
388
- echoed: {
389
- action: "read",
390
- input: { issue: 42 }
391
- }
392
- },
393
- status: 200
595
+ accepted: true,
596
+ echoed: {
597
+ action: "example.read",
598
+ input: { issue: 42 }
599
+ }
394
600
  }, "Capability result");
395
601
  equal(calls.map(({ invocationId, kind, payload }) => ({
396
602
  invocationId,
@@ -398,14 +604,150 @@ export default () => fs.readFileSync('/etc/passwd', 'utf8')`)
398
604
  payload
399
605
  })), [{
400
606
  invocationId: "async-capability",
401
- kind: "artifact.put",
607
+ kind: "connector",
402
608
  payload: {
403
- action: "read",
609
+ action: "example.read",
404
610
  input: { issue: 42 }
405
611
  }
406
612
  }], "Capability request");
407
613
  }
408
614
  },
615
+ {
616
+ name: "stores and reads Artifacts through bounded chunks",
617
+ async verify(harness) {
618
+ const host = artifactHost();
619
+ const value = await harness.invoke({
620
+ capability: host.capability,
621
+ input: null,
622
+ invocationId: "artifact-roundtrip",
623
+ program: program(harness, `export default async (_input, context) => {
624
+ const large = new Uint8Array(1200 * 1024).map((_, index) => index % 251)
625
+ const text = await context.artifact.put('你好', { name: 'greeting.txt', mediaType: 'text/plain' })
626
+ const binary = await context.artifact.put(large, { name: 'data.bin' })
627
+ const empty = await context.artifact.put(new Uint8Array(0), { name: 'empty' })
628
+ const read = await context.artifact.open(binary)
629
+ return { text, binary, empty, greeting: new TextDecoder().decode(await context.artifact.open(text)),
630
+ same: read.length == large.length && read.every((byte, index) => byte == large[index]), emptyLength: (await context.artifact.open(empty)).length }
631
+ }`)
632
+ });
633
+ const ref = (id, name, size, mediaType) => ({
634
+ kind: "artifact",
635
+ id,
636
+ name,
637
+ size,
638
+ digest: host.digest(id),
639
+ ...mediaType == null ? {} : { mediaType }
640
+ });
641
+ equal(value, {
642
+ text: ref("a1", "greeting.txt", 6, "text/plain"),
643
+ binary: ref("a2", "data.bin", 1228800),
644
+ empty: ref("a3", "empty", 0),
645
+ greeting: "你好",
646
+ same: true,
647
+ emptyLength: 0
648
+ }, "Artifact roundtrip");
649
+ equal(host.kinds(), [
650
+ "artifact.put",
651
+ "artifact.write",
652
+ "artifact.write",
653
+ "artifact.put",
654
+ "artifact.put",
655
+ "artifact.read",
656
+ "artifact.read",
657
+ "artifact.read",
658
+ "artifact.read",
659
+ "artifact.read"
660
+ ], "Artifact chunks");
661
+ }
662
+ },
663
+ {
664
+ name: "rejects invalid Artifact arguments before Host dispatch",
665
+ async verify(harness) {
666
+ const host = artifactHost();
667
+ equal(await harness.invoke({
668
+ capability: host.capability,
669
+ input: null,
670
+ invocationId: "artifact-invalid",
671
+ program: program(harness, `export default async (_input, context) => {
672
+ const codes = []
673
+ for (const call of [() => context.artifact.put({}, { name: 'x' }), () => context.artifact.put('x', {}), () => context.artifact.put('x', { name: 'x', mediaType: 1 }), () => context.artifact.open({ id: 'a1' })]) {
674
+ try { await call() } catch (error) { codes.push(error.code) }
675
+ }
676
+ return codes
677
+ }`)
678
+ }), Array.from({ length: 4 }, () => "capability.invalid"), "Artifact validation");
679
+ equal(host.kinds(), [], "Artifact dispatch");
680
+ }
681
+ },
682
+ {
683
+ name: "calls declared HTTP hosts through context.fetch",
684
+ async verify(harness) {
685
+ const calls = [];
686
+ equal(await harness.invoke({
687
+ capability: async (call) => {
688
+ calls.push({
689
+ kind: call.kind,
690
+ payload: call.payload
691
+ });
692
+ return {
693
+ status: 200,
694
+ body: {
695
+ status: 201,
696
+ statusText: "Created",
697
+ url: "https://api.example.com/items?q=1",
698
+ headers: [
699
+ ["content-type", "application/json"],
700
+ ["x-tag", "a"],
701
+ ["x-tag", "b"]
702
+ ],
703
+ body: btoa("{\"id\":7}")
704
+ }
705
+ };
706
+ },
707
+ input: null,
708
+ invocationId: "code-fetch",
709
+ program: program(harness, `export default async (_input, context) => {
710
+ const response = await context.fetch(new URL('https://api.example.com/items?q=1'), { method: 'post', headers: [['X-Trace', '1']], body: '{"name":"a"}' })
711
+ const json = await response.json()
712
+ let reused; try { await response.text() } catch (error) { reused = error instanceof TypeError }
713
+ const codes = []
714
+ for (const call of [() => context.fetch('https://api.example.com', { method: 'TRACE' }), () => context.fetch('https://api.example.com', { body: 'x' }),
715
+ () => context.fetch('https://api.example.com', { method: 'POST', body: {} }), () => context.fetch('https://api.example.com', { headers: { 'bad header': 'x' } }),
716
+ () => context.fetch('https://api.example.com', { method: 'PUT', body: new Uint8Array(1024 * 1024 + 1) })]) {
717
+ try { await call() } catch (error) { codes.push(error.code) }
718
+ }
719
+ return { status: response.status, ok: response.ok, statusText: response.statusText, url: response.url, redirected: response.redirected, json, reused,
720
+ tag: response.headers.get('X-Tag'), has: response.headers.has('content-type'), names: [...response.headers.keys()], codes, egress: typeof context.egress }
721
+ }`)
722
+ }), {
723
+ status: 201,
724
+ ok: true,
725
+ statusText: "Created",
726
+ url: "https://api.example.com/items?q=1",
727
+ redirected: false,
728
+ json: { id: 7 },
729
+ reused: true,
730
+ tag: "a, b",
731
+ has: true,
732
+ names: [
733
+ "content-type",
734
+ "x-tag",
735
+ "x-tag"
736
+ ],
737
+ codes: Array.from({ length: 5 }, () => "capability.invalid"),
738
+ egress: "undefined"
739
+ }, "Fetch response");
740
+ equal(calls, [{
741
+ kind: "http.fetch",
742
+ payload: {
743
+ url: "https://api.example.com/items?q=1",
744
+ method: "POST",
745
+ headers: [["x-trace", "1"], ["content-type", "text/plain;charset=UTF-8"]],
746
+ body: btoa("{\"name\":\"a\"}")
747
+ }
748
+ }], "Fetch request");
749
+ }
750
+ },
409
751
  {
410
752
  name: "returns final outputs without exposing intermediate output capability",
411
753
  async verify(harness) {
@@ -555,6 +897,196 @@ function resolveAction(declarations, payload) {
555
897
  ...connectionId == null ? {} : { connectionId }
556
898
  };
557
899
  }
900
+ /**
901
+ * Serialized into the sandbox before the Capability helpers that use it; keep it self-contained. Encodes in guest
902
+ * JavaScript, because Node compatibility `atob`/`btoa` route through bounded Host primitives.
903
+ */
904
+ function createBase64() {
905
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
906
+ const values = (/* @__PURE__ */ new Uint8Array(128)).fill(255);
907
+ for (let index = 0; index < 64; index++) values[alphabet.charCodeAt(index)] = index;
908
+ return Object.freeze({
909
+ encode(bytes) {
910
+ const parts = [];
911
+ for (let start = 0; start < bytes.length; start += 24576) {
912
+ let text = "";
913
+ for (let index = start; index < Math.min(start + 24576, bytes.length); index += 3) {
914
+ const value = bytes[index] << 16 | (bytes[index + 1] ?? 0) << 8 | (bytes[index + 2] ?? 0);
915
+ text += alphabet[value >> 18] + alphabet[value >> 12 & 63] + (index + 1 < bytes.length ? alphabet[value >> 6 & 63] : "=") + (index + 2 < bytes.length ? alphabet[value & 63] : "=");
916
+ }
917
+ parts.push(text);
918
+ }
919
+ return parts.join("");
920
+ },
921
+ decode(text) {
922
+ if (typeof text != "string" || text.length % 4 != 0) throw new TypeError("Base64 content is invalid.");
923
+ const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
924
+ const bytes = new Uint8Array(text.length / 4 * 3 - padding);
925
+ for (let index = 0, offset = 0; index < text.length; index += 4) {
926
+ const digits = [
927
+ 0,
928
+ 1,
929
+ 2,
930
+ 3
931
+ ].map((position) => {
932
+ const code = text.charCodeAt(index + position);
933
+ if (code == 61 && index + position >= text.length - padding) return 0;
934
+ const value = code < 128 ? values[code] : 255;
935
+ if (value == 255) throw new TypeError("Base64 content is invalid.");
936
+ return value;
937
+ });
938
+ const value = digits[0] << 18 | digits[1] << 12 | digits[2] << 6 | digits[3];
939
+ if (offset < bytes.length) bytes[offset++] = value >> 16;
940
+ if (offset < bytes.length) bytes[offset++] = value >> 8 & 255;
941
+ if (offset < bytes.length) bytes[offset++] = value & 255;
942
+ }
943
+ return bytes;
944
+ }
945
+ });
946
+ }
947
+ /**
948
+ * Serialized into the sandbox; keep it self-contained. Transfers bytes as base64 chunks through
949
+ * `artifact.write`, `artifact.put` and `artifact.read` so each Capability message stays bounded.
950
+ */
951
+ function createArtifacts(invoke, { decode, encode } = createBase64()) {
952
+ const chunkBytes = 524288;
953
+ const invalid = (message) => Object.assign(new TypeError(message), { code: "capability.invalid" });
954
+ return Object.freeze({
955
+ async put(data, options) {
956
+ const settings = options;
957
+ if (settings == null || typeof settings != "object" || typeof settings.name != "string" || settings.name.length == 0) throw invalid("Artifact name is required.");
958
+ if (settings.mediaType !== void 0 && typeof settings.mediaType != "string") throw invalid("Artifact mediaType must be a string.");
959
+ const bytes = typeof data == "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : void 0;
960
+ if (bytes == null) throw invalid("Artifact data must be a string or Uint8Array.");
961
+ const tail = bytes.length == 0 ? 0 : Math.floor((bytes.length - 1) / chunkBytes) * chunkBytes;
962
+ let upload;
963
+ for (let offset = 0; offset < tail; offset += chunkBytes) upload = (await invoke("artifact.write", {
964
+ ...upload === void 0 ? {} : { upload },
965
+ data: encode(bytes.subarray(offset, offset + chunkBytes))
966
+ })).body?.upload;
967
+ return (await invoke("artifact.put", {
968
+ ...upload === void 0 ? {} : { upload },
969
+ name: settings.name,
970
+ ...settings.mediaType === void 0 ? {} : { mediaType: settings.mediaType },
971
+ data: encode(bytes.subarray(tail))
972
+ })).body;
973
+ },
974
+ async open(ref) {
975
+ const artifact = ref;
976
+ if (artifact == null || typeof artifact != "object" || artifact.kind != "artifact" || typeof artifact.id != "string") throw invalid("An ArtifactRef is required.");
977
+ const parts = [];
978
+ let offset = 0;
979
+ let size = 0;
980
+ do {
981
+ const body = (await invoke("artifact.read", {
982
+ id: artifact.id,
983
+ offset
984
+ })).body;
985
+ const part = decode(body?.data);
986
+ if (typeof body?.size != "number" || !Number.isSafeInteger(body.size) || part.length == 0 && offset < body.size) throw new TypeError("Artifact content is invalid.");
987
+ size = body.size;
988
+ parts.push(part);
989
+ offset += part.length;
990
+ } while (offset < size);
991
+ const bytes = new Uint8Array(offset);
992
+ let position = 0;
993
+ for (const part of parts) {
994
+ bytes.set(part, position);
995
+ position += part.length;
996
+ }
997
+ return bytes;
998
+ }
999
+ });
1000
+ }
1001
+ /**
1002
+ * Serialized into the sandbox; keep it self-contained. `context.fetch` sends one `http.fetch` Capability call per request.
1003
+ * The Host authorizes the URL against the node's `http` Capability, does not follow redirects and adds no credentials.
1004
+ * Request and response bodies are limited to 1 MiB; the response is a read-only subset of the Fetch `Response`.
1005
+ */
1006
+ function createFetch(invoke, { decode, encode } = createBase64()) {
1007
+ const maximumBytes = 1048576;
1008
+ const methods = /* @__PURE__ */ new Set([
1009
+ "GET",
1010
+ "HEAD",
1011
+ "POST",
1012
+ "PUT",
1013
+ "PATCH",
1014
+ "DELETE",
1015
+ "OPTIONS"
1016
+ ]);
1017
+ const invalid = (message) => Object.assign(new TypeError(message), { code: "capability.invalid" });
1018
+ const headerList = (value) => {
1019
+ if (value == null) return [];
1020
+ const pairs = typeof value[Symbol.iterator] == "function" ? Array.from(value, (pair) => {
1021
+ if (!Array.isArray(pair) || pair.length != 2) throw invalid("Headers must be name/value pairs.");
1022
+ return pair;
1023
+ }) : typeof value == "object" ? Object.entries(value) : void 0;
1024
+ if (pairs == null) throw invalid("Headers must be an object or name/value pairs.");
1025
+ return pairs.map(([name, text]) => {
1026
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(String(name))) throw invalid(`Invalid header name "${String(name)}".`);
1027
+ return [String(name).toLowerCase(), String(text)];
1028
+ });
1029
+ };
1030
+ return async function fetch(input, init = {}) {
1031
+ const options = init ?? {};
1032
+ if (typeof options != "object") throw invalid("Fetch options must be an object.");
1033
+ const url = String(input instanceof Object && "href" in input ? input.href : input);
1034
+ const method = String(options.method ?? "GET").toUpperCase();
1035
+ if (!methods.has(method)) throw invalid(`Unsupported HTTP method "${method}".`);
1036
+ const headers = headerList(options.headers);
1037
+ const body = options.body == null ? void 0 : typeof options.body == "string" ? new TextEncoder().encode(options.body) : options.body instanceof Uint8Array ? options.body : options.body instanceof ArrayBuffer ? new Uint8Array(options.body) : void 0;
1038
+ if (options.body != null && body == null) throw invalid("Fetch body must be a string, Uint8Array or ArrayBuffer.");
1039
+ if (body != null && (method == "GET" || method == "HEAD")) throw invalid(`A ${method} request cannot have a body.`);
1040
+ if (body != null && body.length > maximumBytes) throw invalid("Fetch request body exceeds 1 MiB.");
1041
+ if (typeof options.body == "string" && !headers.some(([name]) => name == "content-type")) headers.push(["content-type", "text/plain;charset=UTF-8"]);
1042
+ const signal = options.signal;
1043
+ if (signal?.aborted) throw signal.reason;
1044
+ const request = invoke("http.fetch", {
1045
+ url,
1046
+ method,
1047
+ headers,
1048
+ ...body == null ? {} : { body: encode(body) }
1049
+ });
1050
+ const result = (signal?.addEventListener == null ? await request : await Promise.race([request, new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }))])).body;
1051
+ if (result == null || typeof result.status != "number" || typeof result.url != "string" || typeof result.body != "string" || !Array.isArray(result.headers) || result.headers.some((pair) => !Array.isArray(pair) || typeof pair[0] != "string" || typeof pair[1] != "string")) throw new TypeError("The HTTP response is invalid.");
1052
+ const status = result.status;
1053
+ const entries = result.headers;
1054
+ const content = decode(result.body);
1055
+ let used = false;
1056
+ const consume = () => {
1057
+ if (used) throw new TypeError("Response body has already been used.");
1058
+ used = true;
1059
+ return content.slice();
1060
+ };
1061
+ const responseHeaders = Object.freeze({
1062
+ get: (name) => {
1063
+ const values = entries.filter(([key]) => key == String(name).toLowerCase()).map(([, value]) => value);
1064
+ return values.length == 0 ? null : values.join(", ");
1065
+ },
1066
+ has: (name) => entries.some(([key]) => key == String(name).toLowerCase()),
1067
+ entries: () => entries.map(([name, value]) => [name, value])[Symbol.iterator](),
1068
+ keys: () => entries.map(([name]) => name)[Symbol.iterator](),
1069
+ values: () => entries.map(([, value]) => value)[Symbol.iterator](),
1070
+ forEach: (callback) => entries.forEach(([name, value]) => callback(value, name)),
1071
+ [Symbol.iterator]: () => entries.map(([name, value]) => [name, value])[Symbol.iterator]()
1072
+ });
1073
+ return Object.freeze({
1074
+ status,
1075
+ statusText: typeof result.statusText == "string" ? result.statusText : "",
1076
+ ok: status >= 200 && status < 300,
1077
+ redirected: false,
1078
+ url: result.url,
1079
+ headers: responseHeaders,
1080
+ get bodyUsed() {
1081
+ return used;
1082
+ },
1083
+ bytes: async () => consume(),
1084
+ arrayBuffer: async () => consume().buffer,
1085
+ text: async () => new TextDecoder().decode(consume()),
1086
+ json: async () => JSON.parse(new TextDecoder().decode(consume()))
1087
+ });
1088
+ };
1089
+ }
558
1090
  /** Serialized into the sandbox alongside the strict JSON snapshot helper. */
559
1091
  function createWorkflows(invoke) {
560
1092
  return Object.freeze({ async call(name, input = {}) {
@@ -566,4 +1098,4 @@ function createWorkflows(invoke) {
566
1098
  } });
567
1099
  }
568
1100
  //#endregion
569
- export { createActions, createWorkflows, currentEngineContract, findEngineContract, nodejsEngineContract, nodejsRuntimeConformanceCases, resolveAction, runtimeConformanceCases, snapshotRuntimeResult };
1101
+ export { createActions, createArtifacts, createBase64, createFetch, createWorkflows, currentEngineContract, findEngineContract, nodejsEngineContract, nodejsRuntimeConformanceCases, resolveAction, runtimeConformanceCases, snapshotRuntimeResult };