@abyss-project/runtime 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +32 -0
- package/.prettierrc +5 -0
- package/README.md +28 -3
- package/dist/access/access.types.d.ts +14 -0
- package/dist/access/access.types.js +9 -0
- package/dist/access/access.types.js.map +1 -0
- package/dist/access/host-match.d.ts +1 -0
- package/dist/access/host-match.js +14 -0
- package/dist/access/host-match.js.map +1 -0
- package/dist/cost/execution-cost.d.ts +45 -0
- package/dist/cost/execution-cost.js +114 -0
- package/dist/cost/execution-cost.js.map +1 -0
- package/dist/definition/definition.limits.d.ts +4 -0
- package/dist/definition/definition.limits.js +8 -0
- package/dist/definition/definition.limits.js.map +1 -0
- package/dist/definition/definition.schema.d.ts +8 -0
- package/dist/definition/definition.schema.js +123 -0
- package/dist/definition/definition.schema.js.map +1 -0
- package/dist/definition/definition.types.d.ts +117 -0
- package/dist/definition/definition.types.js +37 -0
- package/dist/definition/definition.types.js.map +1 -0
- package/dist/definition/validate-definition.d.ts +9 -0
- package/dist/definition/validate-definition.js +163 -0
- package/dist/definition/validate-definition.js.map +1 -0
- package/dist/definition/walk-steps.d.ts +5 -0
- package/dist/definition/walk-steps.js +31 -0
- package/dist/definition/walk-steps.js.map +1 -0
- package/dist/engine/engine-entry.d.ts +1 -0
- package/dist/engine/engine-entry.js +6 -0
- package/dist/engine/engine-entry.js.map +1 -0
- package/dist/engine/engine-global.d.ts +1 -0
- package/dist/engine/engine-global.js +5 -0
- package/dist/engine/engine-global.js.map +1 -0
- package/dist/engine/engine-source.d.ts +2 -0
- package/dist/engine/engine-source.js +3 -0
- package/dist/engine/run-in-isolate.d.ts +34 -0
- package/dist/engine/run-in-isolate.js +267 -0
- package/dist/engine/run-in-isolate.js.map +1 -0
- package/dist/errors/runtime-error-code.enum.d.ts +18 -0
- package/dist/errors/runtime-error-code.enum.js +19 -0
- package/dist/errors/runtime-error-code.enum.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/dist/interpreter/interpreter-error.d.ts +5 -0
- package/dist/interpreter/interpreter-error.js +12 -0
- package/dist/interpreter/interpreter-error.js.map +1 -0
- package/dist/interpreter/interpreter.d.ts +30 -0
- package/dist/interpreter/interpreter.js +313 -0
- package/dist/interpreter/interpreter.js.map +1 -0
- package/dist/interpreter/interpreter.types.d.ts +152 -0
- package/dist/interpreter/interpreter.types.js +31 -0
- package/dist/interpreter/interpreter.types.js.map +1 -0
- package/dist/interpreter/sequence-path.d.ts +6 -0
- package/dist/interpreter/sequence-path.js +53 -0
- package/dist/interpreter/sequence-path.js.map +1 -0
- package/dist/interpreter/test-host.d.ts +18 -0
- package/dist/interpreter/test-host.js +43 -0
- package/dist/interpreter/test-host.js.map +1 -0
- package/dist/runner-protocol/evaluation.types.d.ts +20 -0
- package/dist/runner-protocol/evaluation.types.js +10 -0
- package/dist/runner-protocol/evaluation.types.js.map +1 -0
- package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
- package/dist/runner-protocol/execution-protocol.types.js +48 -0
- package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
- package/dist/server/code-runner-error.d.ts +5 -0
- package/dist/server/code-runner-error.js +12 -0
- package/dist/server/code-runner-error.js.map +1 -0
- package/dist/server/code-runner-session.d.ts +28 -0
- package/dist/server/code-runner-session.js +208 -0
- package/dist/server/code-runner-session.js.map +1 -0
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +10 -0
- package/dist/server/index.js.map +1 -0
- package/dist/steps/execute-step.d.ts +50 -0
- package/dist/steps/execute-step.js +136 -0
- package/dist/steps/execute-step.js.map +1 -0
- package/dist/steps/global-references.d.ts +2 -0
- package/dist/steps/global-references.js +28 -0
- package/dist/steps/global-references.js.map +1 -0
- package/dist/steps/step-access.d.ts +8 -0
- package/dist/steps/step-access.js +39 -0
- package/dist/steps/step-access.js.map +1 -0
- package/dist/steps/step-fields.d.ts +5 -0
- package/dist/steps/step-fields.js +68 -0
- package/dist/steps/step-fields.js.map +1 -0
- package/dist/steps/value-source.d.ts +6 -0
- package/dist/steps/value-source.js +58 -0
- package/dist/steps/value-source.js.map +1 -0
- package/jest.config.ts +11 -0
- package/package.json +68 -3
- package/scripts/build-engine.cjs +70 -0
- package/src/__tests__/engine-bundle.test.ts +121 -0
- package/src/__tests__/surface.test.ts +53 -0
- package/src/access/__tests__/host-match.test.ts +24 -0
- package/src/access/access.types.ts +25 -0
- package/src/access/host-match.ts +13 -0
- package/src/cost/__tests__/execution-cost.test.ts +200 -0
- package/src/cost/execution-cost.ts +192 -0
- package/src/definition/__tests__/validate-definition.test.ts +354 -0
- package/src/definition/definition.limits.ts +9 -0
- package/src/definition/definition.schema.ts +172 -0
- package/src/definition/definition.types.ts +171 -0
- package/src/definition/validate-definition.ts +206 -0
- package/src/definition/walk-steps.ts +44 -0
- package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
- package/src/engine/engine-entry.ts +3 -0
- package/src/engine/engine-global.ts +2 -0
- package/src/engine/run-in-isolate.ts +404 -0
- package/src/errors/runtime-error-code.enum.ts +37 -0
- package/src/index.ts +30 -0
- package/src/interpreter/__tests__/interpreter.test.ts +854 -0
- package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
- package/src/interpreter/interpreter-error.ts +12 -0
- package/src/interpreter/interpreter.ts +461 -0
- package/src/interpreter/interpreter.types.ts +192 -0
- package/src/interpreter/sequence-path.ts +67 -0
- package/src/interpreter/test-host.ts +85 -0
- package/src/runner-protocol/evaluation.types.ts +21 -0
- package/src/runner-protocol/execution-protocol.types.ts +221 -0
- package/src/server/__tests__/code-runner-session.test.ts +311 -0
- package/src/server/code-runner-error.ts +12 -0
- package/src/server/code-runner-session.ts +310 -0
- package/src/server/index.ts +11 -0
- package/src/steps/__tests__/global-references.test.ts +113 -0
- package/src/steps/execute-step.ts +186 -0
- package/src/steps/global-references.ts +48 -0
- package/src/steps/step-access.ts +56 -0
- package/src/steps/step-fields.ts +87 -0
- package/src/steps/value-source.ts +69 -0
- package/tsconfig.check.json +15 -0
- package/tsconfig.json +35 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateDefinition = void 0;
|
|
4
|
+
const access_types_1 = require("../access/access.types");
|
|
5
|
+
const host_match_1 = require("../access/host-match");
|
|
6
|
+
const definition_schema_1 = require("./definition.schema");
|
|
7
|
+
const definition_types_1 = require("./definition.types");
|
|
8
|
+
const walk_steps_1 = require("./walk-steps");
|
|
9
|
+
const JOI_OPTIONS = { abortEarly: false, convert: false };
|
|
10
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
const joinPath = (base, segments) => segments.reduce((path, segment) => {
|
|
12
|
+
if (typeof segment === 'number') {
|
|
13
|
+
return `${path}[${segment}]`;
|
|
14
|
+
}
|
|
15
|
+
return path === '' ? segment : `${path}.${segment}`;
|
|
16
|
+
}, base);
|
|
17
|
+
const joiErrors = (schema, value, basePath, errors) => {
|
|
18
|
+
const { error } = schema.validate(value, JOI_OPTIONS);
|
|
19
|
+
error?.details.forEach((detail) => errors.push({ path: joinPath(basePath, detail.path), message: detail.message }));
|
|
20
|
+
};
|
|
21
|
+
const isAccessKind = (value) => Object.values(access_types_1.AccessKind).includes(value);
|
|
22
|
+
const isStepType = (value) => Object.values(definition_types_1.StepType).includes(value);
|
|
23
|
+
const allowedInputKeys = (catalog, action) => {
|
|
24
|
+
const description = catalog.get(action)?.inputSchema.describe();
|
|
25
|
+
if (!description?.keys || description.flags?.unknown || description.patterns) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return new Set(Object.keys(description.keys));
|
|
29
|
+
};
|
|
30
|
+
const checkAccesses = (accesses, errors) => {
|
|
31
|
+
if (!Array.isArray(accesses)) {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
const valid = [];
|
|
35
|
+
accesses.forEach((access, index) => {
|
|
36
|
+
const path = `accesses[${index}]`;
|
|
37
|
+
const kind = isRecord(access) ? access.kind : undefined;
|
|
38
|
+
if (!isAccessKind(kind)) {
|
|
39
|
+
errors.push({ path: `${path}.kind`, message: '"kind" must be one of [HTTP, HOST_ACTION]' });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const before = errors.length;
|
|
43
|
+
joiErrors(definition_schema_1.ACCESS_SCHEMAS[kind], access, path, errors);
|
|
44
|
+
if (errors.length === before) {
|
|
45
|
+
valid.push(access);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
return valid;
|
|
49
|
+
};
|
|
50
|
+
const checkHttpAccess = (step, path, checks) => {
|
|
51
|
+
const httpAccesses = checks.accesses.filter((access) => access.kind === access_types_1.AccessKind.HTTP);
|
|
52
|
+
if (httpAccesses.length === 0) {
|
|
53
|
+
checks.errors.push({
|
|
54
|
+
path,
|
|
55
|
+
message: 'an HTTP step requires an access declaration of kind HTTP',
|
|
56
|
+
});
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const { url } = step;
|
|
60
|
+
if (typeof url !== 'string' || url.includes('{{')) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = new URL(url);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
checks.errors.push({ path: `${path}.url`, message: '"url" must be an absolute http(s) URL' });
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
72
|
+
checks.errors.push({ path: `${path}.url`, message: '"url" must be an absolute http(s) URL' });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const covered = httpAccesses.some((access) => access.kind === access_types_1.AccessKind.HTTP &&
|
|
76
|
+
access.hosts.some((pattern) => (0, host_match_1.hostMatches)(parsed.hostname, pattern)));
|
|
77
|
+
if (!covered) {
|
|
78
|
+
checks.errors.push({
|
|
79
|
+
path,
|
|
80
|
+
message: `host "${parsed.hostname}" is not covered by any HTTP access declaration`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const checkHost = (step, path, checks) => {
|
|
85
|
+
const { action, input } = step;
|
|
86
|
+
if (typeof action !== 'string' || action === '') {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (!checks.catalog.has(action)) {
|
|
90
|
+
checks.errors.push({
|
|
91
|
+
path: `${path}.action`,
|
|
92
|
+
message: `action "${action}" is not in the host catalog`,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
else if (isRecord(input)) {
|
|
96
|
+
const allowed = allowedInputKeys(checks.catalog, action);
|
|
97
|
+
if (allowed) {
|
|
98
|
+
Object.keys(input)
|
|
99
|
+
.filter((key) => !allowed.has(key))
|
|
100
|
+
.forEach((key) => checks.errors.push({
|
|
101
|
+
path: `${path}.input.${key}`,
|
|
102
|
+
message: `"${key}" is not an input of action "${action}"`,
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const declared = checks.accesses.some((access) => access.kind === access_types_1.AccessKind.HOST_ACTION && access.action === action);
|
|
107
|
+
if (!declared) {
|
|
108
|
+
checks.errors.push({
|
|
109
|
+
path,
|
|
110
|
+
message: `action "${action}" requires an access declaration of kind HOST_ACTION`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const checkStep = (node, path, ids, checks) => {
|
|
115
|
+
if (!isRecord(node)) {
|
|
116
|
+
checks.errors.push({ path, message: 'a step must be an object' });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (!isStepType(node.type)) {
|
|
120
|
+
checks.errors.push({
|
|
121
|
+
path: `${path}.type`,
|
|
122
|
+
message: `"type" must be one of [${Object.values(definition_types_1.StepType).join(', ')}]`,
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
joiErrors(definition_schema_1.STEP_SCHEMAS[node.type], node, path, checks.errors);
|
|
127
|
+
if (typeof node.id === 'string' && node.id !== '') {
|
|
128
|
+
if (ids.has(node.id)) {
|
|
129
|
+
checks.errors.push({ path: `${path}.id`, message: `id "${node.id}" is already used` });
|
|
130
|
+
}
|
|
131
|
+
ids.add(node.id);
|
|
132
|
+
}
|
|
133
|
+
if (node.type === definition_types_1.StepType.HTTP) {
|
|
134
|
+
checkHttpAccess(node, path, checks);
|
|
135
|
+
}
|
|
136
|
+
else if (node.type === definition_types_1.StepType.HOST) {
|
|
137
|
+
checkHost(node, path, checks);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const validateDefinition = (raw, catalog) => {
|
|
141
|
+
if (!isRecord(raw)) {
|
|
142
|
+
return { ok: false, errors: [{ path: '', message: 'a definition must be an object' }] };
|
|
143
|
+
}
|
|
144
|
+
if (raw.formatVersion !== definition_types_1.CURRENT_FORMAT_VERSION) {
|
|
145
|
+
return {
|
|
146
|
+
ok: false,
|
|
147
|
+
errors: [
|
|
148
|
+
{ path: 'formatVersion', message: `"formatVersion" must be ${definition_types_1.CURRENT_FORMAT_VERSION}` },
|
|
149
|
+
],
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
const errors = [];
|
|
153
|
+
joiErrors(definition_schema_1.DEFINITION_SCHEMA, raw, '', errors);
|
|
154
|
+
const accesses = checkAccesses(raw.accesses, errors);
|
|
155
|
+
const ids = new Set();
|
|
156
|
+
const checks = { catalog, accesses, errors };
|
|
157
|
+
(0, walk_steps_1.walkRawSteps)(raw.steps, (node, path) => checkStep(node, path, ids, checks));
|
|
158
|
+
return errors.length === 0
|
|
159
|
+
? { ok: true, definition: raw }
|
|
160
|
+
: { ok: false, errors };
|
|
161
|
+
};
|
|
162
|
+
exports.validateDefinition = validateDefinition;
|
|
163
|
+
//# sourceMappingURL=validate-definition.js.map
|
|
@@ -0,0 +1 @@
|
|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AAC;QACjD,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE;gBACN,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,2BAA2B,yCAAsB,EAAE,EAAE;aACxF;SACF,CAAC;IACJ,CAAC;IACD,MAAM,MAAM,GAAsB,EAAE,CAAC;IACrC,SAAS,CAAC,qCAAiB,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;IAC9C,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACrD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9B,MAAM,MAAM,GAAe,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACzD,IAAA,yBAAY,EAAC,GAAG,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC;QACxB,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,GAAmC,EAAE;QAC/D,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC5B,CAAC,CAAC;AArBW,QAAA,kBAAkB,sBAqB7B"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Step } from './definition.types';
|
|
2
|
+
export type RawStepVisitor = (node: unknown, path: string) => void;
|
|
3
|
+
export type StepVisitor = (step: Step, path: string) => void;
|
|
4
|
+
export declare const walkRawSteps: (steps: unknown, visit: RawStepVisitor, basePath?: string) => void;
|
|
5
|
+
export declare const walkSteps: (steps: readonly Step[], visit: StepVisitor, basePath?: string) => void;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.walkSteps = exports.walkRawSteps = void 0;
|
|
4
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
5
|
+
const walkList = (list, basePath, visit) => {
|
|
6
|
+
if (!Array.isArray(list)) {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
list.forEach((node, index) => {
|
|
10
|
+
const path = `${basePath}[${index}]`;
|
|
11
|
+
visit(node, path);
|
|
12
|
+
if (!isRecord(node)) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
walkList(node.then, `${path}.then`, visit);
|
|
16
|
+
walkList(node.else, `${path}.else`, visit);
|
|
17
|
+
if (Array.isArray(node.cases)) {
|
|
18
|
+
node.cases.forEach((branch, caseIndex) => {
|
|
19
|
+
if (isRecord(branch)) {
|
|
20
|
+
walkList(branch.steps, `${path}.cases[${caseIndex}].steps`, visit);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
walkList(node.default, `${path}.default`, visit);
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
const walkRawSteps = (steps, visit, basePath = 'steps') => walkList(steps, basePath, visit);
|
|
28
|
+
exports.walkRawSteps = walkRawSteps;
|
|
29
|
+
const walkSteps = (steps, visit, basePath = 'steps') => (0, exports.walkRawSteps)(steps, (node, path) => visit(node, path), basePath);
|
|
30
|
+
exports.walkSteps = walkSteps;
|
|
31
|
+
//# sourceMappingURL=walk-steps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"walk-steps.js","sourceRoot":"","sources":["../../src/definition/walk-steps.ts"],"names":[],"mappings":";;;AAKA,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CACpE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAE,QAAgB,EA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KAAkB,EAAE,QAAQ,GAAG,OAAO,EAAQ,EAAE,CAChG,IAAA,oBAAY,EAAC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,IAAY,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AAD9D,QAAA,SAAS,aACqD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { runInIsolate } from './run-in-isolate';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runInIsolate = void 0;
|
|
4
|
+
var run_in_isolate_1 = require("./run-in-isolate");
|
|
5
|
+
Object.defineProperty(exports, "runInIsolate", { enumerable: true, get: function () { return run_in_isolate_1.runInIsolate; } });
|
|
6
|
+
//# sourceMappingURL=engine-entry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine-entry.js","sourceRoot":"","sources":["../../src/engine/engine-entry.ts"],"names":[],"mappings":";;;AAEA,mDAAgD;AAAvC,8GAAA,YAAY,OAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ENGINE_GLOBAL_NAME = "AbyssRuntimeEngine";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine-global.js","sourceRoot":"","sources":["../../src/engine/engine-global.ts"],"names":[],"mappings":";;;AACa,QAAA,kBAAkB,GAAG,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ENGINE_SOURCE = "\"use strict\";\nvar AbyssRuntimeEngine = (() => {\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n // src/engine/engine-entry.ts\n var engine_entry_exports = {};\n __export(engine_entry_exports, {\n runInIsolate: () => runInIsolate\n });\n\n // src/errors/runtime-error-code.enum.ts\n var RuntimeErrorCode = /* @__PURE__ */ ((RuntimeErrorCode2) => {\n RuntimeErrorCode2[\"EXPRESSION_ERROR\"] = \"EXPRESSION_ERROR\";\n RuntimeErrorCode2[\"CODE_ERROR\"] = \"CODE_ERROR\";\n RuntimeErrorCode2[\"TIMEOUT\"] = \"TIMEOUT\";\n RuntimeErrorCode2[\"MEMORY_LIMIT\"] = \"MEMORY_LIMIT\";\n RuntimeErrorCode2[\"ACCESS_DENIED\"] = \"ACCESS_DENIED\";\n RuntimeErrorCode2[\"BUDGET_EXCEEDED\"] = \"BUDGET_EXCEEDED\";\n RuntimeErrorCode2[\"HOST_ERROR\"] = \"HOST_ERROR\";\n RuntimeErrorCode2[\"HTTP_ERROR\"] = \"HTTP_ERROR\";\n RuntimeErrorCode2[\"RUNNER_UNAVAILABLE\"] = \"RUNNER_UNAVAILABLE\";\n RuntimeErrorCode2[\"RUNNER_SATURATED\"] = \"RUNNER_SATURATED\";\n RuntimeErrorCode2[\"INVALID_REQUEST\"] = \"INVALID_REQUEST\";\n RuntimeErrorCode2[\"STATE_VERSION_UNSUPPORTED\"] = \"STATE_VERSION_UNSUPPORTED\";\n return RuntimeErrorCode2;\n })(RuntimeErrorCode || {});\n\n // src/definition/definition.limits.ts\n var MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;\n var MIN_RESPONSE_STATUS = 100;\n var MAX_RESPONSE_STATUS = 599;\n\n // src/interpreter/interpreter-error.ts\n var InterpreterError = class extends Error {\n constructor(code, message) {\n super(message);\n this.name = \"InterpreterError\";\n this.code = code;\n }\n };\n\n // src/definition/definition.types.ts\n var CURRENT_FORMAT_VERSION = 1;\n\n // src/steps/value-source.ts\n var TEMPLATE_PATTERN = /\\{\\{[\\s\\S]*?\\}\\}/;\n var IDENTIFIER_KEY = /^[A-Za-z_$][\\w$-]*$/;\n var isExpressionValue = (value) => typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && typeof value.$expression === \"string\";\n var propertyPath = (base, key) => IDENTIFIER_KEY.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]`;\n var indexPath = (base, index) => `${base}[${index}]`;\n var collectItems = (path, source, items) => {\n if (typeof source === \"string\") {\n if (TEMPLATE_PATTERN.test(source)) {\n items.push({ id: path, kind: \"TEMPLATE\" /* TEMPLATE */, source });\n }\n return;\n }\n if (source === null || typeof source !== \"object\") {\n return;\n }\n if (isExpressionValue(source)) {\n items.push({ id: path, kind: \"EXPRESSION\" /* EXPRESSION */, source: source.$expression });\n return;\n }\n if (Array.isArray(source)) {\n source.forEach((entry, index) => collectItems(indexPath(path, index), entry, items));\n return;\n }\n for (const [key, entry] of Object.entries(source)) {\n collectItems(propertyPath(path, key), entry, items);\n }\n };\n var resolveValue = (path, source, results) => {\n if (typeof source === \"string\") {\n return TEMPLATE_PATTERN.test(source) ? results.get(path) : source;\n }\n if (source === null || typeof source !== \"object\") {\n return source;\n }\n if (isExpressionValue(source)) {\n return results.get(path);\n }\n if (Array.isArray(source)) {\n return source.map((entry, index) => resolveValue(indexPath(path, index), entry, results));\n }\n return Object.fromEntries(\n Object.entries(source).map(([key, entry]) => [\n key,\n resolveValue(propertyPath(path, key), entry, results)\n ])\n );\n };\n\n // src/steps/execute-step.ts\n var fail = (message) => ({\n kind: \"FAIL\" /* FAIL */,\n error: { code: \"EXPRESSION_ERROR\" /* EXPRESSION_ERROR */, message }\n });\n var headerValue = (value) => typeof value === \"string\" ? value : JSON.stringify(value) ?? \"\";\n var resolvedRecord = (base, keys, fields) => Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));\n var executeWait = (step, fields) => {\n if (step.durationMs !== void 0) {\n const durationMs = fields.get(\"durationMs\");\n if (typeof durationMs !== \"number\" || !Number.isInteger(durationMs) || durationMs < 0) {\n return fail(\"Wait duration must resolve to a non-negative integer number of milliseconds\");\n }\n return { kind: \"WAIT\" /* WAIT */, durationMs };\n }\n const until = fields.get(\"until\");\n if (typeof until !== \"string\" || Number.isNaN(Date.parse(until))) {\n return fail(\"Wait date must resolve to an ISO 8601 date\");\n }\n return { kind: \"WAIT\" /* WAIT */, until };\n };\n var executeLog = (step, fields) => {\n const message = fields.get(\"message\");\n const action = {\n kind: \"LOG\" /* LOG */,\n level: step.level,\n message: typeof message === \"string\" ? message : JSON.stringify(message) ?? \"\"\n };\n if (step.data !== void 0) {\n action.data = fields.get(\"data\");\n }\n return action;\n };\n var executeRespond = (step, fields) => {\n const status = fields.get(\"status\");\n if (typeof status !== \"number\" || !Number.isInteger(status) || status < MIN_RESPONSE_STATUS || status > MAX_RESPONSE_STATUS) {\n return fail(\n `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`\n );\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const response = {\n status,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n response.body = fields.get(\"body\");\n }\n return { kind: \"RESPOND\" /* RESPOND */, response };\n };\n var executeStep = (step, fields) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */: {\n if (fields.get(\"if\")) {\n return { kind: \"DONE\" /* DONE */, output: \"then\", branch: \"then\" };\n }\n return step.else ? { kind: \"DONE\" /* DONE */, output: \"else\", branch: \"else\" } : { kind: \"DONE\" /* DONE */, output: \"else\" };\n }\n case \"SWITCH\" /* SWITCH */: {\n const value = fields.get(\"value\");\n const index = step.cases.findIndex(\n (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value\n );\n if (index >= 0) {\n const branch = `cases[${index}].steps`;\n return { kind: \"DONE\" /* DONE */, output: `cases[${index}]`, branch };\n }\n return step.default ? { kind: \"DONE\" /* DONE */, output: \"default\", branch: \"default\" } : { kind: \"DONE\" /* DONE */, output: null };\n }\n case \"WAIT\" /* WAIT */:\n return executeWait(step, fields);\n case \"SET\" /* SET */: {\n const value = fields.get(\"value\");\n return {\n kind: \"DONE\" /* DONE */,\n output: value,\n variable: { name: step.variable, value }\n };\n }\n case \"CODE\" /* CODE */:\n return { kind: \"DONE\" /* DONE */, output: fields.get(\"source\") };\n case \"HTTP\" /* HTTP */: {\n const url = fields.get(\"url\");\n if (typeof url !== \"string\") {\n return fail(\"HTTP url must resolve to a string\");\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const request = {\n method: step.method,\n url,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n request.body = fields.get(\"body\");\n }\n if (step.timeoutMs !== void 0) {\n request.timeoutMs = step.timeoutMs;\n }\n return { kind: \"HTTP\" /* HTTP */, request };\n }\n case \"HOST\" /* HOST */:\n return {\n kind: \"HOST\" /* HOST */,\n action: step.action,\n input: resolvedRecord(\"input\", Object.keys(step.input), fields)\n };\n case \"LOG\" /* LOG */:\n return executeLog(step, fields);\n case \"RESPOND\" /* RESPOND */:\n return executeRespond(step, fields);\n case \"STOP\" /* STOP */:\n return { kind: \"STOP\" /* STOP */, status: step.status, output: fields.get(\"output\") };\n }\n };\n\n // src/steps/step-fields.ts\n var recordFields = (base, record) => Object.entries(record ?? {}).map(([key, source]) => ({ path: propertyPath(base, key), source }));\n var optionalField = (path, source) => source === void 0 ? [] : [{ path, source }];\n var stepFields = (step) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */:\n return [{ path: \"if\", source: step.if }];\n case \"SWITCH\" /* SWITCH */:\n return [\n { path: \"value\", source: step.value },\n ...step.cases.map((switchCase, index) => ({\n path: `cases[${index}].match`,\n source: switchCase.match\n }))\n ];\n case \"WAIT\" /* WAIT */:\n return [\n ...optionalField(\"durationMs\", step.durationMs),\n ...optionalField(\"until\", step.until)\n ];\n case \"SET\" /* SET */:\n return [{ path: \"value\", source: step.value }];\n case \"CODE\" /* CODE */:\n return [];\n case \"HTTP\" /* HTTP */:\n return [\n { path: \"url\", source: step.url },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"HOST\" /* HOST */:\n return recordFields(\"input\", step.input);\n case \"LOG\" /* LOG */:\n return [{ path: \"message\", source: step.message }, ...optionalField(\"data\", step.data)];\n case \"RESPOND\" /* RESPOND */:\n return [\n { path: \"status\", source: step.status },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"STOP\" /* STOP */:\n return optionalField(\"output\", step.output);\n }\n };\n var collectStepItems = (step) => {\n if (step.type === \"CODE\" /* CODE */) {\n return [{ id: \"source\", kind: \"CODE\" /* CODE */, source: step.source }];\n }\n const items = [];\n for (const field of stepFields(step)) {\n collectItems(field.path, field.source, items);\n }\n return items;\n };\n var resolveStepFields = (step, results) => {\n if (step.type === \"CODE\" /* CODE */) {\n return /* @__PURE__ */ new Map([[\"source\", results.get(\"source\")]]);\n }\n return new Map(\n stepFields(step).map((field) => [field.path, resolveValue(field.path, field.source, results)])\n );\n };\n\n // src/interpreter/interpreter.types.ts\n var CURRENT_STATE_VERSION = 1;\n\n // src/interpreter/sequence-path.ts\n var ROOT = \"steps\";\n var SEGMENT = /\\[(\\d+)\\]\\.(?:(then|else|default)|cases\\[(\\d+)\\]\\.steps)/y;\n var corrupted = (path) => new InterpreterError(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n `Run state points outside the definition: ${path}`\n );\n var branchOf = (step, name, caseIndex) => {\n if (step.type === \"CONDITION\" /* CONDITION */) {\n return name === \"then\" ? step.then : name === \"else\" ? step.else : void 0;\n }\n if (step.type === \"SWITCH\" /* SWITCH */) {\n return name === \"default\" ? step.default : caseIndex === void 0 ? void 0 : step.cases[Number(caseIndex)]?.steps;\n }\n return void 0;\n };\n var resolveSequence = (definition, path) => {\n if (!path.startsWith(ROOT)) {\n throw corrupted(path);\n }\n let sequence = definition.steps;\n let position = ROOT.length;\n while (position < path.length) {\n SEGMENT.lastIndex = position;\n const match = SEGMENT.exec(path);\n const next = match ? branchOf(sequence[Number(match[1])], match[2], match[3]) : void 0;\n if (!match || !next) {\n throw corrupted(path);\n }\n sequence = next;\n position = SEGMENT.lastIndex;\n }\n return sequence;\n };\n var resolveStep = (definition, frame) => {\n const step = resolveSequence(definition, frame.sequencePath)[frame.index];\n if (!step) {\n throw corrupted(frame.sequencePath);\n }\n return step;\n };\n var branchPath = (frame, branch) => `${frame.sequencePath}[${frame.index}].${branch}`;\n var ROOT_SEQUENCE_PATH = ROOT;\n\n // src/interpreter/interpreter.ts\n var NO_RESULTS = /* @__PURE__ */ new Map();\n var SILENT_OBSERVER = {\n stepStarted: () => void 0,\n stepFinished: () => void 0\n };\n var invalidRequest = (message) => new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, message);\n var draftOf = (state) => ({\n ...state,\n stack: state.stack.map((frame) => ({ ...frame })),\n outputs: { ...state.outputs },\n vars: { ...state.vars },\n counters: { ...state.counters }\n });\n var setOwn = (target, key, value) => {\n Object.defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n };\n var topFrame = (draft) => draft.stack[draft.stack.length - 1];\n var advance = (draft) => {\n topFrame(draft).index += 1;\n };\n var settle = (draft, status) => {\n draft.status = status;\n draft.pending = null;\n return { state: draft, effects: [], status };\n };\n var failRun = (context, draft, error, stepId) => {\n draft.outcome = { status: \"FAILED\" /* FAILED */, error: { ...error, stepId } };\n context.observer.stepFinished(stepId, { ok: false, error });\n return settle(draft, \"FAILED\" /* FAILED */);\n };\n var emit = (context, draft, effect) => {\n if (draft.counters.effects + 1 > context.policy.budget.maxEffects) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Effect budget exceeded\" },\n effect.stepId\n );\n }\n draft.counters.effects += 1;\n draft.pending = effect;\n draft.status = \"WAITING\" /* WAITING */;\n return { state: draft, effects: [effect], status: \"WAITING\" /* WAITING */ };\n };\n var accessDenied = (verdict, subject) => ({\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: verdict === \"NOT_DECLARED\" /* NOT_DECLARED */ ? `${subject} is not declared by the definition` : `${subject} is not granted to the run`\n });\n var applyAction = (context, draft, step, action) => {\n const { policy, observer } = context;\n switch (action.kind) {\n case \"FAIL\" /* FAIL */:\n return failRun(context, draft, action.error, step.id);\n case \"STOP\" /* STOP */:\n draft.outcome = { status: action.status, output: action.output };\n observer.stepFinished(step.id, { ok: true, output: action.output });\n return settle(\n draft,\n action.status === \"SUCCEEDED\" /* SUCCEEDED */ ? \"SUCCEEDED\" /* SUCCEEDED */ : \"FAILED\" /* FAILED */\n );\n case \"DONE\" /* DONE */: {\n setOwn(draft.outputs, step.id, { output: action.output });\n observer.stepFinished(step.id, { ok: true, output: action.output });\n if (action.variable) {\n setOwn(draft.vars, action.variable.name, action.variable.value);\n }\n if (action.branch === void 0) {\n advance(draft);\n } else {\n draft.stack.push({ sequencePath: branchPath(topFrame(draft), action.branch), index: 0 });\n }\n return null;\n }\n case \"WAIT\" /* WAIT */: {\n const maxWaitMs = Math.min(policy.budget.maxWaitMs, MAX_WAIT_DURATION_MS);\n if (action.durationMs !== void 0 && action.durationMs > maxWaitMs) {\n return failRun(\n context,\n draft,\n {\n code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */,\n message: `Wait duration exceeds the budget of ${maxWaitMs} ms`\n },\n step.id\n );\n }\n const effect = { type: \"WAIT\" /* WAIT */, stepId: step.id };\n if (action.durationMs !== void 0) {\n effect.durationMs = action.durationMs;\n }\n if (action.until !== void 0) {\n effect.until = action.until;\n }\n return emit(context, draft, effect);\n }\n case \"HTTP\" /* HTTP */: {\n const verdict = policy.httpAccess(action.request.url);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"HTTP request host\"), step.id);\n }\n return emit(context, draft, {\n type: \"HTTP\" /* HTTP */,\n stepId: step.id,\n request: action.request\n });\n }\n case \"HOST\" /* HOST */: {\n const verdict = policy.hostActionAccess(action.action);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"Host action\"), step.id);\n }\n const validated = policy.hostInput(action.action, action.input);\n if (\"error\" in validated) {\n return failRun(context, draft, validated.error, step.id);\n }\n return emit(context, draft, {\n type: \"HOST\" /* HOST */,\n stepId: step.id,\n action: action.action,\n input: validated.input\n });\n }\n // Logging and responding are granted to every run; the host bounds them (one response).\n case \"LOG\" /* LOG */: {\n const effect = {\n type: \"LOG\" /* LOG */,\n stepId: step.id,\n level: action.level,\n message: action.message\n };\n if (\"data\" in action) {\n effect.data = action.data;\n }\n return emit(context, draft, effect);\n }\n case \"RESPOND\" /* RESPOND */:\n return emit(context, draft, {\n type: \"RESPOND\" /* RESPOND */,\n stepId: step.id,\n response: action.response\n });\n }\n };\n var runStep = (context, draft, step, results) => {\n if (results === void 0) {\n const items = collectStepItems(step);\n if (items.length > 0) {\n return emit(context, draft, {\n type: \"EVALUATE\" /* EVALUATE */,\n stepId: step.id,\n items,\n context: { input: draft.input, steps: draft.outputs, vars: draft.vars }\n });\n }\n }\n const fields = resolveStepFields(step, results ?? NO_RESULTS);\n return applyAction(context, draft, step, executeStep(step, fields));\n };\n var drive = (context, draft) => {\n for (; ; ) {\n const frame = topFrame(draft);\n if (!frame) {\n draft.outcome = { status: \"SUCCEEDED\" /* SUCCEEDED */ };\n return settle(draft, \"SUCCEEDED\" /* SUCCEEDED */);\n }\n const sequence = resolveSequence(context.definition, frame.sequencePath);\n if (frame.index >= sequence.length) {\n draft.stack.pop();\n if (draft.stack.length > 0) {\n advance(draft);\n }\n continue;\n }\n const step = sequence[frame.index];\n context.observer.stepStarted(step.id);\n if (draft.counters.steps + 1 > context.policy.budget.maxSteps) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Step budget exceeded\" },\n step.id\n );\n }\n draft.counters.steps += 1;\n const result = runStep(context, draft, step, void 0);\n if (result) {\n return result;\n }\n }\n };\n var startRun = (definition, input, policy, observer = SILENT_OBSERVER) => drive(\n { definition, policy, observer },\n {\n stateVersion: CURRENT_STATE_VERSION,\n formatVersion: CURRENT_FORMAT_VERSION,\n status: \"WAITING\" /* WAITING */,\n input,\n stack: [{ sequencePath: ROOT_SEQUENCE_PATH, index: 0 }],\n outputs: {},\n vars: {},\n pending: null,\n counters: { steps: 0, effects: 0 }\n }\n );\n var unexpected = (event, pending) => invalidRequest(`Event ${event.type} does not answer the pending ${pending.type} effect`);\n var readEvaluation = (pending, results) => {\n if (pending.type !== \"EVALUATE\" /* EVALUATE */) {\n throw invalidRequest(\n `Event ${\"EVALUATED\" /* EVALUATED */} does not answer the pending ${pending.type} effect`\n );\n }\n const values = /* @__PURE__ */ new Map();\n for (const item of pending.items) {\n const result = results.find((candidate) => candidate.id === item.id);\n if (!result) {\n throw invalidRequest(\"Evaluation results do not cover every item of the lot\");\n }\n if (!result.ok) {\n return result.error;\n }\n values.set(item.id, result.value);\n }\n return values;\n };\n var complete = (context, draft, step, output) => {\n setOwn(draft.outputs, step.id, { output });\n context.observer.stepFinished(step.id, { ok: true, output });\n advance(draft);\n return drive(context, draft);\n };\n var stepRun = (definition, state, event, policy, observer = SILENT_OBSERVER) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n throw new InterpreterError(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n const pending = state.pending;\n if (state.status !== \"WAITING\" /* WAITING */ || !pending) {\n throw invalidRequest(`Event ${event.type} received by a run that waits for nothing`);\n }\n const context = { definition, policy, observer };\n const draft = draftOf(state);\n draft.pending = null;\n const current = resolveStep(definition, topFrame(draft));\n switch (event.type) {\n case \"EVALUATED\" /* EVALUATED */: {\n const values = readEvaluation(pending, event.results);\n if (!(values instanceof Map)) {\n return failRun(context, draft, values, current.id);\n }\n return runStep(context, draft, current, values) ?? drive(context, draft);\n }\n case \"HTTP_COMPLETED\" /* HTTP_COMPLETED */:\n if (pending.type !== \"HTTP\" /* HTTP */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.response);\n case \"HOST_COMPLETED\" /* HOST_COMPLETED */:\n if (pending.type !== \"HOST\" /* HOST */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"WAIT_ELAPSED\" /* WAIT_ELAPSED */:\n if (pending.type !== \"WAIT\" /* WAIT */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"LOG_WRITTEN\" /* LOG_WRITTEN */:\n if (pending.type !== \"LOG\" /* LOG */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESPONSE_SENT\" /* RESPONSE_SENT */:\n if (pending.type !== \"RESPOND\" /* RESPOND */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESUMED\" /* RESUMED */:\n if (pending.type === \"EVALUATE\" /* EVALUATE */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"EFFECT_FAILED\" /* EFFECT_FAILED */:\n return failRun(context, draft, event.error, current.id);\n }\n };\n\n // src/runner-protocol/execution-protocol.types.ts\n var MAX_PROGRESS_OUTPUT_CHARS = 4096;\n\n // src/engine/run-in-isolate.ts\n var RUNTIME_ERROR_CODES = new Set(Object.values(RuntimeErrorCode));\n var rejected = (code, message) => ({\n kind: \"REJECTED\" /* REJECTED */,\n code,\n message\n });\n var finished = (outcome) => ({\n kind: \"FINISHED\" /* FINISHED */,\n outcome\n });\n var isolatePolicy = (request) => {\n const exposed = new Set(request.capabilities);\n const declared = (action) => request.definition.accesses.some(\n (access) => access.kind === \"HOST_ACTION\" /* HOST_ACTION */ && access.action === action\n );\n return {\n // Waits above `suspendWaitAboveMs` suspend; the host bounds the others by the time left.\n budget: { ...request.budget, maxWaitMs: MAX_WAIT_DURATION_MS },\n httpAccess: () => exposed.has(\"http.fetch\" /* HTTP_FETCH */) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */,\n hostActionAccess: (action) => {\n if (!declared(action)) {\n return \"NOT_DECLARED\" /* NOT_DECLARED */;\n }\n return exposed.has(action) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */;\n },\n hostInput: (_action, input) => ({ input })\n };\n };\n var outputPreview = (output) => {\n let json;\n try {\n json = JSON.stringify(output);\n } catch {\n return { outputTruncated: true };\n }\n if (json === void 0) {\n return {};\n }\n if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {\n return { output };\n }\n return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };\n };\n var progressObserver = (host) => {\n const startedAt = /* @__PURE__ */ new Map();\n const durationOf = (stepId) => {\n const start = startedAt.get(stepId);\n startedAt.delete(stepId);\n return start === void 0 ? 0 : Math.max(0, host.now() - start);\n };\n const observer = {\n stepStarted: (stepId) => {\n startedAt.set(stepId, host.now());\n host.onProgress({ stepId, phase: \"started\" /* STARTED */ });\n },\n stepFinished: (stepId, finish) => {\n const durationMs = durationOf(stepId);\n host.onProgress(\n finish.ok ? {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUCCEEDED\" /* SUCCEEDED */,\n durationMs,\n ...outputPreview(finish.output)\n } : {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"FAILED\" /* FAILED */,\n durationMs,\n errorCode: finish.error.code\n }\n );\n }\n };\n const suspended = (stepId) => host.onProgress({\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUSPENDED\" /* SUSPENDED */,\n durationMs: durationOf(stepId)\n });\n return { observer, suspended };\n };\n var callOf = (effect) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { capability: \"http.fetch\" /* HTTP_FETCH */, args: effect.request };\n case \"HOST\" /* HOST */:\n return { capability: effect.action, args: effect.input };\n case \"WAIT\" /* WAIT */:\n return {\n capability: \"wait\" /* WAIT */,\n args: effect.durationMs !== void 0 ? { durationMs: effect.durationMs } : { until: effect.until }\n };\n case \"LOG\" /* LOG */: {\n const args = { level: effect.level, message: effect.message };\n if (\"data\" in effect) {\n args.data = effect.data;\n }\n return { capability: \"log.write\" /* LOG_WRITE */, args };\n }\n case \"RESPOND\" /* RESPOND */:\n return { capability: \"http.respond\" /* HTTP_RESPOND */, args: effect.response };\n }\n };\n var completionOf = (effect, value) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { type: \"HTTP_COMPLETED\" /* HTTP_COMPLETED */, response: value };\n case \"HOST\" /* HOST */:\n return { type: \"HOST_COMPLETED\" /* HOST_COMPLETED */, output: value };\n case \"WAIT\" /* WAIT */:\n return { type: \"WAIT_ELAPSED\" /* WAIT_ELAPSED */ };\n case \"LOG\" /* LOG */:\n return { type: \"LOG_WRITTEN\" /* LOG_WRITTEN */ };\n case \"RESPOND\" /* RESPOND */:\n return { type: \"RESPONSE_SENT\" /* RESPONSE_SENT */ };\n }\n };\n var callFailure = (effect, error) => {\n const fallback = effect.type === \"HTTP\" /* HTTP */ ? \"HTTP_ERROR\" /* HTTP_ERROR */ : \"HOST_ERROR\" /* HOST_ERROR */;\n const detail = {\n code: error.code !== void 0 && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,\n message: error.message\n };\n return { type: \"EFFECT_FAILED\" /* EFFECT_FAILED */, error: detail };\n };\n var waitsAboveThreshold = (effect, request, now) => {\n const threshold = request.suspendWaitAboveMs;\n if (threshold === void 0) {\n return false;\n }\n if (effect.durationMs !== void 0) {\n return effect.durationMs > threshold;\n }\n return effect.until !== void 0 && Date.parse(effect.until) - now > threshold;\n };\n var outcomeOf = (state) => {\n const outcome = state.outcome;\n if (state.status === \"SUCCEEDED\" /* SUCCEEDED */) {\n return outcome?.output === void 0 ? { status: \"SUCCEEDED\" /* SUCCEEDED */ } : { status: \"SUCCEEDED\" /* SUCCEEDED */, output: outcome.output };\n }\n if (outcome?.error) {\n const failure = {\n status: \"FAILED\" /* FAILED */,\n errorCode: outcome.error.code,\n errorMessage: outcome.error.message\n };\n if (outcome.error.stepId !== void 0) {\n failure.stepId = outcome.error.stepId;\n }\n return failure;\n }\n return outcome?.status === \"FAILED\" /* FAILED */ && outcome.output !== void 0 ? { status: \"FAILED\" /* FAILED */, output: outcome.output } : { status: \"FAILED\" /* FAILED */ };\n };\n var resumeRefusal = (state) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n return rejected(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n if (state.status !== \"WAITING\" /* WAITING */ || !state.pending) {\n return rejected(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"The state to resume is not suspended\");\n }\n if (state.pending.type === \"EVALUATE\" /* EVALUATE */) {\n return rejected(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n \"The state to resume waits for an evaluation, which never suspends\"\n );\n }\n return null;\n };\n var runInIsolate = async (request, host) => {\n const { definition, state } = request;\n if (state !== void 0) {\n const refusal = resumeRefusal(state);\n if (refusal) {\n return refusal;\n }\n }\n const policy = isolatePolicy(request);\n const exposed = new Set(request.capabilities);\n const progress = progressObserver(host);\n const suspend = (stepId, suspendedState) => {\n progress.suspended(stepId);\n return finished({ status: \"SUSPENDED\" /* SUSPENDED */, state: suspendedState });\n };\n try {\n let result;\n if (state === void 0) {\n result = startRun(definition, request.input, policy, progress.observer);\n } else {\n progress.observer.stepStarted(state.pending.stepId);\n result = stepRun(\n definition,\n state,\n { type: \"RESUMED\" /* RESUMED */, output: request.resumeInput ?? null },\n policy,\n progress.observer\n );\n }\n while (result.status === \"WAITING\" /* WAITING */) {\n const effect = result.state.pending;\n if (!effect) {\n throw new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"Run waits for no effect\");\n }\n let event;\n if (effect.type === \"EVALUATE\" /* EVALUATE */) {\n const results = await host.evaluate(\n effect.items,\n effect.context,\n effect.stepId,\n request.globals\n );\n event = { type: \"EVALUATED\" /* EVALUATED */, results };\n } else if (effect.type === \"WAIT\" /* WAIT */ && waitsAboveThreshold(effect, request, host.now())) {\n return suspend(effect.stepId, result.state);\n } else {\n const { capability, args } = callOf(effect);\n if (!exposed.has(capability)) {\n event = {\n type: \"EFFECT_FAILED\" /* EFFECT_FAILED */,\n error: {\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: `Capability \"${capability}\" is not granted to the execution`\n }\n };\n } else {\n const answer = await host.callHost(effect.stepId, capability, args);\n if (!answer.ok) {\n event = callFailure(effect, answer.error);\n } else if (\"suspend\" in answer) {\n return suspend(effect.stepId, result.state);\n } else {\n event = completionOf(effect, answer.value);\n }\n }\n }\n result = stepRun(definition, result.state, event, policy, progress.observer);\n }\n return finished(outcomeOf(result.state));\n } catch (error) {\n if (error instanceof InterpreterError) {\n return finished({\n status: \"FAILED\" /* FAILED */,\n errorCode: error.code,\n errorMessage: error.message\n });\n }\n throw error;\n }\n };\n return __toCommonJS(engine_entry_exports);\n})();\n";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { EvaluationContext } from '../interpreter/interpreter.types';
|
|
2
|
+
import type { EvaluationItem, EvaluationResult } from '../runner-protocol/evaluation.types';
|
|
3
|
+
import type { CallError, ExecuteMessage, ExecutionOutcome, ExecutionRejectionCode, JSONValue, ProgressMessage } from '../runner-protocol/execution-protocol.types';
|
|
4
|
+
export type HostCallAnswer = {
|
|
5
|
+
ok: true;
|
|
6
|
+
value: unknown;
|
|
7
|
+
} | {
|
|
8
|
+
ok: true;
|
|
9
|
+
suspend: true;
|
|
10
|
+
} | {
|
|
11
|
+
ok: false;
|
|
12
|
+
error: CallError;
|
|
13
|
+
};
|
|
14
|
+
export type EngineProgress = Omit<ProgressMessage, 'type' | 'metrics'>;
|
|
15
|
+
export interface EngineHost {
|
|
16
|
+
evaluate: (items: EvaluationItem[], context: EvaluationContext, stepId: string, globals?: Record<string, JSONValue>) => Promise<EvaluationResult[]>;
|
|
17
|
+
callHost: (stepId: string, capability: string, args: unknown) => Promise<HostCallAnswer>;
|
|
18
|
+
onProgress: (progress: EngineProgress) => void;
|
|
19
|
+
now: () => number;
|
|
20
|
+
}
|
|
21
|
+
export type EngineRequest = Pick<ExecuteMessage, 'definition' | 'input' | 'state' | 'resumeInput' | 'capabilities' | 'budget' | 'suspendWaitAboveMs' | 'globals'>;
|
|
22
|
+
export declare enum EngineResultKind {
|
|
23
|
+
FINISHED = "FINISHED",
|
|
24
|
+
REJECTED = "REJECTED"
|
|
25
|
+
}
|
|
26
|
+
export type EngineResult = {
|
|
27
|
+
kind: EngineResultKind.FINISHED;
|
|
28
|
+
outcome: ExecutionOutcome;
|
|
29
|
+
} | {
|
|
30
|
+
kind: EngineResultKind.REJECTED;
|
|
31
|
+
code: ExecutionRejectionCode;
|
|
32
|
+
message: string;
|
|
33
|
+
};
|
|
34
|
+
export declare const runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult>;
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runInIsolate = exports.EngineResultKind = void 0;
|
|
4
|
+
const runtime_error_code_enum_1 = require("../errors/runtime-error-code.enum");
|
|
5
|
+
const access_types_1 = require("../access/access.types");
|
|
6
|
+
const definition_limits_1 = require("../definition/definition.limits");
|
|
7
|
+
const interpreter_error_1 = require("../interpreter/interpreter-error");
|
|
8
|
+
const interpreter_1 = require("../interpreter/interpreter");
|
|
9
|
+
const interpreter_types_1 = require("../interpreter/interpreter.types");
|
|
10
|
+
const definition_types_1 = require("../definition/definition.types");
|
|
11
|
+
const step_access_1 = require("../steps/step-access");
|
|
12
|
+
const execution_protocol_types_1 = require("../runner-protocol/execution-protocol.types");
|
|
13
|
+
var EngineResultKind;
|
|
14
|
+
(function (EngineResultKind) {
|
|
15
|
+
EngineResultKind["FINISHED"] = "FINISHED";
|
|
16
|
+
EngineResultKind["REJECTED"] = "REJECTED";
|
|
17
|
+
})(EngineResultKind || (exports.EngineResultKind = EngineResultKind = {}));
|
|
18
|
+
const RUNTIME_ERROR_CODES = new Set(Object.values(runtime_error_code_enum_1.RuntimeErrorCode));
|
|
19
|
+
const rejected = (code, message) => ({
|
|
20
|
+
kind: EngineResultKind.REJECTED,
|
|
21
|
+
code,
|
|
22
|
+
message,
|
|
23
|
+
});
|
|
24
|
+
const finished = (outcome) => ({
|
|
25
|
+
kind: EngineResultKind.FINISHED,
|
|
26
|
+
outcome,
|
|
27
|
+
});
|
|
28
|
+
const isolatePolicy = (request) => {
|
|
29
|
+
const exposed = new Set(request.capabilities);
|
|
30
|
+
const declared = (action) => request.definition.accesses.some((access) => access.kind === access_types_1.AccessKind.HOST_ACTION && access.action === action);
|
|
31
|
+
return {
|
|
32
|
+
budget: { ...request.budget, maxWaitMs: definition_limits_1.MAX_WAIT_DURATION_MS },
|
|
33
|
+
httpAccess: () => exposed.has(execution_protocol_types_1.CoreCapability.HTTP_FETCH) ? step_access_1.AccessVerdict.ALLOWED : step_access_1.AccessVerdict.NOT_GRANTED,
|
|
34
|
+
hostActionAccess: (action) => {
|
|
35
|
+
if (!declared(action)) {
|
|
36
|
+
return step_access_1.AccessVerdict.NOT_DECLARED;
|
|
37
|
+
}
|
|
38
|
+
return exposed.has(action) ? step_access_1.AccessVerdict.ALLOWED : step_access_1.AccessVerdict.NOT_GRANTED;
|
|
39
|
+
},
|
|
40
|
+
hostInput: (_action, input) => ({ input }),
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
const outputPreview = (output) => {
|
|
44
|
+
let json;
|
|
45
|
+
try {
|
|
46
|
+
json = JSON.stringify(output);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return { outputTruncated: true };
|
|
50
|
+
}
|
|
51
|
+
if (json === undefined) {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
if (json.length <= execution_protocol_types_1.MAX_PROGRESS_OUTPUT_CHARS) {
|
|
55
|
+
return { output };
|
|
56
|
+
}
|
|
57
|
+
return { output: json.slice(0, execution_protocol_types_1.MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };
|
|
58
|
+
};
|
|
59
|
+
const progressObserver = (host) => {
|
|
60
|
+
const startedAt = new Map();
|
|
61
|
+
const durationOf = (stepId) => {
|
|
62
|
+
const start = startedAt.get(stepId);
|
|
63
|
+
startedAt.delete(stepId);
|
|
64
|
+
return start === undefined ? 0 : Math.max(0, host.now() - start);
|
|
65
|
+
};
|
|
66
|
+
const observer = {
|
|
67
|
+
stepStarted: (stepId) => {
|
|
68
|
+
startedAt.set(stepId, host.now());
|
|
69
|
+
host.onProgress({ stepId, phase: execution_protocol_types_1.StepPhase.STARTED });
|
|
70
|
+
},
|
|
71
|
+
stepFinished: (stepId, finish) => {
|
|
72
|
+
const durationMs = durationOf(stepId);
|
|
73
|
+
host.onProgress(finish.ok
|
|
74
|
+
? {
|
|
75
|
+
stepId,
|
|
76
|
+
phase: execution_protocol_types_1.StepPhase.FINISHED,
|
|
77
|
+
status: execution_protocol_types_1.StepStatus.SUCCEEDED,
|
|
78
|
+
durationMs,
|
|
79
|
+
...outputPreview(finish.output),
|
|
80
|
+
}
|
|
81
|
+
: {
|
|
82
|
+
stepId,
|
|
83
|
+
phase: execution_protocol_types_1.StepPhase.FINISHED,
|
|
84
|
+
status: execution_protocol_types_1.StepStatus.FAILED,
|
|
85
|
+
durationMs,
|
|
86
|
+
errorCode: finish.error.code,
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
const suspended = (stepId) => host.onProgress({
|
|
91
|
+
stepId,
|
|
92
|
+
phase: execution_protocol_types_1.StepPhase.FINISHED,
|
|
93
|
+
status: execution_protocol_types_1.StepStatus.SUSPENDED,
|
|
94
|
+
durationMs: durationOf(stepId),
|
|
95
|
+
});
|
|
96
|
+
return { observer, suspended };
|
|
97
|
+
};
|
|
98
|
+
const callOf = (effect) => {
|
|
99
|
+
switch (effect.type) {
|
|
100
|
+
case interpreter_types_1.EffectType.HTTP:
|
|
101
|
+
return { capability: execution_protocol_types_1.CoreCapability.HTTP_FETCH, args: effect.request };
|
|
102
|
+
case interpreter_types_1.EffectType.HOST:
|
|
103
|
+
return { capability: effect.action, args: effect.input };
|
|
104
|
+
case interpreter_types_1.EffectType.WAIT:
|
|
105
|
+
return {
|
|
106
|
+
capability: execution_protocol_types_1.CoreCapability.WAIT,
|
|
107
|
+
args: effect.durationMs !== undefined
|
|
108
|
+
? { durationMs: effect.durationMs }
|
|
109
|
+
: { until: effect.until },
|
|
110
|
+
};
|
|
111
|
+
case interpreter_types_1.EffectType.LOG: {
|
|
112
|
+
const args = { level: effect.level, message: effect.message };
|
|
113
|
+
if ('data' in effect) {
|
|
114
|
+
args.data = effect.data;
|
|
115
|
+
}
|
|
116
|
+
return { capability: execution_protocol_types_1.CoreCapability.LOG_WRITE, args };
|
|
117
|
+
}
|
|
118
|
+
case interpreter_types_1.EffectType.RESPOND:
|
|
119
|
+
return { capability: execution_protocol_types_1.CoreCapability.HTTP_RESPOND, args: effect.response };
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const completionOf = (effect, value) => {
|
|
123
|
+
switch (effect.type) {
|
|
124
|
+
case interpreter_types_1.EffectType.HTTP:
|
|
125
|
+
return { type: interpreter_types_1.RunEventType.HTTP_COMPLETED, response: value };
|
|
126
|
+
case interpreter_types_1.EffectType.HOST:
|
|
127
|
+
return { type: interpreter_types_1.RunEventType.HOST_COMPLETED, output: value };
|
|
128
|
+
case interpreter_types_1.EffectType.WAIT:
|
|
129
|
+
return { type: interpreter_types_1.RunEventType.WAIT_ELAPSED };
|
|
130
|
+
case interpreter_types_1.EffectType.LOG:
|
|
131
|
+
return { type: interpreter_types_1.RunEventType.LOG_WRITTEN };
|
|
132
|
+
case interpreter_types_1.EffectType.RESPOND:
|
|
133
|
+
return { type: interpreter_types_1.RunEventType.RESPONSE_SENT };
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const callFailure = (effect, error) => {
|
|
137
|
+
const fallback = effect.type === interpreter_types_1.EffectType.HTTP ? runtime_error_code_enum_1.RuntimeErrorCode.HTTP_ERROR : runtime_error_code_enum_1.RuntimeErrorCode.HOST_ERROR;
|
|
138
|
+
const detail = {
|
|
139
|
+
code: error.code !== undefined && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,
|
|
140
|
+
message: error.message,
|
|
141
|
+
};
|
|
142
|
+
return { type: interpreter_types_1.RunEventType.EFFECT_FAILED, error: detail };
|
|
143
|
+
};
|
|
144
|
+
const waitsAboveThreshold = (effect, request, now) => {
|
|
145
|
+
const threshold = request.suspendWaitAboveMs;
|
|
146
|
+
if (threshold === undefined) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
if (effect.durationMs !== undefined) {
|
|
150
|
+
return effect.durationMs > threshold;
|
|
151
|
+
}
|
|
152
|
+
return effect.until !== undefined && Date.parse(effect.until) - now > threshold;
|
|
153
|
+
};
|
|
154
|
+
const outcomeOf = (state) => {
|
|
155
|
+
const outcome = state.outcome;
|
|
156
|
+
if (state.status === interpreter_types_1.RunStatus.SUCCEEDED) {
|
|
157
|
+
return outcome?.output === undefined
|
|
158
|
+
? { status: execution_protocol_types_1.ExecutionStatus.SUCCEEDED }
|
|
159
|
+
: { status: execution_protocol_types_1.ExecutionStatus.SUCCEEDED, output: outcome.output };
|
|
160
|
+
}
|
|
161
|
+
if (outcome?.error) {
|
|
162
|
+
const failure = {
|
|
163
|
+
status: execution_protocol_types_1.ExecutionStatus.FAILED,
|
|
164
|
+
errorCode: outcome.error.code,
|
|
165
|
+
errorMessage: outcome.error.message,
|
|
166
|
+
};
|
|
167
|
+
if (outcome.error.stepId !== undefined) {
|
|
168
|
+
failure.stepId = outcome.error.stepId;
|
|
169
|
+
}
|
|
170
|
+
return failure;
|
|
171
|
+
}
|
|
172
|
+
return outcome?.status === definition_types_1.StopStatus.FAILED && outcome.output !== undefined
|
|
173
|
+
? { status: execution_protocol_types_1.ExecutionStatus.FAILED, output: outcome.output }
|
|
174
|
+
: { status: execution_protocol_types_1.ExecutionStatus.FAILED };
|
|
175
|
+
};
|
|
176
|
+
const resumeRefusal = (state) => {
|
|
177
|
+
if (state.stateVersion !== interpreter_types_1.CURRENT_STATE_VERSION) {
|
|
178
|
+
return rejected(runtime_error_code_enum_1.RuntimeErrorCode.STATE_VERSION_UNSUPPORTED, `Run state version ${String(state.stateVersion)} is not supported ` +
|
|
179
|
+
`(this core reads version ${interpreter_types_1.CURRENT_STATE_VERSION})`);
|
|
180
|
+
}
|
|
181
|
+
if (state.status !== interpreter_types_1.RunStatus.WAITING || !state.pending) {
|
|
182
|
+
return rejected(runtime_error_code_enum_1.RuntimeErrorCode.INVALID_REQUEST, 'The state to resume is not suspended');
|
|
183
|
+
}
|
|
184
|
+
if (state.pending.type === interpreter_types_1.EffectType.EVALUATE) {
|
|
185
|
+
return rejected(runtime_error_code_enum_1.RuntimeErrorCode.INVALID_REQUEST, 'The state to resume waits for an evaluation, which never suspends');
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
};
|
|
189
|
+
const runInIsolate = async (request, host) => {
|
|
190
|
+
const { definition, state } = request;
|
|
191
|
+
if (state !== undefined) {
|
|
192
|
+
const refusal = resumeRefusal(state);
|
|
193
|
+
if (refusal) {
|
|
194
|
+
return refusal;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const policy = isolatePolicy(request);
|
|
198
|
+
const exposed = new Set(request.capabilities);
|
|
199
|
+
const progress = progressObserver(host);
|
|
200
|
+
const suspend = (stepId, suspendedState) => {
|
|
201
|
+
progress.suspended(stepId);
|
|
202
|
+
return finished({ status: execution_protocol_types_1.ExecutionStatus.SUSPENDED, state: suspendedState });
|
|
203
|
+
};
|
|
204
|
+
try {
|
|
205
|
+
let result;
|
|
206
|
+
if (state === undefined) {
|
|
207
|
+
result = (0, interpreter_1.startRun)(definition, request.input, policy, progress.observer);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
progress.observer.stepStarted(state.pending.stepId);
|
|
211
|
+
result = (0, interpreter_1.stepRun)(definition, state, { type: interpreter_types_1.RunEventType.RESUMED, output: request.resumeInput ?? null }, policy, progress.observer);
|
|
212
|
+
}
|
|
213
|
+
while (result.status === interpreter_types_1.RunStatus.WAITING) {
|
|
214
|
+
const effect = result.state.pending;
|
|
215
|
+
if (!effect) {
|
|
216
|
+
throw new interpreter_error_1.InterpreterError(runtime_error_code_enum_1.RuntimeErrorCode.INVALID_REQUEST, 'Run waits for no effect');
|
|
217
|
+
}
|
|
218
|
+
let event;
|
|
219
|
+
if (effect.type === interpreter_types_1.EffectType.EVALUATE) {
|
|
220
|
+
const results = await host.evaluate(effect.items, effect.context, effect.stepId, request.globals);
|
|
221
|
+
event = { type: interpreter_types_1.RunEventType.EVALUATED, results };
|
|
222
|
+
}
|
|
223
|
+
else if (effect.type === interpreter_types_1.EffectType.WAIT &&
|
|
224
|
+
waitsAboveThreshold(effect, request, host.now())) {
|
|
225
|
+
return suspend(effect.stepId, result.state);
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
const { capability, args } = callOf(effect);
|
|
229
|
+
if (!exposed.has(capability)) {
|
|
230
|
+
event = {
|
|
231
|
+
type: interpreter_types_1.RunEventType.EFFECT_FAILED,
|
|
232
|
+
error: {
|
|
233
|
+
code: runtime_error_code_enum_1.RuntimeErrorCode.ACCESS_DENIED,
|
|
234
|
+
message: `Capability "${capability}" is not granted to the execution`,
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
const answer = await host.callHost(effect.stepId, capability, args);
|
|
240
|
+
if (!answer.ok) {
|
|
241
|
+
event = callFailure(effect, answer.error);
|
|
242
|
+
}
|
|
243
|
+
else if ('suspend' in answer) {
|
|
244
|
+
return suspend(effect.stepId, result.state);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
event = completionOf(effect, answer.value);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
result = (0, interpreter_1.stepRun)(definition, result.state, event, policy, progress.observer);
|
|
252
|
+
}
|
|
253
|
+
return finished(outcomeOf(result.state));
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (error instanceof interpreter_error_1.InterpreterError) {
|
|
257
|
+
return finished({
|
|
258
|
+
status: execution_protocol_types_1.ExecutionStatus.FAILED,
|
|
259
|
+
errorCode: error.code,
|
|
260
|
+
errorMessage: error.message,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
exports.runInIsolate = runInIsolate;
|
|
267
|
+
//# sourceMappingURL=run-in-isolate.js.map
|