@requence/service 1.0.0-alpha.4 → 1.0.0-alpha.45

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 +246 -0
  2. package/build/{chunk-0x9092n4.js → chunk-6w7td62p.js} +5 -44
  3. package/build/chunk-6w7td62p.js.map +10 -0
  4. package/build/cli.js +19 -12
  5. package/build/cli.js.map +3 -3
  6. package/build/index.js +930 -863
  7. package/build/index.js.map +18 -16
  8. package/build/types/helpers/src/files/RequenceFile.d.ts +40 -0
  9. package/build/types/helpers/src/files/RequenceFile.d.ts.map +1 -0
  10. package/build/types/helpers/src/files/RequenceStream.d.ts +32 -0
  11. package/build/types/helpers/src/files/RequenceStream.d.ts.map +1 -0
  12. package/build/types/helpers/src/files/fileObject.d.ts +16 -0
  13. package/build/types/helpers/src/files/fileObject.d.ts.map +1 -0
  14. package/build/types/helpers/src/files/index.d.ts +7 -0
  15. package/build/types/helpers/src/files/index.d.ts.map +1 -0
  16. package/build/types/helpers/src/files/isValidMimeType.d.ts +5 -0
  17. package/build/types/helpers/src/files/isValidMimeType.d.ts.map +1 -0
  18. package/build/types/helpers/src/files/mapOutput.d.ts +10 -0
  19. package/build/types/helpers/src/files/mapOutput.d.ts.map +1 -0
  20. package/build/types/helpers/src/files/streamObject.d.ts +14 -0
  21. package/build/types/helpers/src/files/streamObject.d.ts.map +1 -0
  22. package/build/types/helpers/src/files/types.d.ts +4 -0
  23. package/build/types/helpers/src/files/types.d.ts.map +1 -0
  24. package/build/types/helpers/src/index.d.ts +10 -6
  25. package/build/types/helpers/src/index.d.ts.map +1 -1
  26. package/build/types/helpers/src/jsonschema/mapSchema.d.ts +20 -0
  27. package/build/types/helpers/src/jsonschema/mapSchema.d.ts.map +1 -0
  28. package/build/types/helpers/src/jsonschema/types.d.ts +13 -0
  29. package/build/types/helpers/src/jsonschema/types.d.ts.map +1 -0
  30. package/build/types/helpers/src/jsonschema/validate.d.ts +32 -0
  31. package/build/types/helpers/src/jsonschema/validate.d.ts.map +1 -0
  32. package/build/types/helpers/src/jsonschema/zod.d.ts +15 -0
  33. package/build/types/helpers/src/jsonschema/zod.d.ts.map +1 -0
  34. package/build/types/helpers/src/protocol/NodeTree.d.ts +993 -0
  35. package/build/types/helpers/src/protocol/NodeTree.d.ts.map +1 -0
  36. package/build/types/helpers/src/protocol/command.d.ts +853 -0
  37. package/build/types/helpers/src/protocol/command.d.ts.map +1 -0
  38. package/build/types/helpers/src/protocol/helpers.d.ts +7 -0
  39. package/build/types/helpers/src/protocol/helpers.d.ts.map +1 -0
  40. package/build/types/helpers/src/protocol/index.d.ts +7 -0
  41. package/build/types/helpers/src/protocol/index.d.ts.map +1 -0
  42. package/build/types/helpers/src/protocol/nodeType.d.ts +434 -0
  43. package/build/types/helpers/src/protocol/nodeType.d.ts.map +1 -0
  44. package/build/types/helpers/src/protocol/taskOptions.d.ts +23 -0
  45. package/build/types/helpers/src/protocol/taskOptions.d.ts.map +1 -0
  46. package/build/types/helpers/src/protocol/treeNodes.d.ts +1542 -0
  47. package/build/types/helpers/src/protocol/treeNodes.d.ts.map +1 -0
  48. package/build/types/helpers/src/protocol/update.d.ts +379 -0
  49. package/build/types/helpers/src/protocol/update.d.ts.map +1 -0
  50. package/build/types/helpers/src/utils/callbackToAsyncIterator.d.ts +3 -0
  51. package/build/types/helpers/src/utils/callbackToAsyncIterator.d.ts.map +1 -0
  52. package/build/types/helpers/src/utils/clone.d.ts +3 -0
  53. package/build/types/helpers/src/utils/clone.d.ts.map +1 -0
  54. package/build/types/helpers/src/utils/createObjectProxy.d.ts +2 -0
  55. package/build/types/helpers/src/utils/createObjectProxy.d.ts.map +1 -0
  56. package/build/types/helpers/src/{createRemotePromise.d.ts → utils/createRemotePromise.d.ts} +1 -1
  57. package/build/types/helpers/src/utils/createRemotePromise.d.ts.map +1 -0
  58. package/build/types/helpers/src/utils/isRecord.d.ts +2 -0
  59. package/build/types/helpers/src/utils/isRecord.d.ts.map +1 -0
  60. package/build/types/helpers/src/utils/mapData.d.ts +18 -0
  61. package/build/types/helpers/src/utils/mapData.d.ts.map +1 -0
  62. package/build/types/helpers/src/{utils.d.ts → utils/matchSchema.d.ts} +2 -2
  63. package/build/types/helpers/src/utils/matchSchema.d.ts.map +1 -0
  64. package/build/types/helpers/src/utils/obfuscate.d.ts.map +1 -0
  65. package/build/types/helpers/src/utils/requenceCallback.d.ts +17 -0
  66. package/build/types/helpers/src/utils/requenceCallback.d.ts.map +1 -0
  67. package/build/types/helpers/src/utils/resolveRequenceTypes.d.ts +8 -0
  68. package/build/types/helpers/src/utils/resolveRequenceTypes.d.ts.map +1 -0
  69. package/build/types/service/src/createAmqpConnection.d.ts +19 -20
  70. package/build/types/service/src/createAmqpConnection.d.ts.map +1 -1
  71. package/build/types/service/src/helpers.d.ts +72 -99
  72. package/build/types/service/src/helpers.d.ts.map +1 -1
  73. package/build/types/service/src/index.d.ts +8 -4
  74. package/build/types/service/src/index.d.ts.map +1 -1
  75. package/build/types/service/src/macro.d.ts +2 -0
  76. package/build/types/service/src/macro.d.ts.map +1 -0
  77. package/build/types/service/src/mapInput.d.ts +2 -0
  78. package/build/types/service/src/mapInput.d.ts.map +1 -0
  79. package/build/types/service/src/utils.d.ts +6 -0
  80. package/build/types/service/src/utils.d.ts.map +1 -0
  81. package/package.json +8 -7
  82. package/build/chunk-0x9092n4.js.map +0 -12
  83. package/build/types/helpers/src/clone.d.ts +0 -3
  84. package/build/types/helpers/src/clone.d.ts.map +0 -1
  85. package/build/types/helpers/src/createObjectProxy.d.ts +0 -2
  86. package/build/types/helpers/src/createObjectProxy.d.ts.map +0 -1
  87. package/build/types/helpers/src/createRemotePromise.d.ts.map +0 -1
  88. package/build/types/helpers/src/obfuscate.d.ts.map +0 -1
  89. package/build/types/helpers/src/utils.d.ts.map +0 -1
  90. /package/build/types/helpers/src/{obfuscate.d.ts → utils/obfuscate.d.ts} +0 -0
package/build/index.js CHANGED
@@ -1,677 +1,449 @@
1
1
  import {
2
- clone,
3
- createObjectProxy,
4
2
  deobfuscate,
5
3
  obfuscate
6
- } from "./chunk-0x9092n4.js";
4
+ } from "./chunk-6w7td62p.js";
7
5
 
8
6
  // src/index.ts
9
- import { readFileSync } from "node:fs";
10
- import { z as z8 } from "zod";
7
+ import fs from "node:fs";
11
8
 
12
- // ../helpers/src/context/context.ts
13
- import { z } from "zod";
14
- var contextSchema = z.object({
15
- input: z.any(),
16
- meta: z.any(),
17
- tenant: z.object({ name: z.string() }),
18
- data: z.record(z.string(), z.any()),
19
- errors: z.record(z.string(), z.string()),
20
- dates: z.record(z.string(), z.string().datetime())
21
- });
22
- function isRecord(data) {
23
- return typeof data === "object" && data !== null && !Array.isArray(data);
24
- }
25
- var internalKey = Symbol.for("internal");
26
- function getInternalContext(contextHelper) {
27
- return contextHelper[internalKey];
28
- }
29
- function createContextHelper(context, nodes) {
30
- const results = new Map(nodes.map((node) => [
31
- node.id,
32
- {
33
- node,
34
- executionDate: node.id in context.dates ? new Date(context.dates[node.id]) : null,
35
- data: context.data[node.id] ?? null,
36
- error: context.errors[node.id] ?? null
37
- }
38
- ]));
39
- const lookUpMap = new Map;
40
- for (const node of nodes) {
41
- const alias = typeof node.meta?.mapAlias === "string" ? node.meta.mapAlias : ("alias" in node) && node.alias;
42
- if (alias) {
43
- if (lookUpMap.has(alias)) {
44
- lookUpMap.get(alias).push(node.id);
45
- } else {
46
- lookUpMap.set(alias, [node.id]);
47
- }
48
- }
49
- const name = typeof node.meta?.mapName === "string" ? node.meta.mapName : node.type === "service" && node.name;
50
- if (name) {
51
- if (lookUpMap.has(name)) {
52
- lookUpMap.get(name).push(node.id);
53
- } else {
54
- lookUpMap.set(name, [node.id]);
55
- }
56
- }
57
- }
58
- return {
59
- [internalKey]: {
60
- results
61
- },
62
- getInput() {
63
- return context.input;
64
- },
65
- getMeta() {
66
- return context.meta;
67
- },
68
- getData(alias) {
69
- if (alias) {
70
- const nodeIds = lookUpMap.get(alias);
71
- if (!nodeIds) {
72
- return null;
73
- }
74
- const combinedData = nodeIds.map((nodeId) => results.get(nodeId)?.data).filter(Boolean);
75
- if (combinedData.length === 0) {
76
- return null;
77
- }
78
- if (combinedData.length === 1) {
79
- return combinedData[0];
80
- }
81
- if (combinedData.every(isRecord)) {
82
- return combinedData.reduce((acc, data) => ({ ...acc, ...data }), {});
9
+ // ../helpers/src/utils/createRemotePromise.ts
10
+ function createRemotePromise(onAwait) {
11
+ let resolvePromise;
12
+ let rejectPromise;
13
+ const internalPromise = new Promise((resolve, reject) => {
14
+ resolvePromise = resolve;
15
+ rejectPromise = reject;
16
+ });
17
+ let isAwaited = false;
18
+ const wrappedPromise = new Proxy(internalPromise, {
19
+ get(target, property) {
20
+ if (property === "then" || property === "catch" || property === "finally") {
21
+ if (!isAwaited && onAwait) {
22
+ isAwaited = true;
23
+ onAwait(resolvePromise, rejectPromise);
83
24
  }
84
- return combinedData;
85
- }
86
- return Array.from(results.values()).filter((result) => result.executionDate && isRecord(result.data)).toSorted((a, b) => a.executionDate.getTime() - b.executionDate.getTime()).reduce((acc, result) => ({
87
- ...acc,
88
- ...result.data
89
- }), isRecord(context.input) ? { ...context.input } : {});
90
- },
91
- getError(alias) {
92
- const nodeIds = lookUpMap.get(alias);
93
- if (!nodeIds) {
94
- return null;
25
+ return target[property].bind(target);
95
26
  }
96
- return nodeIds.map((nodeId) => results.get(nodeId)?.error).filter((str) => typeof str === "string").join(`
97
- `);
27
+ return target[property];
98
28
  }
99
- };
29
+ });
30
+ return Object.assign(wrappedPromise, {
31
+ resolve: resolvePromise,
32
+ reject: rejectPromise,
33
+ promise: wrappedPromise
34
+ });
100
35
  }
101
- // ../helpers/src/protocol/command.ts
102
- import { z as z5 } from "zod";
103
36
 
104
- // ../helpers/src/protocol/nodes.ts
105
- import { ZodError, z as z4 } from "zod";
37
+ // ../helpers/src/utils/isRecord.ts
38
+ import { z } from "zod/v4";
39
+ var recordSchema = z.record(z.string(), z.unknown());
40
+ function isRecord(data) {
41
+ return recordSchema.safeParse(data).success;
42
+ }
106
43
 
107
- // ../helpers/src/protocol/getNodeOutputs.ts
108
- function getNodeOutputs(node, outputName) {
109
- const outputs = !outputName ? node.output : outputName === "__default__" ? node.output.filter((o) => o.default) : node.output.filter((o) => ("name" in o) && o.name === outputName);
110
- const outputTargets = new Set;
111
- for (const output of outputs) {
112
- if (output.exit) {
113
- outputTargets.add("__exit__");
114
- } else {
115
- outputTargets.add(output.target);
116
- }
44
+ // ../helpers/src/utils/mapData.ts
45
+ function resolve(value, onResolve) {
46
+ if (value instanceof Promise) {
47
+ return Promise.resolve().then(() => value).then(onResolve);
117
48
  }
118
- return Array.from(outputTargets);
49
+ return onResolve(value);
50
+ }
51
+ function notUndefined(value, fallback) {
52
+ return resolve(value, (resolvedValue) => typeof resolvedValue === "undefined" ? fallback : resolvedValue);
119
53
  }
120
54
 
121
- // ../helpers/src/protocol/createNodeMaps.ts
122
- function createNodeMaps(nodes) {
123
- const nodesByIdMap = new Map;
124
- const nodesByNameOrAlias = new Map;
125
- const inputsNodeMap = new Map([
126
- ["__exit__", []]
127
- ]);
128
- for (const node of nodes) {
129
- nodesByIdMap.set(node.id, node);
130
- if ("alias" in node && node.alias) {
131
- nodesByNameOrAlias.set(node.alias, node);
132
- }
133
- if ("name" in node && node.name) {
134
- nodesByNameOrAlias.set(node.name, node);
55
+ class AbortMapData extends Error {
56
+ }
57
+ function mapData(data, visitors) {
58
+ let aborted = false;
59
+ const traverseData = (data2, path) => {
60
+ if (aborted) {
61
+ return data2;
135
62
  }
136
- }
137
- for (const node of nodes) {
138
- for (const outputNodeId of getNodeOutputs(node)) {
139
- if (!inputsNodeMap.has(outputNodeId)) {
140
- inputsNodeMap.set(outputNodeId, []);
63
+ try {
64
+ if (Array.isArray(data2)) {
65
+ return resolve(visitors.Array?.(data2, path), (resolvedData) => {
66
+ if (resolvedData) {
67
+ return resolvedData;
68
+ }
69
+ const items = data2.map((item, index) => traverseData(item, [...path, index]));
70
+ if (items.some((item) => item instanceof Promise)) {
71
+ return Promise.all(items);
72
+ }
73
+ return items;
74
+ });
141
75
  }
142
- inputsNodeMap.get(outputNodeId).push(node);
143
- }
144
- }
145
- return {
146
- getInputs(node) {
147
- if (typeof node === "string") {
148
- return inputsNodeMap.get(node) ?? [];
76
+ if (data2 === null) {
77
+ return notUndefined(visitors.Null?.(data2, path), data2);
149
78
  }
150
- if (node.type === "catch" || node.type === "entry") {
151
- return [];
79
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(data2)) {
80
+ return notUndefined(visitors.Buffer?.(data2, path), data2);
152
81
  }
153
- return inputsNodeMap.get(node.id) ?? [];
154
- },
155
- getNode(nodeId) {
156
- return nodesByIdMap.get(nodeId);
157
- },
158
- lookupNode(nameOrAlias) {
159
- return nodesByNameOrAlias.get(nameOrAlias);
82
+ if (typeof data2 === "string") {
83
+ return notUndefined(visitors.String?.(data2, path), data2);
84
+ }
85
+ if (typeof data2 === "number") {
86
+ return notUndefined(visitors.Number?.(data2, path), data2);
87
+ }
88
+ if (typeof data2 === "symbol") {
89
+ return notUndefined(visitors.Symbol?.(data2, path), data2);
90
+ }
91
+ if (typeof data2 === "function") {
92
+ return notUndefined(visitors.Function?.(data2, path), data2);
93
+ }
94
+ if (isRecord(data2)) {
95
+ return resolve(visitors.Object?.(structuredClone(data2), path), (resolvedData) => {
96
+ const nextData = resolvedData ?? data2;
97
+ if (!isRecord(nextData)) {
98
+ return nextData;
99
+ }
100
+ const entries = Object.entries(nextData).map(([key, value]) => [
101
+ key,
102
+ traverseData(value, [...path, key])
103
+ ]);
104
+ if (entries.some(([, value]) => value instanceof Promise)) {
105
+ return Promise.all(entries.map(([key, value]) => Promise.resolve().then(() => value).then((resolvedValue) => [key, resolvedValue]))).then((entries2) => Object.fromEntries(entries2));
106
+ }
107
+ return Object.fromEntries(entries);
108
+ });
109
+ }
110
+ if (typeof data2 === "object" && data2) {
111
+ return notUndefined(visitors.Object?.(data2, path), data2);
112
+ }
113
+ return data2;
114
+ } catch (error) {
115
+ if (error instanceof AbortMapData) {
116
+ aborted = true;
117
+ return data2;
118
+ }
119
+ throw error;
160
120
  }
161
121
  };
122
+ return traverseData(data, []);
162
123
  }
124
+ mapData.abort = () => {
125
+ throw new AbortMapData;
126
+ };
163
127
 
164
- // ../helpers/src/protocol/getPossiblePaths.ts
165
- function getPossiblePaths({
166
- getInputs,
167
- getNode,
168
- onMissingInputs
169
- }) {
170
- const sets = new Set;
171
- const followPath = (nodeId, set2) => {
172
- if (nodeId === "__entry__") {
173
- return;
128
+ // ../helpers/src/utils/requenceCallback.ts
129
+ import { z as z2 } from "zod/v4";
130
+ var callbackObjectSchema = z2.object({
131
+ sourceId: z2.string(),
132
+ outputName: z2.string().nullable(),
133
+ propertyPath: z2.array(z2.union([z2.string(), z2.int()])),
134
+ callbackId: z2.uuid(),
135
+ __REQUENCE_type: z2.literal("RequenceCallback")
136
+ });
137
+ function isCallbackObject(data) {
138
+ return callbackObjectSchema.safeParse(data).success;
139
+ }
140
+ function createCallback(callback) {
141
+ let resolvePromise;
142
+ const promise = new Promise((resolve2) => {
143
+ resolvePromise = resolve2;
144
+ });
145
+ const executor = (arg) => {
146
+ resolvePromise(arg);
147
+ callback?.(arg);
148
+ };
149
+ return Object.assign(executor, {
150
+ response() {
151
+ return promise;
174
152
  }
175
- const node = nodeId !== "__exit__" ? getNode(nodeId) : null;
176
- const isOrNode = node?.type === "or";
177
- const inputNodes = getInputs(nodeId);
178
- if (node && node.type !== "catch" && inputNodes.length === 0) {
179
- onMissingInputs?.(node, Array.from(set2).toReversed());
153
+ });
154
+ }
155
+
156
+ // ../helpers/src/files/mapOutput.ts
157
+ async function upload(uploadUrl, body, signal, contentType) {
158
+ const uploadResponse = await fetch(uploadUrl, {
159
+ method: "POST",
160
+ signal,
161
+ headers: contentType ? {
162
+ "Content-Type": contentType
163
+ } : {},
164
+ body
165
+ });
166
+ const data = await uploadResponse.json();
167
+ if (!data || typeof data !== "object") {
168
+ throw new Error("invalid upload response");
169
+ }
170
+ return toFileObject(data);
171
+ }
172
+ async function stream(streamUrl, stream2, signal, contentType) {
173
+ const [testStream, dataStream] = stream2.tee();
174
+ const reader = testStream.getReader();
175
+ const dataPromise = reader.read().then(({ done: done2 }) => {
176
+ if (done2) {
177
+ throw new Error("No streaming date received");
180
178
  }
181
- for (const inputNode of inputNodes) {
182
- let usedSet = set2;
183
- if (isOrNode) {
184
- usedSet = new Set(set2);
185
- sets.add(usedSet);
179
+ reader.cancel();
180
+ });
181
+ const streamResponse = await fetch(streamUrl, {
182
+ method: "POST",
183
+ signal,
184
+ headers: contentType ? { "Content-Type": contentType } : {}
185
+ });
186
+ const data = await streamResponse.json();
187
+ if (!data || typeof data !== "object") {
188
+ throw new Error("invalid stream response");
189
+ }
190
+ const { mime, url } = data;
191
+ await dataPromise;
192
+ const done = fetch(url, {
193
+ method: "POST",
194
+ signal,
195
+ duplex: "half",
196
+ body: dataStream
197
+ });
198
+ return [toStreamObject({ mime, url }), done];
199
+ }
200
+ async function mapOutput(params) {
201
+ const streamPromises = [];
202
+ const mapped = await mapData(params.value, {
203
+ async Object(obj) {
204
+ if (obj instanceof Blob || obj instanceof RequenceFile) {
205
+ if (obj instanceof RequenceFile && obj.fileObject) {
206
+ return obj.fileObject;
207
+ }
208
+ if (params.options.uploadUrl) {
209
+ try {
210
+ if (obj instanceof Blob) {
211
+ return await upload(params.options.uploadUrl, obj, params.signal, obj.type);
212
+ }
213
+ if (obj instanceof RequenceFile) {
214
+ return await upload(params.options.uploadUrl, await obj.blob(), params.signal, obj.mimeType);
215
+ }
216
+ } catch (error) {
217
+ if (!(error instanceof Error)) {
218
+ throw error;
219
+ }
220
+ params.onFail?.(error);
221
+ return null;
222
+ }
223
+ } else {
224
+ params.onSkip?.();
225
+ return null;
226
+ }
186
227
  }
187
- const inputNodeId = inputNode.id;
188
- if (inputNode.type !== "or") {
189
- if (usedSet.has(inputNodeId)) {
190
- return;
228
+ if (obj instanceof Response || obj instanceof RequenceStream) {
229
+ if (obj instanceof RequenceStream && obj.streamObject) {
230
+ return obj.streamObject;
231
+ }
232
+ if (params.options.streamUrl) {
233
+ try {
234
+ if (obj instanceof Response && obj.body) {
235
+ const [streamObject, streamPromise] = await stream(params.options.streamUrl, obj.body, params.signal, obj.headers.get("Content-Type"));
236
+ streamPromises.push(streamPromise);
237
+ return streamObject;
238
+ }
239
+ if (obj instanceof RequenceStream) {
240
+ const [streamObject, streamPromise] = await stream(params.options.streamUrl, obj.stream(), params.signal, obj.mimeType);
241
+ streamPromises.push(streamPromise);
242
+ return streamObject;
243
+ }
244
+ } catch (error) {
245
+ if (!(error instanceof Error)) {
246
+ throw error;
247
+ }
248
+ params.onFail?.(error);
249
+ return null;
250
+ }
251
+ } else {
252
+ params.onSkip?.();
253
+ return null;
191
254
  }
192
- usedSet.add(inputNodeId);
193
255
  }
194
- followPath(inputNodeId, usedSet);
195
256
  }
196
- if (isOrNode) {
197
- sets.delete(set2);
198
- }
199
- };
200
- const set = new Set(["__exit__"]);
201
- sets.add(set);
202
- followPath("__exit__", set);
203
- return Array.from(sets, (set2) => Array.from(set2).toReversed());
257
+ });
258
+ Promise.allSettled(streamPromises).then(() => params.onDone?.());
259
+ return mapped;
204
260
  }
205
261
 
206
- // ../helpers/src/protocol/identifyNode.ts
207
- function identifyNode(nodeId, getNode) {
208
- if (nodeId === "__entry__") {
209
- return "ENTRY";
262
+ // ../helpers/src/files/RequenceFile.ts
263
+ class RequenceFile {
264
+ #data;
265
+ #file = null;
266
+ constructor(blobParts, options) {
267
+ this.#data = new Blob(blobParts, options);
210
268
  }
211
- if (nodeId === "__exit__") {
212
- return "EXIT";
269
+ static fromFileObject(file) {
270
+ const instance = new this([], { type: "x/x" });
271
+ instance.#file = file;
272
+ return instance;
213
273
  }
214
- if (typeof nodeId === "symbol") {
215
- return String(nodeId);
274
+ get fileObject() {
275
+ return this.#file;
216
276
  }
217
- const node = getNode(nodeId);
218
- if (!node) {
219
- return `Unknown[${nodeId}]`;
277
+ get size() {
278
+ return this.#file?.size ?? this.#data.size;
220
279
  }
221
- switch (node.type) {
222
- case "service": {
223
- return `Service[${node.alias || node.name}]`;
224
- }
225
- case "catch": {
226
- return `Catch[${identifyNode(node.subject, getNode)}]`;
280
+ get mimeType() {
281
+ return this.#file?.mime ?? this.#data.type;
282
+ }
283
+ get mainMimeType() {
284
+ return this.mimeType.split("/")[0];
285
+ }
286
+ get subMimeType() {
287
+ return this.mimeType.split("/")[1];
288
+ }
289
+ async text() {
290
+ if (this.#file) {
291
+ return fetch(this.#file.url).then((response) => response.text());
227
292
  }
228
- case "logic": {
229
- return `Logic[${node.alias || node.id}]`;
293
+ return this.#data.text();
294
+ }
295
+ async json() {
296
+ if (this.#file) {
297
+ return fetch(this.#file.url).then((response) => response.json());
230
298
  }
231
- case "entry": {
232
- return "ENTRY";
299
+ return JSON.parse(await this.text());
300
+ }
301
+ async blob() {
302
+ if (this.#file) {
303
+ return fetch(this.#file.url).then((response) => response.blob());
233
304
  }
234
- case "or": {
235
- return `OR[${node.alias || node.id}]`;
305
+ return this.#data;
306
+ }
307
+ async arrayBuffer() {
308
+ if (this.#file) {
309
+ return fetch(this.#file.url).then((response) => response.arrayBuffer());
236
310
  }
311
+ return this.#data.arrayBuffer();
237
312
  }
238
- }
239
-
240
- // ../helpers/src/protocol/node.ts
241
- import { z as z3 } from "zod";
242
-
243
- // ../helpers/src/protocol/jsonSchema.ts
244
- import { z as z2 } from "zod";
245
- var jsonSchema7Schema = z2.lazy(() => z2.object({
246
- $id: z2.string().optional(),
247
- $schema: z2.string().optional(),
248
- $ref: z2.string().optional(),
249
- title: z2.string().optional(),
250
- description: z2.string().optional(),
251
- type: z2.union([
252
- z2.literal("string"),
253
- z2.literal("number"),
254
- z2.literal("integer"),
255
- z2.literal("boolean"),
256
- z2.literal("object"),
257
- z2.literal("array"),
258
- z2.literal("null")
259
- ]).optional(),
260
- enum: z2.array(z2.union([z2.string(), z2.number(), z2.boolean(), z2.null()])).optional(),
261
- const: z2.union([z2.string(), z2.number(), z2.boolean(), z2.null()]).optional(),
262
- multipleOf: z2.number().positive().optional(),
263
- maximum: z2.number().optional(),
264
- exclusiveMaximum: z2.number().optional(),
265
- minimum: z2.number().optional(),
266
- exclusiveMinimum: z2.number().optional(),
267
- maxLength: z2.number().int().nonnegative().optional(),
268
- minLength: z2.number().int().nonnegative().optional(),
269
- pattern: z2.string().optional(),
270
- additionalItems: z2.boolean().optional(),
271
- items: z2.union([z2.lazy(() => jsonSchema7Schema), z2.array(jsonSchema7Schema)]).optional(),
272
- maxItems: z2.number().int().nonnegative().optional(),
273
- minItems: z2.number().int().nonnegative().optional(),
274
- uniqueItems: z2.boolean().optional(),
275
- contains: z2.lazy(() => jsonSchema7Schema).optional(),
276
- maxProperties: z2.number().int().nonnegative().optional(),
277
- minProperties: z2.number().int().nonnegative().optional(),
278
- required: z2.array(z2.string()).optional(),
279
- properties: z2.record(jsonSchema7Schema).optional(),
280
- patternProperties: z2.record(jsonSchema7Schema).optional(),
281
- additionalProperties: z2.union([z2.boolean(), z2.lazy(() => jsonSchema7Schema)]).optional(),
282
- dependencies: z2.record(z2.union([z2.array(z2.string()), jsonSchema7Schema])).optional(),
283
- propertyNames: z2.lazy(() => jsonSchema7Schema).optional(),
284
- if: z2.lazy(() => jsonSchema7Schema).optional(),
285
- then: z2.lazy(() => jsonSchema7Schema).optional(),
286
- else: z2.lazy(() => jsonSchema7Schema).optional(),
287
- allOf: z2.array(jsonSchema7Schema).optional(),
288
- anyOf: z2.array(jsonSchema7Schema).optional(),
289
- oneOf: z2.array(jsonSchema7Schema).optional(),
290
- not: z2.lazy(() => jsonSchema7Schema).optional(),
291
- definitions: z2.record(jsonSchema7Schema).optional(),
292
- format: z2.string().optional(),
293
- contentMediaType: z2.string().optional(),
294
- contentEncoding: z2.string().optional()
295
- }));
296
- var jsonSchema7ObjectSchema = z2.object({
297
- type: z2.literal("object"),
298
- properties: z2.record(jsonSchema7Schema),
299
- required: z2.array(z2.string()).optional(),
300
- description: z2.string().optional(),
301
- maxProperties: z2.number().int().nonnegative().optional(),
302
- minProperties: z2.number().int().nonnegative().optional(),
303
- additionalProperties: z2.boolean().optional()
304
- });
305
-
306
- // ../helpers/src/protocol/node.ts
307
- var outputDefinitionSchema = z3.object({
308
- schema: jsonSchema7Schema.nullable().optional()
309
- }).and(z3.union([
310
- z3.object({
311
- default: z3.literal(false).default(false),
312
- name: z3.string().min(1)
313
- }),
314
- z3.object({
315
- default: z3.literal(true).default(true)
316
- })
317
- ])).and(z3.union([
318
- z3.object({
319
- exit: z3.literal(false).default(false),
320
- target: z3.string().min(1)
321
- }),
322
- z3.object({ exit: z3.literal(true) })
323
- ]));
324
- var defaultOutputSchema = z3.union([
325
- z3.string().min(1),
326
- z3.object({ default: z3.literal(true).default(true), exit: z3.literal(true) }),
327
- z3.object({
328
- default: z3.literal(true).default(true),
329
- exit: z3.literal(false).default(false),
330
- target: z3.string().min(1)
331
- })
332
- ]).transform((output) => {
333
- if (typeof output === "string") {
334
- return {
335
- default: true,
336
- exit: false,
337
- target: output
338
- };
313
+ toString() {
314
+ return `RequenceFile<${this.mimeType}>`;
339
315
  }
340
- return output;
341
- });
342
- var outputSchema = z3.union([z3.string().min(1), outputDefinitionSchema]).transform((output) => {
343
- if (typeof output === "string") {
344
- return {
345
- default: true,
346
- exit: false,
347
- target: output
348
- };
316
+ toJSON() {
317
+ return `RequenceFile<${this.mimeType}>`;
349
318
  }
350
- return output;
351
- });
352
- function validateOutputs(outputs, ctx) {
353
- const exitOutputs = new Set(outputs.filter((output) => output.exit).map((output) => output.default ? "__default__" : output.name));
354
- outputs.filter((output) => !output.exit).forEach((output) => {
355
- const name = output.default ? "__default__" : output.name;
356
- if (exitOutputs.has(name)) {
357
- ctx.addIssue({
358
- code: "custom",
359
- message: output.default ? `default exit output cannot be mixed with target output "${output.target}"` : `named exit output "${name}" cannot be mixed with target output "${output.target}"`
360
- });
361
- }
362
- });
363
- const targets = new Map;
364
- outputs.forEach((output) => {
365
- const name = output.default ? "__default__" : output.name;
366
- const target = output.exit ? "__exit__" : output.target;
367
- if (!targets.has(name)) {
368
- targets.set(name, new Set);
369
- }
370
- const knownTargets = targets.get(name);
371
- if (knownTargets.has(target)) {
372
- ctx.addIssue({
373
- code: "custom",
374
- message: [
375
- output.default ? "duplicate default output" : `duplicate named output "${name}"`,
376
- output.exit ? "for exit" : `for target "${target}"`
377
- ].join(" ")
378
- });
379
- }
380
- knownTargets.add(target);
381
- });
382
319
  }
383
- var defaultOutputsSchema = z3.array(defaultOutputSchema).default([]).superRefine(validateOutputs);
384
- var outputsSchema = z3.array(outputSchema).default([]).superRefine(validateOutputs);
385
- var idSchema = z3.string().uuid().default(() => crypto.randomUUID());
386
- var metaSchema = z3.record(z3.any()).optional();
387
- var entryNodeSchema = z3.object({
388
- type: z3.literal("entry"),
389
- id: z3.literal("__entry__").default("__entry__"),
390
- output: defaultOutputsSchema,
391
- inputSchema: jsonSchema7Schema.nullable().optional(),
392
- metaSchema: jsonSchema7Schema.nullable().optional(),
393
- meta: metaSchema
394
- });
395
- var serviceNodeSchema = z3.object({
396
- type: z3.literal("service"),
397
- output: outputsSchema,
398
- inputSchema: jsonSchema7ObjectSchema.nullable().optional(),
399
- id: idSchema,
400
- name: z3.string(),
401
- version: z3.string(),
402
- configuration: z3.any().optional(),
403
- configurationSchema: jsonSchema7Schema.nullable().optional(),
404
- alias: z3.string().optional(),
405
- ttl: z3.number().int().min(1).optional(),
406
- retry: z3.number().int().min(1).optional(),
407
- retryDelay: z3.number().int().min(100).optional(),
408
- meta: metaSchema
409
- });
410
- var catchNodeSchema = z3.object({
411
- type: z3.literal("catch"),
412
- output: outputsSchema,
413
- id: idSchema,
414
- subject: z3.string(),
415
- meta: metaSchema
416
- });
417
- var logicNodeSchema = z3.object({
418
- type: z3.literal("logic"),
419
- alias: z3.string().optional(),
420
- inputSchema: jsonSchema7ObjectSchema.nullable().optional(),
421
- output: outputsSchema,
422
- id: idSchema,
423
- script: z3.string(),
424
- concurrency: z3.boolean().default(true),
425
- language: z3.enum(["javascript", "python", "typescript"]).default("javascript"),
426
- maxExecutionTime: z3.number().int().min(0).default(200),
427
- meta: metaSchema
428
- });
429
- var orNodeSchema = z3.object({
430
- id: idSchema,
431
- type: z3.literal("or"),
432
- alias: z3.string().optional(),
433
- output: outputsSchema,
434
- meta: metaSchema
435
- });
436
- var nodeSchema = z3.discriminatedUnion("type", [
437
- entryNodeSchema,
438
- serviceNodeSchema,
439
- catchNodeSchema,
440
- logicNodeSchema,
441
- orNodeSchema
442
- ]);
443
320
 
444
- // ../helpers/src/protocol/nodes.ts
445
- class NodesError extends ZodError {
446
- constructor(message, params, path = []) {
447
- super([
448
- {
449
- code: z4.ZodIssueCode.custom,
450
- message,
451
- path,
452
- params
453
- }
454
- ]);
455
- }
456
- }
457
- var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
458
- const aliases = new Map;
459
- const names = new Map;
460
- let entryNode = null;
461
- let firstNodeId = null;
462
- for (const node of nodes) {
463
- if (node.type === "entry") {
464
- entryNode = node;
465
- }
466
- if ((node.type === "service" || node.type === "logic") && !firstNodeId) {
467
- firstNodeId = node.id;
468
- }
469
- if ("alias" in node && node.alias) {
470
- if (!aliases.has(node.alias)) {
471
- aliases.set(node.alias, []);
472
- }
473
- aliases.get(node.alias).push(node.id);
474
- }
475
- if ("name" in node && node.name) {
476
- if (!names.has(node.name)) {
477
- names.set(node.name, []);
478
- }
479
- names.get(node.name).push(node.id);
480
- }
321
+ // ../helpers/src/files/RequenceStream.ts
322
+ class RequenceStream {
323
+ #data;
324
+ #stream = null;
325
+ #options;
326
+ constructor(stream2, options) {
327
+ this.#data = stream2;
328
+ this.#options = options;
481
329
  }
482
- if (!entryNode && firstNodeId) {
483
- nodes.unshift({
484
- type: "entry",
485
- id: "__entry__",
486
- output: [{ default: true, exit: false, target: firstNodeId }]
330
+ static fromStreamObject(stream2) {
331
+ const instance = new this(null, {
332
+ type: "x/x"
487
333
  });
334
+ instance.#stream = stream2;
335
+ return instance;
488
336
  }
489
- const resolveOutput = (identifier) => {
490
- if (aliases.get(identifier)?.length === 1) {
491
- return aliases.get(identifier)[0];
492
- }
493
- if (names.get(identifier)?.length === 1) {
494
- return names.get(identifier)[0];
495
- }
496
- return identifier;
497
- };
498
- return nodes.map((node) => {
499
- node.output = node.output.map((output) => ("target" in output) ? {
500
- ...output,
501
- target: resolveOutput(output.target)
502
- } : output);
503
- if ("subject" in node) {
504
- node.subject = resolveOutput(node.subject);
505
- }
506
- return node;
507
- });
508
- }).transform((nodes) => {
509
- const { getInputs, getNode } = createNodeMaps(nodes);
510
- const nodeAliases = new Set;
511
- const nodeIds = new Set;
512
- const catchSubjects = new Map;
513
- const identify = (nodeId) => identifyNode(nodeId, getNode);
514
- for (const node of nodes) {
515
- if (nodeIds.has(node.id)) {
516
- throw new NodesError("id is not unique", {
517
- id: node.id
518
- });
519
- }
520
- nodeIds.add(node.id);
521
- if ("alias" in node && node.alias) {
522
- if (nodeAliases.has(node.alias)) {
523
- throw new NodesError("alias is not unique", {
524
- alias: node.alias
525
- });
526
- }
527
- nodeAliases.add(node.alias);
528
- }
529
- if (node.type === "catch") {
530
- if (catchSubjects.has(node.subject)) {
531
- throw new NodesError("only one catch node per service allowed", {
532
- id: node.subject
533
- });
534
- }
535
- catchSubjects.set(node.subject, node);
536
- }
337
+ get streamObject() {
338
+ return this.#stream;
537
339
  }
538
- if (!getNode("__entry__")) {
539
- throw new NodesError("missing entry node");
340
+ get mimeType() {
341
+ return this.#stream?.mime ?? this.#options.type;
540
342
  }
541
- if (getInputs("__exit__").length === 0) {
542
- throw new NodesError("no path leads to exit");
343
+ get mainMimeType() {
344
+ return this.mimeType.split("/")[0];
543
345
  }
544
- for (const catchNode of nodes.filter((node) => node.type === "catch")) {
545
- if (!getNode(catchNode.subject)) {
546
- throw new NodesError("catch node has invalid subject", {
547
- id: catchNode.subject
548
- });
549
- }
346
+ get subMimeType() {
347
+ return this.mimeType.split("/")[1];
550
348
  }
551
- for (const node of nodes) {
552
- if (node.type === "or") {
553
- const inputs = getInputs(node);
554
- if (!inputs || inputs.length < 2) {
555
- throw new NodesError("or nodes need at least 2 inputs");
556
- }
349
+ stream() {
350
+ if (this.#stream) {
351
+ const { readable, writable } = new TransformStream;
352
+ fetch(this.#stream.url).then((response) => response.body?.pipeTo(writable));
353
+ return readable;
557
354
  }
558
- for (const targetNodeId of getNodeOutputs(node)) {
559
- if (targetNodeId !== "__exit__" && !getNode(targetNodeId)) {
560
- throw new NodesError("missing node", {
561
- id: targetNodeId
562
- });
355
+ return this.#data;
356
+ }
357
+ asyncIterable() {
358
+ const reader = this.stream().getReader();
359
+ return {
360
+ [Symbol.asyncIterator]() {
361
+ return {
362
+ async next() {
363
+ return reader.read();
364
+ },
365
+ async return() {
366
+ reader.cancel();
367
+ reader.releaseLock();
368
+ return { done: true, value: null };
369
+ }
370
+ };
563
371
  }
564
- }
372
+ };
565
373
  }
566
- const possiblePaths = getPossiblePaths({
567
- getInputs,
568
- getNode,
569
- onMissingInputs: (_node, path) => {
570
- throw new NodesError("no path from entry to node", {
571
- path: path.map(identify)
572
- });
573
- }
574
- });
575
- if (possiblePaths.every((possiblePath) => !possiblePath.includes("__entry__"))) {
576
- throw new NodesError("no path from entry to exit");
374
+ toString() {
375
+ return `RequenceStream<${this.mimeType}>`;
577
376
  }
578
- for (const possiblePath of possiblePaths) {
579
- for (const pathSegment of possiblePath) {
580
- const node = pathSegment === "__exit__" ? null : getNode(pathSegment);
581
- if (node?.type === "catch" && possiblePath.includes(node.subject)) {
582
- throw new NodesError("Unresolvable, inputs needs both catch and subject", {
583
- path: possiblePath.map(identify)
584
- });
585
- }
586
- }
377
+ toJSON() {
378
+ return `RequenceStream<${this.mimeType}>`;
587
379
  }
588
- return nodes;
589
- });
380
+ }
590
381
 
591
- // ../helpers/src/protocol/command.ts
592
- var abortSchema = z5.object({
593
- type: z5.literal("ABORT"),
594
- reason: z5.string().optional()
595
- });
596
- var nodeOptionsSchema = z5.object({
597
- maxExecutions: z5.number().int().min(0).optional().default(10)
598
- });
599
- var createNodesSchema = z5.object({
600
- type: z5.literal("CREATE_NODES"),
601
- nodes: nodesSchema,
602
- input: z5.any(),
603
- meta: z5.any(),
604
- options: nodeOptionsSchema
605
- });
606
- var commandSchema = z5.union([abortSchema, createNodesSchema]);
607
- // ../helpers/src/protocol/update.ts
608
- import { z as z6 } from "zod";
609
- var baseUpdateSchema = z6.object({
610
- timestamp: z6.number().int().transform((int) => new Date(int))
611
- });
612
- var baseNodeUpdateSchema = baseUpdateSchema.extend({
613
- nodeId: z6.string().uuid()
614
- });
615
- var nodeStartUpdateSchema = baseNodeUpdateSchema.extend({
616
- type: z6.literal("NODE_START"),
617
- context: contextSchema
618
- });
619
- var nodeErrorUpdateSchema = baseNodeUpdateSchema.extend({
620
- type: z6.literal("NODE_ERROR"),
621
- error: z6.string(),
622
- context: contextSchema
623
- });
624
- var nodeUpdateSchema = baseNodeUpdateSchema.extend({
625
- type: z6.literal("NODE_UPDATE"),
626
- output: z6.string(),
627
- data: z6.unknown(),
628
- context: contextSchema
629
- });
630
- var nodeFinishedUpdateSchema = baseNodeUpdateSchema.extend({
631
- type: z6.literal("NODE_FINISHED"),
632
- context: contextSchema
633
- });
634
- var nodeDebugUpdateSchema = baseNodeUpdateSchema.extend({
635
- type: z6.literal("NODE_DEBUG"),
636
- severity: z6.enum(["log", "info", "warn", "error"]),
637
- data: z6.unknown(),
638
- context: contextSchema
639
- });
640
- var nodeDeferUpdateSchema = baseNodeUpdateSchema.extend({
641
- type: z6.literal("NODE_DEFER"),
642
- data: z6.unknown(),
643
- context: contextSchema
644
- });
645
- var taskStartUpdateSchema = baseUpdateSchema.extend({
646
- type: z6.literal("TASK_START"),
647
- nodes: nodesSchema,
648
- context: contextSchema
649
- });
650
- var taskErrorUpdateSchema = baseUpdateSchema.extend({
651
- type: z6.literal("TASK_ERROR"),
652
- reason: z6.string().optional(),
653
- context: contextSchema
382
+ // ../helpers/src/files/streamObject.ts
383
+ import { z as z3 } from "zod/v4";
384
+ var streamObjectSchema = z3.object({
385
+ mime: z3.string(),
386
+ url: z3.string().url(),
387
+ __REQUENCE_type: z3.literal("RequenceStream")
654
388
  });
655
- var taskFinishedUpdateSchema = baseUpdateSchema.extend({
656
- type: z6.literal("TASK_FINISHED"),
657
- context: contextSchema
389
+ function isStreamObject(data) {
390
+ return streamObjectSchema.safeParse(data).success;
391
+ }
392
+ function toStreamObject(streamInfo) {
393
+ return {
394
+ ...streamInfo,
395
+ __REQUENCE_type: "RequenceStream"
396
+ };
397
+ }
398
+
399
+ // ../helpers/src/files/fileObject.ts
400
+ import { z as z4 } from "zod/v4";
401
+ var fileObjectSchema = z4.object({
402
+ size: z4.int().positive(),
403
+ mime: z4.string(),
404
+ url: z4.url(),
405
+ __REQUENCE_type: z4.literal("RequenceFile")
658
406
  });
659
- var updateSchema = z6.discriminatedUnion("type", [
660
- nodeStartUpdateSchema,
661
- nodeErrorUpdateSchema,
662
- nodeUpdateSchema,
663
- nodeFinishedUpdateSchema,
664
- nodeDebugUpdateSchema,
665
- nodeDeferUpdateSchema,
666
- taskStartUpdateSchema,
667
- taskErrorUpdateSchema,
668
- taskFinishedUpdateSchema
669
- ]);
407
+ function toFileObject(fileInfo) {
408
+ return {
409
+ ...fileInfo,
410
+ __REQUENCE_type: "RequenceFile"
411
+ };
412
+ }
413
+ function isFileObject(data) {
414
+ return fileObjectSchema.safeParse(data).success;
415
+ }
416
+
417
+ // ../helpers/src/utils/resolveRequenceTypes.ts
418
+ function resolveRequenceTypes(data, onCallback) {
419
+ return mapData(data, {
420
+ Object(obj) {
421
+ if (isFileObject(obj)) {
422
+ return RequenceFile.fromFileObject(obj);
423
+ }
424
+ if (isStreamObject(obj)) {
425
+ return RequenceStream.fromStreamObject(obj);
426
+ }
427
+ if (isCallbackObject(obj)) {
428
+ return (arg) => {
429
+ onCallback?.({ ...obj, arg });
430
+ };
431
+ }
432
+ }
433
+ });
434
+ }
435
+
436
+ // src/index.ts
437
+ import { z as z6 } from "zod/v4";
438
+
670
439
  // src/createAmqpConnection.ts
671
- import { connect } from "amqp-connection-manager";
672
- import { z as z7 } from "zod";
440
+ import {
441
+ connect
442
+ } from "amqp-connection-manager";
443
+ import { z as z5 } from "zod/v4";
673
444
 
674
445
  // src/helpers.ts
446
+ import { AsyncLocalStorage } from "node:async_hooks";
675
447
  class RetryError extends Error {
676
448
  delay;
677
449
  constructor(delay) {
@@ -680,92 +452,160 @@ class RetryError extends Error {
680
452
  }
681
453
  }
682
454
 
455
+ class SkipError extends Error {
456
+ }
457
+
683
458
  class AbortError extends Error {
684
459
  }
685
460
  var OUTPUT_VALUE = Symbol("output_value");
686
461
  function isOutputValue(value) {
687
462
  return value !== null && typeof value === "object" && OUTPUT_VALUE in value;
688
463
  }
689
- function unwrapResult(result) {
690
- if (isOutputValue(result)) {
691
- return { value: result.value, outputName: result[OUTPUT_VALUE] };
464
+ function processData(params) {
465
+ return mapOutput({
466
+ value: mapData(params.data, {
467
+ Function(data, path) {
468
+ return {
469
+ ...params.onCallback(data),
470
+ outputName: params.outputName,
471
+ propertyPath: path,
472
+ __REQUENCE_type: "RequenceCallback"
473
+ };
474
+ }
475
+ }),
476
+ options: params.options,
477
+ onDone: params.onDone
478
+ });
479
+ }
480
+ async function unwrapResult(params) {
481
+ if (isOutputValue(params.result)) {
482
+ return {
483
+ value: await processData({
484
+ outputName: params.result[OUTPUT_VALUE],
485
+ data: params.result.value,
486
+ options: params.options,
487
+ onDone: params.onDone,
488
+ onCallback: params.onCallback
489
+ }),
490
+ outputName: params.result[OUTPUT_VALUE]
491
+ };
692
492
  }
693
- return { value: result, outputName: null };
493
+ return {
494
+ value: await processData({
495
+ outputName: null,
496
+ data: params.result,
497
+ options: params.options,
498
+ onDone: params.onDone,
499
+ onCallback: params.onCallback
500
+ }),
501
+ outputName: null
502
+ };
694
503
  }
695
- function createExtendedContextHelper(options) {
696
- const contextHelper = createContextHelper(options.context, options.nodes);
697
- const internalContext = getInternalContext(contextHelper);
698
- return Object.assign(contextHelper, {
699
- taskId: options.taskId,
700
- toOutput(name, value) {
701
- return {
702
- [OUTPUT_VALUE]: name,
703
- value
704
- };
705
- },
706
- defer: options.onDefer,
707
- getConfiguration() {
708
- const result = internalContext.results.get(options.serviceId);
709
- if (result?.node.type === "service") {
710
- return result.node.configuration ?? null;
711
- }
712
- return null;
713
- },
714
- getNode() {
715
- return internalContext.results.get(options.serviceId).node;
716
- },
717
- state: createObjectProxy(options.state, options.onStateChange),
718
- debug: {
719
- log(...data) {
720
- options.onLog("log", data);
504
+ function createContextHelper(options) {
505
+ const terminatePromise = createRemotePromise();
506
+ return [
507
+ {
508
+ taskId: options.taskId,
509
+ input: resolveRequenceTypes(options.input, options.onCallback),
510
+ configuration: resolveRequenceTypes(options.configuration, () => {
511
+ throw new Error("configuration may not have callbacks");
512
+ }),
513
+ toOutput(name, value) {
514
+ return {
515
+ [OUTPUT_VALUE]: name,
516
+ value
517
+ };
518
+ },
519
+ defer: options.onDefer,
520
+ debug: {
521
+ log(...data) {
522
+ options.onLog("log", data);
523
+ },
524
+ info(...data) {
525
+ options.onLog("info", data);
526
+ },
527
+ warn(...data) {
528
+ options.onLog("warn", data);
529
+ },
530
+ error(...data) {
531
+ options.onLog("error", data);
532
+ }
721
533
  },
722
- info(...data) {
723
- options.onLog("info", data);
534
+ retry(delay) {
535
+ throw new RetryError(delay);
724
536
  },
725
- warn(...data) {
726
- options.onLog("warn", data);
537
+ abort(reason) {
538
+ throw new AbortError(reason);
727
539
  },
728
- error(...data) {
729
- options.onLog("error", data);
730
- }
731
- },
732
- retry(delay) {
733
- throw new RetryError(delay);
540
+ skip() {
541
+ throw new SkipError;
542
+ },
543
+ terminated: terminatePromise.promise
734
544
  },
735
- abort(reason) {
736
- throw new AbortError(reason);
545
+ terminatePromise
546
+ ];
547
+ }
548
+ var handlerStorage = new AsyncLocalStorage;
549
+
550
+ // src/mapInput.ts
551
+ function mapInput(data) {
552
+ return mapData(data, {
553
+ Object(obj) {
554
+ if (isFileObject(obj)) {
555
+ return RequenceFile.fromFileObject(obj);
556
+ }
557
+ if (isStreamObject(obj)) {
558
+ return RequenceStream.fromStreamObject(obj);
559
+ }
737
560
  }
738
561
  });
739
562
  }
740
563
 
741
564
  // src/createAmqpConnection.ts
742
- var messageKeySchema = z7.string().transform((str) => deobfuscate(str)).pipe(z7.array(z7.string().uuid()).length(3)).transform((arr) => ({
565
+ var messageKeySchema = z5.string().transform((str) => deobfuscate(str)).pipe(z5.tuple([z5.uuid(), z5.uuid()]).rest(z5.string())).transform((arr) => ({
743
566
  taskId: arr[0],
744
- serviceId: arr[1],
745
- messageId: arr[2]
567
+ messageId: arr[1],
568
+ uploadUrl: arr[2] || undefined,
569
+ streamUrl: arr[3] || undefined
746
570
  }));
747
- var headerSchema = z7.object({
748
- properties: z7.object({
749
- correlationId: z7.string().uuid(),
750
- headers: z7.object({
751
- version: z7.string(),
752
- taskId: z7.string().uuid(),
753
- serviceId: z7.string().uuid()
571
+ var headerSchema = z5.object({
572
+ properties: z5.object({
573
+ correlationId: z5.uuid(),
574
+ headers: z5.object({
575
+ taskId: z5.uuid()
754
576
  })
755
577
  })
756
578
  }).transform((msg) => ({
757
- version: msg.properties.headers.version,
758
579
  messageId: msg.properties.correlationId,
759
- taskId: msg.properties.headers.taskId,
760
- serviceId: msg.properties.headers.serviceId
580
+ taskId: msg.properties.headers.taskId
761
581
  }));
762
- var payloadSchema = z7.object({ content: z7.instanceof(Buffer) }).transform((msg) => JSON.parse(msg.content.toString())).pipe(z7.object({
763
- context: contextSchema,
764
- meta: z7.object({
765
- nodes: nodesSchema,
766
- state: z7.record(z7.any())
582
+ var payloadSchema = z5.object({ content: z5.instanceof(Buffer) }).transform((msg) => JSON.parse(msg.content.toString())).pipe(z5.object({
583
+ input: z5.unknown(),
584
+ configuration: z5.unknown(),
585
+ options: z5.object({
586
+ uploadUrl: z5.url().optional(),
587
+ streamUrl: z5.url().optional()
588
+ })
589
+ }));
590
+ var backchannelMessageSchema = z5.object({
591
+ content: z5.instanceof(Buffer).transform((content) => JSON.parse(content.toString())).pipe(z5.discriminatedUnion("type", [
592
+ z5.object({
593
+ type: z5.literal("stop")
594
+ }),
595
+ z5.object({
596
+ type: z5.literal("callback"),
597
+ callbackId: z5.uuid(),
598
+ arg: z5.any()
599
+ })
600
+ ])),
601
+ properties: z5.object({
602
+ correlationId: z5.string()
767
603
  })
604
+ }).transform((message) => ({
605
+ payload: message.content,
606
+ messageId: message.properties.correlationId
768
607
  }));
608
+ var abortSymbol = Symbol();
769
609
  function isMessageHandlerGenerator(handler) {
770
610
  return handler.constructor.name === "GeneratorFunction" || handler.constructor.name === "AsyncGeneratorFunction";
771
611
  }
@@ -775,12 +615,13 @@ function createConnection({
775
615
  version,
776
616
  prefetch = 1,
777
617
  silent = false,
778
- connectionTimeout
618
+ connectionTimeout,
619
+ connectionOptions
779
620
  }, messageHandler) {
780
621
  const queue = `${url.username}@${version}`;
781
622
  const exchange = url.username;
782
- const connection = connect(url.toString());
783
- const connectedPromise = new Promise((resolve, reject) => {
623
+ const connection = connect(url.toString(), { connectionOptions });
624
+ const connectedPromise = new Promise((resolve2, reject) => {
784
625
  const unsubscribe = () => {
785
626
  clearTimeout(timeout);
786
627
  connection.removeListener("connect", handleConnect);
@@ -791,7 +632,7 @@ function createConnection({
791
632
  }, connectionTimeout);
792
633
  const handleConnect = () => {
793
634
  unsubscribe();
794
- resolve();
635
+ resolve2();
795
636
  };
796
637
  const handleConnectFailed = ({ err }) => {
797
638
  unsubscribe();
@@ -800,255 +641,470 @@ function createConnection({
800
641
  connection.addListener("connect", handleConnect);
801
642
  connection.addListener("connectFailed", handleConnectFailed);
802
643
  });
803
- const channel = connection.createChannel({
804
- async setup(channel2) {
805
- await channel2.checkExchange(exchange);
806
- await channel2.checkExchange(`${exchange}-retry`);
807
- await channel2.checkQueue(queue);
808
- await channel2.prefetch(prefetch);
644
+ const connectionId = crypto.randomUUID();
645
+ const backchannelQueue = `${queue}-backchannel-${connectionId}`;
646
+ const channelWrapper = connection.createChannel({
647
+ async setup(channel) {
648
+ await channel.checkExchange(exchange);
649
+ await channel.checkExchange(`${exchange}-retry`);
650
+ await channel.checkQueue(queue);
651
+ await channel.prefetch(prefetch);
809
652
  }
810
653
  });
811
654
  const publish = ({
812
655
  data,
813
656
  outputName,
814
657
  messageId,
658
+ priority,
815
659
  ...headers
816
- }) => {
817
- channel.publish(exchange, "", Buffer.from(JSON.stringify(data ?? null)), {
818
- correlationId: messageId,
819
- contentType: "application/json",
820
- headers: {
821
- outputName: outputName ?? null,
822
- ...headers
823
- }
824
- });
825
- };
826
- channel.consume(queue, async (message) => {
827
- if (message.properties.headers?.abort || message.properties.headers?.exception) {
828
- channel.nack(message, false, false);
829
- return;
660
+ }) => channelWrapper.publish(exchange, "", Buffer.from(JSON.stringify(data ?? null)), {
661
+ correlationId: messageId,
662
+ contentType: "application/json",
663
+ persistent: true,
664
+ priority,
665
+ headers: {
666
+ outputName: outputName ?? null,
667
+ connectionId,
668
+ libVersion: "javascript@1.0.0-alpha.45",
669
+ ...headers
830
670
  }
831
- let removeActiveMessage = () => {
832
- };
833
- try {
834
- let deferred = false;
835
- let deferredReason = null;
836
- const { messageId, serviceId, taskId } = headerSchema.parse(message);
837
- activeMessages.add(messageId);
838
- removeActiveMessage = () => activeMessages.delete(messageId);
839
- const payload = payloadSchema.parse(message);
840
- let acked = false;
841
- const ack = () => {
842
- if (!acked) {
843
- acked = true;
844
- channel.ack(message);
671
+ });
672
+ const generatorTerminators = new Map;
673
+ const callbacks = new Map;
674
+ channelWrapper.addSetup(async (channel) => {
675
+ await channel.assertQueue(backchannelQueue, {
676
+ exclusive: true
677
+ });
678
+ await channel.bindQueue(backchannelQueue, "service", backchannelQueue);
679
+ await channel.consume(backchannelQueue, async (message) => {
680
+ const result = backchannelMessageSchema.safeParse(message);
681
+ if (!result.success) {
682
+ return;
683
+ }
684
+ const backchannelMessage = result.data;
685
+ switch (backchannelMessage.payload.type) {
686
+ case "stop": {
687
+ generatorTerminators.get(backchannelMessage.messageId)?.("task stopped");
688
+ break;
845
689
  }
846
- };
847
- let immediateUpdateState;
848
- const extendedContext = createExtendedContextHelper({
849
- serviceId,
850
- context: payload.context,
851
- nodes: payload.meta.nodes,
852
- taskId,
853
- state: payload.meta.state,
854
- onStateChange(newState) {
855
- clearImmediate(immediateUpdateState);
856
- immediateUpdateState = setImmediate(() => {
690
+ case "callback": {
691
+ callbacks.get(backchannelMessage.payload.callbackId)?.(backchannelMessage.payload.arg);
692
+ break;
693
+ }
694
+ }
695
+ }, {
696
+ noAck: true
697
+ });
698
+ });
699
+ channelWrapper.addSetup(async (channel) => {
700
+ channel.consume(queue, async (message) => {
701
+ if (!message) {
702
+ return;
703
+ }
704
+ let publishIndex = 0;
705
+ const donePromises = [];
706
+ const registeredCallbackIds = new Set;
707
+ let removeActiveMessage = () => {};
708
+ const { messageId, taskId } = headerSchema.parse(message);
709
+ try {
710
+ let deferred = false;
711
+ let deferredReason = null;
712
+ activeMessages.add(messageId);
713
+ removeActiveMessage = () => activeMessages.delete(messageId);
714
+ const payload = payloadSchema.parse(message);
715
+ const [extendedContext, terminatePromise] = createContextHelper({
716
+ taskId,
717
+ input: mapInput(payload.input),
718
+ configuration: mapInput(payload.configuration),
719
+ onLog(debugMethod, data) {
857
720
  publish({
721
+ index: publishIndex++,
722
+ version,
858
723
  messageId,
859
724
  taskId,
860
- serviceId,
861
- data: clone(newState),
862
- state: true
725
+ data,
726
+ debugMethod,
727
+ priority: message.properties.priority,
728
+ debug: true
863
729
  });
730
+ },
731
+ onDefer(reason) {
732
+ deferred = true;
733
+ deferredReason = reason || null;
734
+ return obfuscate(taskId, messageId, payload.options.uploadUrl ?? "", payload.options.streamUrl ?? "");
735
+ },
736
+ onCallback(params) {
737
+ publish({
738
+ index: 0,
739
+ version,
740
+ taskId,
741
+ messageId,
742
+ data: params.arg,
743
+ outputName: params.outputName,
744
+ connectionId: params.sourceId,
745
+ callbackId: params.callbackId,
746
+ propertyPath: params.propertyPath
747
+ });
748
+ }
749
+ });
750
+ await publish({
751
+ index: publishIndex++,
752
+ version,
753
+ messageId,
754
+ taskId,
755
+ priority: message.properties.priority,
756
+ begin: true
757
+ });
758
+ if (isMessageHandlerGenerator(messageHandler)) {
759
+ const generator = messageHandler(extendedContext);
760
+ const terminationPromise = createRemotePromise();
761
+ generatorTerminators.set(messageId, (reason) => {
762
+ generator.return();
763
+ terminationPromise.resolve(abortSymbol);
764
+ terminatePromise.resolve(reason);
864
765
  });
865
- },
866
- onLog(debugMethod, data) {
867
- publish({
868
- messageId,
869
- taskId,
870
- serviceId,
871
- data,
872
- debugMethod,
873
- debug: true
766
+ await handlerStorage.run(extendedContext, async () => {
767
+ while (true) {
768
+ const next = await Promise.race([
769
+ terminationPromise,
770
+ generator.next()
771
+ ]);
772
+ if (next === abortSymbol) {
773
+ break;
774
+ }
775
+ const { value: result, done } = next;
776
+ if (deferred) {
777
+ deferred = false;
778
+ console.warn("returning a value in a deferred message resets the deferred status");
779
+ }
780
+ const donePromise = createRemotePromise();
781
+ donePromises.push(donePromise);
782
+ const { value, outputName } = await unwrapResult({
783
+ result,
784
+ options: payload.options,
785
+ onDone: donePromise.resolve,
786
+ onCallback: (callback) => {
787
+ const callbackId = crypto.randomUUID();
788
+ registeredCallbackIds.add(callbackId);
789
+ callbacks.set(callbackId, callback);
790
+ return {
791
+ sourceId: connectionId,
792
+ callbackId
793
+ };
794
+ }
795
+ });
796
+ if (!done || typeof value !== "undefined") {
797
+ publish({
798
+ index: publishIndex++,
799
+ version,
800
+ messageId,
801
+ taskId,
802
+ data: value,
803
+ priority: message.properties.priority,
804
+ outputName
805
+ });
806
+ }
807
+ if (done) {
808
+ break;
809
+ }
810
+ }
874
811
  });
875
- },
876
- onDefer(reason) {
877
- deferred = true;
878
- deferredReason = reason || null;
879
- ack();
880
- return obfuscate(taskId, serviceId, messageId);
881
- }
882
- });
883
- if (isMessageHandlerGenerator(messageHandler)) {
884
- const generator = messageHandler(extendedContext);
885
- while (true) {
886
- const { value: result, done } = await generator.next();
887
- ack();
888
- if (deferred) {
889
- deferred = false;
812
+ } else {
813
+ const result = await handlerStorage.run(extendedContext, () => messageHandler(extendedContext));
814
+ const donePromise = createRemotePromise();
815
+ donePromises.push(donePromise);
816
+ const { value, outputName } = await unwrapResult({
817
+ result,
818
+ options: payload.options,
819
+ onDone: donePromise.resolve,
820
+ onCallback: () => {
821
+ throw new Error("callbacks can only be used in generator functions");
822
+ }
823
+ });
824
+ if (deferred && value) {
890
825
  console.warn("returning a value in a deferred message resets the deferred status");
826
+ deferred = false;
891
827
  }
892
- const { value, outputName } = unwrapResult(result);
893
- if (!done || typeof value !== "undefined") {
828
+ if (!deferred || value) {
894
829
  publish({
830
+ index: publishIndex++,
831
+ version,
895
832
  messageId,
896
833
  taskId,
897
- serviceId,
898
834
  data: value,
835
+ priority: message.properties.priority,
899
836
  outputName
900
837
  });
901
838
  }
902
- if (done) {
903
- break;
904
- }
905
839
  }
906
- } else {
907
- const result = await messageHandler(extendedContext);
908
- ack();
909
- const { value, outputName } = unwrapResult(result);
910
- if (deferred && value) {
911
- console.warn("returning a value in a deferred message resets the deferred status");
912
- deferred = false;
913
- }
914
- if (!deferred || value) {
840
+ setImmediate(async () => {
841
+ if (!deferred) {
842
+ await Promise.allSettled(donePromises);
843
+ }
915
844
  publish({
845
+ index: publishIndex++,
846
+ version,
916
847
  messageId,
917
848
  taskId,
918
- serviceId,
919
- data: value,
920
- outputName
849
+ data: deferredReason,
850
+ priority: message.properties.priority,
851
+ deferred,
852
+ done: !deferred
921
853
  });
922
- }
923
- }
924
- setImmediate(() => publish({
925
- messageId,
926
- taskId,
927
- serviceId,
928
- data: deferredReason,
929
- deferred,
930
- done: !deferred
931
- }));
932
- } catch (error) {
933
- if (error instanceof RetryError) {
934
- const properties = {
935
- ...message.properties,
936
- expiration: error.delay || 1000
937
- };
938
- channel.publish(`${exchange}-retry`, "retry", message.content, properties);
939
- channel.ack(message);
940
- return;
941
- }
942
- if (error instanceof AbortError && error.message.length > 0) {
943
- channel.publish(`${exchange}-retry`, "requeue", error.message, {
944
- ...message.properties,
945
- expiration: 0,
946
- priority: 0,
947
- contentType: "text/plain",
948
- headers: {
949
- ...message.properties.headers,
950
- abort: true
951
- }
854
+ channel.ack(message);
952
855
  });
953
- channel.ack(message);
954
- return;
955
- }
956
- if (error instanceof Error) {
957
- if (!silent) {
958
- console.error(`Encountered an error inside service handler:`);
959
- console.error(error);
856
+ } catch (error) {
857
+ if (error instanceof SkipError) {
858
+ channel.nack(message);
859
+ return;
960
860
  }
961
- channel.publish(`${exchange}-retry`, "requeue", message.content, {
962
- ...message.properties,
963
- expiration: 0,
964
- priority: 0,
965
- headers: {
966
- ...message.properties.headers,
967
- exception: true,
968
- "error-message": error.message || "error in service handler"
861
+ if (error instanceof RetryError) {
862
+ channel.ack(message);
863
+ const properties = {
864
+ ...message.properties,
865
+ expiration: error.delay || 1000
866
+ };
867
+ channel.publish(`${exchange}-retry`, version, message.content, properties);
868
+ return;
869
+ }
870
+ if (error instanceof AbortError && error.message.length > 0) {
871
+ channelWrapper.ack(message);
872
+ channelWrapper.publish(`${exchange}-retry`, "operator", error.message, {
873
+ ...message.properties,
874
+ contentType: "text/plain",
875
+ headers: {
876
+ ...message.properties.headers,
877
+ index: publishIndex++,
878
+ libVersion: "javascript@1.0.0-alpha.45",
879
+ abort: true
880
+ }
881
+ });
882
+ return;
883
+ }
884
+ if (error instanceof Error) {
885
+ if (!silent) {
886
+ console.error("Encountered an error inside service handler:");
887
+ console.error(error);
969
888
  }
970
- });
971
- channel.ack(message);
972
- return;
889
+ channel.ack(message);
890
+ channel.publish(`${exchange}-retry`, "operator", message.content, {
891
+ ...message.properties,
892
+ headers: {
893
+ ...message.properties.headers,
894
+ version,
895
+ exception: true,
896
+ index: publishIndex++,
897
+ libVersion: "javascript@1.0.0-alpha.45",
898
+ "error-message": error.message || "error in service handler"
899
+ }
900
+ });
901
+ return;
902
+ }
903
+ } finally {
904
+ generatorTerminators.delete(messageId);
905
+ registeredCallbackIds.forEach((id) => callbacks.delete(id));
906
+ removeActiveMessage();
973
907
  }
974
- channel.nack(message, false, false);
975
- } finally {
976
- removeActiveMessage();
977
- }
908
+ });
978
909
  });
979
910
  const api = {
980
911
  close: async () => {
981
- await channel.close();
912
+ await channelWrapper.close();
982
913
  await connection.close();
983
914
  },
984
915
  open: () => connectedPromise.then(() => api),
985
916
  async act(messageKey, actor) {
917
+ let publishIndex = 0;
918
+ const { taskId, messageId, ...options } = messageKeySchema.parse(messageKey);
919
+ const checkActiveMessage = () => {
920
+ if (activeMessages.has(messageId)) {
921
+ throw new Error("Cannot send deferred message while callback handler is still running");
922
+ }
923
+ };
924
+ const registeredCallbackIds = new Set;
925
+ const donePromises = [];
986
926
  await actor({
987
- sendToOutput(outputName, data) {
988
- const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
989
- if (activeMessages.has(messageId2)) {
990
- throw new Error("Cannot send deferred message while callback handler is still running");
991
- }
927
+ async sendToOutput(outputName, data) {
928
+ checkActiveMessage();
929
+ const donePromise = createRemotePromise();
930
+ donePromises.push(donePromise);
992
931
  publish({
993
- messageId: messageId2,
994
- taskId: taskId2,
995
- serviceId: serviceId2,
996
- data,
932
+ index: publishIndex++,
933
+ version,
934
+ messageId,
935
+ taskId,
936
+ data: await processData({
937
+ outputName,
938
+ data,
939
+ options,
940
+ onDone: donePromise.resolve,
941
+ onCallback: (callback) => {
942
+ const callbackId = crypto.randomUUID();
943
+ registeredCallbackIds.add(callbackId);
944
+ callbacks.set(callbackId, callback);
945
+ return {
946
+ sourceId: connectionId,
947
+ callbackId
948
+ };
949
+ }
950
+ }),
997
951
  outputName
998
952
  });
999
953
  },
1000
- send(data) {
1001
- const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
1002
- if (activeMessages.has(messageId2)) {
1003
- throw new Error("Cannot send deferred message while callback handler is still running");
1004
- }
954
+ async send(data) {
955
+ checkActiveMessage();
956
+ const donePromise = createRemotePromise();
957
+ donePromises.push(donePromise);
1005
958
  publish({
1006
- messageId: messageId2,
1007
- taskId: taskId2,
1008
- serviceId: serviceId2,
1009
- data
959
+ index: publishIndex++,
960
+ version,
961
+ messageId,
962
+ taskId,
963
+ data: await processData({
964
+ outputName: null,
965
+ data,
966
+ options,
967
+ onDone: donePromise.resolve,
968
+ onCallback: (callback) => {
969
+ const callbackId = crypto.randomUUID();
970
+ registeredCallbackIds.add(callbackId);
971
+ callbacks.set(callbackId, callback);
972
+ return {
973
+ sourceId: connectionId,
974
+ callbackId
975
+ };
976
+ }
977
+ })
1010
978
  });
1011
979
  },
1012
980
  abort(error) {
1013
- const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
1014
- if (activeMessages.has(messageId2)) {
1015
- throw new Error("Cannot send deferred message while callback handler is still running");
1016
- }
1017
- channel.publish(`${exchange}-retry`, "requeue", error instanceof Error ? error.message : error, {
1018
- correlationId: messageId2,
981
+ checkActiveMessage();
982
+ channelWrapper.publish(`${exchange}-retry`, "operator", error instanceof Error ? error.message : error, {
983
+ persistent: true,
984
+ correlationId: messageId,
1019
985
  expiration: 0,
1020
986
  priority: 0,
1021
987
  contentType: "text/plain",
1022
988
  headers: {
1023
- taskId: taskId2,
1024
- serviceId: serviceId2,
989
+ taskId,
990
+ libVersion: "javascript@1.0.0-alpha.45",
991
+ index: publishIndex++,
1025
992
  abort: true
1026
993
  }
1027
994
  });
1028
995
  }
1029
996
  });
1030
- const { taskId, serviceId, messageId } = messageKeySchema.parse(messageKey);
1031
- setImmediate(() => publish({
1032
- messageId,
1033
- taskId,
1034
- serviceId,
1035
- done: true
1036
- }));
997
+ setImmediate(async () => {
998
+ await Promise.allSettled(donePromises);
999
+ registeredCallbackIds.forEach((id) => callbacks.delete(id));
1000
+ publish({
1001
+ index: publishIndex++,
1002
+ version,
1003
+ messageId,
1004
+ taskId,
1005
+ done: true
1006
+ });
1007
+ });
1037
1008
  }
1038
1009
  };
1039
1010
  return api;
1040
1011
  }
1012
+ // src/utils.ts
1013
+ function isAsyncIterable(iterable) {
1014
+ return typeof iterable[Symbol.asyncIterator] === "function";
1015
+ }
1016
+ function wrapIterable(iterable) {
1017
+ const context = handlerStorage.getStore();
1018
+ if (!context) {
1019
+ return iterable;
1020
+ }
1021
+ let terminated = false;
1022
+ context.terminated.then(() => {
1023
+ terminated = true;
1024
+ });
1025
+ if (isAsyncIterable(iterable)) {
1026
+ return {
1027
+ [Symbol.asyncIterator]() {
1028
+ const iterator = iterable[Symbol.asyncIterator]();
1029
+ return {
1030
+ async next() {
1031
+ const result = await Promise.race([
1032
+ context.terminated,
1033
+ iterator.next()
1034
+ ]);
1035
+ if (terminated) {
1036
+ return { done: true, value: undefined };
1037
+ }
1038
+ return result;
1039
+ }
1040
+ };
1041
+ }
1042
+ };
1043
+ }
1044
+ return {
1045
+ [Symbol.iterator]() {
1046
+ const iterator = iterable[Symbol.iterator]();
1047
+ return {
1048
+ next() {
1049
+ if (terminated) {
1050
+ return { done: true, value: undefined };
1051
+ }
1052
+ const result = iterator.next();
1053
+ return result;
1054
+ }
1055
+ };
1056
+ }
1057
+ };
1058
+ }
1059
+ function asyncEventEmitter(initial = []) {
1060
+ const context = handlerStorage.getStore();
1061
+ let terminated = false;
1062
+ context?.terminated.then(() => {
1063
+ terminated = true;
1064
+ });
1065
+ let resolve2;
1066
+ const initialValues = structuredClone(initial);
1067
+ return {
1068
+ push: (value) => {
1069
+ if (resolve2) {
1070
+ resolve2(value);
1071
+ } else {
1072
+ initialValues.push(value);
1073
+ }
1074
+ },
1075
+ [Symbol.asyncIterator]() {
1076
+ return {
1077
+ async next() {
1078
+ if (initialValues.length > 0) {
1079
+ return { value: initialValues.shift(), done: false };
1080
+ }
1081
+ const defer = Promise.withResolvers();
1082
+ resolve2 = defer.resolve;
1083
+ if (context) {
1084
+ const value = await Promise.race([
1085
+ defer.promise,
1086
+ context.terminated
1087
+ ]);
1088
+ return terminated ? { done: true, value: undefined } : { done: false, value };
1089
+ }
1090
+ return { value: await defer.promise, done: false };
1091
+ }
1092
+ };
1093
+ }
1094
+ };
1095
+ }
1041
1096
 
1042
1097
  // src/index.ts
1043
- var connectionOptionsSchema = z8.object({
1044
- url: z8.union([
1045
- z8.string().regex(/^amqps?:\/\/(.+):(.+)@(.+)$/).transform((str) => new URL(str)),
1046
- z8.instanceof(URL).refine((url) => url.protocol.match(/^amqps?:/), "Wrong protocol")
1098
+ var connectionOptionsSchema = z6.object({
1099
+ url: z6.union([
1100
+ z6.string().regex(/^amqps?:\/\/(.+):(.+)@(.+)$/).transform((str) => new URL(str)),
1101
+ z6.instanceof(URL).refine((url) => url.protocol.match(/^amqps?:/), "Wrong protocol")
1047
1102
  ]),
1048
- version: z8.string(),
1049
- silent: z8.boolean().optional(),
1050
- prefetch: z8.number().int().optional(),
1051
- connectionTimeout: z8.number().positive().default(3000)
1103
+ version: z6.string(),
1104
+ silent: z6.boolean().optional(),
1105
+ prefetch: z6.number().int().optional(),
1106
+ connectionTimeout: z6.number().positive().default(3000),
1107
+ connectionOptions: z6.any()
1052
1108
  });
1053
1109
  function createService(optionsOrVersion, optionalMessageHandler) {
1054
1110
  let options;
@@ -1062,7 +1118,13 @@ function createService(optionsOrVersion, optionalMessageHandler) {
1062
1118
  options = optionsOrVersion;
1063
1119
  messageHandler = optionalMessageHandler;
1064
1120
  }
1065
- const token = options.accessToken ?? process.env.REQUENCE_ACCESS_TOKEN ?? JSON.parse(readFileSync("package.json", "utf-8")).requence?.accessToken;
1121
+ let token = options.accessToken ?? process.env.REQUENCE_SERVICE_ACCESS_TOKEN ?? process.env.REQUENCE_ACCESS_TOKEN;
1122
+ if (!token) {
1123
+ try {
1124
+ const pkgJson = JSON.parse(fs.readFileSync("package.json", "utf-8"));
1125
+ token = pkgJson.requence?.service?.accessToken ?? pkgJson.requence?.accessToken;
1126
+ } catch {}
1127
+ }
1066
1128
  if (!token) {
1067
1129
  throw new Error("No service key found");
1068
1130
  }
@@ -1077,8 +1139,13 @@ function createService(optionsOrVersion, optionalMessageHandler) {
1077
1139
  return createConnection(connectionOptionsSchema.parse(connectionOptions), messageHandler);
1078
1140
  }
1079
1141
  export {
1080
- createService
1142
+ wrapIterable,
1143
+ createService,
1144
+ createCallback,
1145
+ asyncEventEmitter,
1146
+ RequenceStream,
1147
+ RequenceFile
1081
1148
  };
1082
1149
 
1083
- //# debugId=1AE0F5F375D764C164756E2164756E21
1150
+ //# debugId=A727A68F2D25EA2864756E2164756E21
1084
1151
  //# sourceMappingURL=index.js.map