@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.
Files changed (132) hide show
  1. package/.eslintrc.js +32 -0
  2. package/.prettierrc +5 -0
  3. package/README.md +28 -3
  4. package/dist/access/access.types.d.ts +14 -0
  5. package/dist/access/access.types.js +9 -0
  6. package/dist/access/access.types.js.map +1 -0
  7. package/dist/access/host-match.d.ts +1 -0
  8. package/dist/access/host-match.js +14 -0
  9. package/dist/access/host-match.js.map +1 -0
  10. package/dist/cost/execution-cost.d.ts +45 -0
  11. package/dist/cost/execution-cost.js +114 -0
  12. package/dist/cost/execution-cost.js.map +1 -0
  13. package/dist/definition/definition.limits.d.ts +4 -0
  14. package/dist/definition/definition.limits.js +8 -0
  15. package/dist/definition/definition.limits.js.map +1 -0
  16. package/dist/definition/definition.schema.d.ts +8 -0
  17. package/dist/definition/definition.schema.js +123 -0
  18. package/dist/definition/definition.schema.js.map +1 -0
  19. package/dist/definition/definition.types.d.ts +117 -0
  20. package/dist/definition/definition.types.js +37 -0
  21. package/dist/definition/definition.types.js.map +1 -0
  22. package/dist/definition/validate-definition.d.ts +9 -0
  23. package/dist/definition/validate-definition.js +163 -0
  24. package/dist/definition/validate-definition.js.map +1 -0
  25. package/dist/definition/walk-steps.d.ts +5 -0
  26. package/dist/definition/walk-steps.js +31 -0
  27. package/dist/definition/walk-steps.js.map +1 -0
  28. package/dist/engine/engine-entry.d.ts +1 -0
  29. package/dist/engine/engine-entry.js +6 -0
  30. package/dist/engine/engine-entry.js.map +1 -0
  31. package/dist/engine/engine-global.d.ts +1 -0
  32. package/dist/engine/engine-global.js +5 -0
  33. package/dist/engine/engine-global.js.map +1 -0
  34. package/dist/engine/engine-source.d.ts +2 -0
  35. package/dist/engine/engine-source.js +3 -0
  36. package/dist/engine/run-in-isolate.d.ts +34 -0
  37. package/dist/engine/run-in-isolate.js +267 -0
  38. package/dist/engine/run-in-isolate.js.map +1 -0
  39. package/dist/errors/runtime-error-code.enum.d.ts +18 -0
  40. package/dist/errors/runtime-error-code.enum.js +19 -0
  41. package/dist/errors/runtime-error-code.enum.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/interpreter/interpreter-error.d.ts +5 -0
  46. package/dist/interpreter/interpreter-error.js +12 -0
  47. package/dist/interpreter/interpreter-error.js.map +1 -0
  48. package/dist/interpreter/interpreter.d.ts +30 -0
  49. package/dist/interpreter/interpreter.js +313 -0
  50. package/dist/interpreter/interpreter.js.map +1 -0
  51. package/dist/interpreter/interpreter.types.d.ts +152 -0
  52. package/dist/interpreter/interpreter.types.js +31 -0
  53. package/dist/interpreter/interpreter.types.js.map +1 -0
  54. package/dist/interpreter/sequence-path.d.ts +6 -0
  55. package/dist/interpreter/sequence-path.js +53 -0
  56. package/dist/interpreter/sequence-path.js.map +1 -0
  57. package/dist/interpreter/test-host.d.ts +18 -0
  58. package/dist/interpreter/test-host.js +43 -0
  59. package/dist/interpreter/test-host.js.map +1 -0
  60. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  61. package/dist/runner-protocol/evaluation.types.js +10 -0
  62. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  63. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  64. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  65. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  66. package/dist/server/code-runner-error.d.ts +5 -0
  67. package/dist/server/code-runner-error.js +12 -0
  68. package/dist/server/code-runner-error.js.map +1 -0
  69. package/dist/server/code-runner-session.d.ts +28 -0
  70. package/dist/server/code-runner-session.js +208 -0
  71. package/dist/server/code-runner-session.js.map +1 -0
  72. package/dist/server/index.d.ts +3 -0
  73. package/dist/server/index.js +10 -0
  74. package/dist/server/index.js.map +1 -0
  75. package/dist/steps/execute-step.d.ts +50 -0
  76. package/dist/steps/execute-step.js +136 -0
  77. package/dist/steps/execute-step.js.map +1 -0
  78. package/dist/steps/global-references.d.ts +2 -0
  79. package/dist/steps/global-references.js +28 -0
  80. package/dist/steps/global-references.js.map +1 -0
  81. package/dist/steps/step-access.d.ts +8 -0
  82. package/dist/steps/step-access.js +39 -0
  83. package/dist/steps/step-access.js.map +1 -0
  84. package/dist/steps/step-fields.d.ts +5 -0
  85. package/dist/steps/step-fields.js +68 -0
  86. package/dist/steps/step-fields.js.map +1 -0
  87. package/dist/steps/value-source.d.ts +6 -0
  88. package/dist/steps/value-source.js +58 -0
  89. package/dist/steps/value-source.js.map +1 -0
  90. package/jest.config.ts +11 -0
  91. package/package.json +68 -3
  92. package/scripts/build-engine.cjs +70 -0
  93. package/src/__tests__/engine-bundle.test.ts +121 -0
  94. package/src/__tests__/surface.test.ts +53 -0
  95. package/src/access/__tests__/host-match.test.ts +24 -0
  96. package/src/access/access.types.ts +25 -0
  97. package/src/access/host-match.ts +13 -0
  98. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  99. package/src/cost/execution-cost.ts +192 -0
  100. package/src/definition/__tests__/validate-definition.test.ts +354 -0
  101. package/src/definition/definition.limits.ts +9 -0
  102. package/src/definition/definition.schema.ts +172 -0
  103. package/src/definition/definition.types.ts +171 -0
  104. package/src/definition/validate-definition.ts +206 -0
  105. package/src/definition/walk-steps.ts +44 -0
  106. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  107. package/src/engine/engine-entry.ts +3 -0
  108. package/src/engine/engine-global.ts +2 -0
  109. package/src/engine/run-in-isolate.ts +404 -0
  110. package/src/errors/runtime-error-code.enum.ts +37 -0
  111. package/src/index.ts +30 -0
  112. package/src/interpreter/__tests__/interpreter.test.ts +854 -0
  113. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  114. package/src/interpreter/interpreter-error.ts +12 -0
  115. package/src/interpreter/interpreter.ts +461 -0
  116. package/src/interpreter/interpreter.types.ts +192 -0
  117. package/src/interpreter/sequence-path.ts +67 -0
  118. package/src/interpreter/test-host.ts +85 -0
  119. package/src/runner-protocol/evaluation.types.ts +21 -0
  120. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  121. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  122. package/src/server/code-runner-error.ts +12 -0
  123. package/src/server/code-runner-session.ts +310 -0
  124. package/src/server/index.ts +11 -0
  125. package/src/steps/__tests__/global-references.test.ts +113 -0
  126. package/src/steps/execute-step.ts +186 -0
  127. package/src/steps/global-references.ts +48 -0
  128. package/src/steps/step-access.ts +56 -0
  129. package/src/steps/step-fields.ts +87 -0
  130. package/src/steps/value-source.ts +69 -0
  131. package/tsconfig.check.json +15 -0
  132. package/tsconfig.json +35 -0
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveValue = exports.collectItems = exports.propertyPath = exports.isExpressionValue = void 0;
4
+ const evaluation_types_1 = require("../runner-protocol/evaluation.types");
5
+ const TEMPLATE_PATTERN = /\{\{[\s\S]*?\}\}/;
6
+ const IDENTIFIER_KEY = /^[A-Za-z_$][\w$-]*$/;
7
+ const isExpressionValue = (value) => typeof value === 'object' &&
8
+ value !== null &&
9
+ !Array.isArray(value) &&
10
+ Object.keys(value).length === 1 &&
11
+ typeof value.$expression === 'string';
12
+ exports.isExpressionValue = isExpressionValue;
13
+ const propertyPath = (base, key) => IDENTIFIER_KEY.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]`;
14
+ exports.propertyPath = propertyPath;
15
+ const indexPath = (base, index) => `${base}[${index}]`;
16
+ const collectItems = (path, source, items) => {
17
+ if (typeof source === 'string') {
18
+ if (TEMPLATE_PATTERN.test(source)) {
19
+ items.push({ id: path, kind: evaluation_types_1.EvaluationKind.TEMPLATE, source });
20
+ }
21
+ return;
22
+ }
23
+ if (source === null || typeof source !== 'object') {
24
+ return;
25
+ }
26
+ if ((0, exports.isExpressionValue)(source)) {
27
+ items.push({ id: path, kind: evaluation_types_1.EvaluationKind.EXPRESSION, source: source.$expression });
28
+ return;
29
+ }
30
+ if (Array.isArray(source)) {
31
+ source.forEach((entry, index) => (0, exports.collectItems)(indexPath(path, index), entry, items));
32
+ return;
33
+ }
34
+ for (const [key, entry] of Object.entries(source)) {
35
+ (0, exports.collectItems)((0, exports.propertyPath)(path, key), entry, items);
36
+ }
37
+ };
38
+ exports.collectItems = collectItems;
39
+ const resolveValue = (path, source, results) => {
40
+ if (typeof source === 'string') {
41
+ return TEMPLATE_PATTERN.test(source) ? results.get(path) : source;
42
+ }
43
+ if (source === null || typeof source !== 'object') {
44
+ return source;
45
+ }
46
+ if ((0, exports.isExpressionValue)(source)) {
47
+ return results.get(path);
48
+ }
49
+ if (Array.isArray(source)) {
50
+ return source.map((entry, index) => (0, exports.resolveValue)(indexPath(path, index), entry, results));
51
+ }
52
+ return Object.fromEntries(Object.entries(source).map(([key, entry]) => [
53
+ key,
54
+ (0, exports.resolveValue)((0, exports.propertyPath)(path, key), entry, results),
55
+ ]));
56
+ };
57
+ exports.resolveValue = resolveValue;
58
+ //# sourceMappingURL=value-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-source.js","sourceRoot":"","sources":["../../src/steps/value-source.ts"],"names":[],"mappings":";;;AAAA,0EAAqE;AAIrE,MAAM,gBAAgB,GAAG,kBAAkB,CAAC;AAC5C,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAEtC,MAAM,iBAAiB,GAAG,CAAC,KAAkB,EAA4B,EAAE,CAChF,OAAO,KAAK,KAAK,QAAQ;IACzB,KAAK,KAAK,IAAI;IACd,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;IACrB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC;IAC/B,OAAQ,KAAyB,CAAC,WAAW,KAAK,QAAQ,CAAC;AALhD,QAAA,iBAAiB,qBAK+B;AAGtD,MAAM,YAAY,GAAG,CAAC,IAAY,EAAE,GAAW,EAAU,EAAE,CACh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,KAAK,EAAE,OAAO,CAAC;KACtD,CAAC,CACH,CAAC;AACJ,CAAC,CAAC;AAvBW,QAAA,YAAY,gBAuBvB"}
package/jest.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { Config } from '@jest/types';
2
+
3
+ const config: Config.InitialOptions = {
4
+ testEnvironment: 'node',
5
+ transform: {
6
+ '^.+\\.tsx?$': ['ts-jest', { isolatedModules: true }],
7
+ },
8
+ modulePathIgnorePatterns: ['dist'],
9
+ };
10
+
11
+ export default config;
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@abyss-project/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0",
4
+ "description": "Abyss automation core: definitions, interpreter, runner protocol",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./server": {
13
+ "types": "./dist/server/index.d.ts",
14
+ "default": "./dist/server/index.js"
15
+ },
16
+ "./engine": {
17
+ "types": "./dist/engine/engine-source.d.ts",
18
+ "default": "./dist/engine/engine-source.js"
19
+ }
20
+ },
21
+ "typesVersions": {
22
+ "*": {
23
+ "server": [
24
+ "dist/server/index.d.ts"
25
+ ],
26
+ "engine": [
27
+ "dist/engine/engine-source.d.ts"
28
+ ]
29
+ }
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://gitlab.com/abyss-group/abyss-runtime.git"
34
+ },
35
+ "keywords": [],
36
+ "author": "scylla",
37
+ "license": "ISC",
38
+ "engines": {
39
+ "node": ">=19.8"
40
+ },
41
+ "dependencies": {
42
+ "joi": "^17.13.3",
43
+ "ws": "^8"
44
+ },
45
+ "devDependencies": {
46
+ "@jest/types": "^29.6.0",
47
+ "@types/jest": "^29.5.5",
48
+ "@types/node": "^20.11.0",
49
+ "@types/ws": "^8",
50
+ "@typescript-eslint/eslint-plugin": "8.71.0",
51
+ "@typescript-eslint/parser": "8.71.0",
52
+ "esbuild": "^0.28.2",
53
+ "eslint": "^8.57.1",
54
+ "eslint-config-prettier": "^8.3.0",
55
+ "eslint-plugin-filenames-simple": "^0.7.0",
56
+ "eslint-plugin-prettier": "^3.4.0",
57
+ "jest": "^29.7.0",
58
+ "prettier": "2.3.1",
59
+ "ts-jest": "^29.1.0",
60
+ "ts-node": "^10.4.0",
61
+ "typescript": "5.9.3"
62
+ },
63
+ "scripts": {
64
+ "lint": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --fix",
65
+ "lint:check": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --max-warnings 0",
66
+ "tsc": "tsc",
67
+ "build": "tsc && node scripts/build-engine.cjs",
68
+ "test": "jest",
69
+ "dev": "tsc --watch"
70
+ }
6
71
  }
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * build-engine.cjs — bundles the isolate engine (ADR-0238) into one self-contained script and
4
+ * ships it as a string: `@abyss-project/runtime/engine` exports `ENGINE_SOURCE`.
5
+ *
6
+ * The script is an IIFE that defines one global (`ENGINE_GLOBAL_NAME`, `{ runInIsolate }`).
7
+ * `platform: 'neutral'` resolves no Node built-in: an import of `fs`, `net`... fails the build
8
+ * instead of slipping into the isolate. Runs after `tsc`, which emits the rest of `dist`.
9
+ *
10
+ * USAGE (from the package directory, what `build` does)
11
+ * node scripts/build-engine.cjs
12
+ */
13
+
14
+ /* eslint-disable no-console */
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const esbuild = require('esbuild');
20
+
21
+ const PACKAGE_DIR = path.resolve(__dirname, '..');
22
+ const ENTRY = path.join(PACKAGE_DIR, 'src', 'engine', 'engine-entry.ts');
23
+ const OUT_DIR = path.join(PACKAGE_DIR, 'dist', 'engine');
24
+
25
+ /** The engine script, as a string; `globalName` is the global it defines. */
26
+ function bundleEngine(globalName) {
27
+ const result = esbuild.buildSync({
28
+ entryPoints: [ENTRY],
29
+ bundle: true,
30
+ format: 'iife',
31
+ globalName,
32
+ platform: 'neutral',
33
+ target: 'es2021',
34
+ write: false,
35
+ legalComments: 'none',
36
+ logLevel: 'silent',
37
+ });
38
+ return result.outputFiles[0].text;
39
+ }
40
+
41
+ function main() {
42
+ const globalPath = path.join(OUT_DIR, 'engine-global.js');
43
+ if (!fs.existsSync(globalPath)) {
44
+ throw new Error(`${globalPath} is missing: run tsc before this script`);
45
+ }
46
+ const { ENGINE_GLOBAL_NAME } = require(globalPath);
47
+ const source = bundleEngine(ENGINE_GLOBAL_NAME);
48
+ fs.writeFileSync(
49
+ path.join(OUT_DIR, 'engine-source.js'),
50
+ `"use strict";\nObject.defineProperty(exports, "__esModule", { value: true });\n` +
51
+ `exports.ENGINE_SOURCE = ${JSON.stringify(source)};\n`,
52
+ );
53
+ fs.writeFileSync(
54
+ path.join(OUT_DIR, 'engine-source.d.ts'),
55
+ '/** The isolate engine script: evaluating it defines the global `ENGINE_GLOBAL_NAME`. */\n' +
56
+ 'export declare const ENGINE_SOURCE: string;\n',
57
+ );
58
+ console.log(`engine bundle: ${source.length} characters in dist/engine/engine-source.js`);
59
+ }
60
+
61
+ if (require.main === module) {
62
+ try {
63
+ main();
64
+ } catch (error) {
65
+ console.error(error instanceof Error ? error.message : error);
66
+ process.exit(1);
67
+ }
68
+ }
69
+
70
+ module.exports = { bundleEngine };
@@ -0,0 +1,121 @@
1
+ import * as vm from 'vm';
2
+ import { AccessKind } from '../access/access.types';
3
+ import {
4
+ CURRENT_FORMAT_VERSION,
5
+ HttpMethod,
6
+ LogLevel,
7
+ StepType,
8
+ StopStatus,
9
+ } from '../definition/definition.types';
10
+ import type { RuntimeDefinition } from '../definition/definition.types';
11
+ import { ENGINE_GLOBAL_NAME } from '../engine/engine-global';
12
+ import { EngineResultKind } from '../engine/run-in-isolate';
13
+ import type { EngineHost, EngineRequest, EngineResult } from '../engine/run-in-isolate';
14
+ import type { EvaluationItem } from '../runner-protocol/evaluation.types';
15
+ import { CoreCapability, ExecutionStatus } from '../runner-protocol/execution-protocol.types';
16
+
17
+ // The build script is plain CommonJS, shared with `build`: the test bundles exactly what ships.
18
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
19
+ const { bundleEngine } = require('../../scripts/build-engine.cjs') as {
20
+ bundleEngine: (globalName: string) => string;
21
+ };
22
+
23
+ type Engine = { runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult> };
24
+
25
+ const definition: RuntimeDefinition = {
26
+ formatVersion: CURRENT_FORMAT_VERSION,
27
+ accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
28
+ steps: [
29
+ { id: 'double', type: StepType.SET, variable: 'n', value: { $expression: 'input.n * 2' } },
30
+ {
31
+ id: 'fetch',
32
+ type: StepType.HTTP,
33
+ method: HttpMethod.GET,
34
+ url: 'https://api.example.com/{{ vars.n }}',
35
+ },
36
+ { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'fetched' },
37
+ {
38
+ id: 'end',
39
+ type: StepType.STOP,
40
+ status: StopStatus.SUCCEEDED,
41
+ output: { $expression: 'vars.n' },
42
+ },
43
+ ],
44
+ };
45
+
46
+ describe('isolate engine bundle', () => {
47
+ let source: string;
48
+
49
+ beforeAll(() => {
50
+ source = bundleEngine(ENGINE_GLOBAL_NAME);
51
+ });
52
+
53
+ it('carries no module loader and no Joi', () => {
54
+ expect(source).not.toMatch(/\brequire\s*\(/);
55
+ expect(source).not.toMatch(/joi/i);
56
+ });
57
+
58
+ it('loads in a bare context and runs a definition with a fake evaluate and callHost', async () => {
59
+ // No `require`, `process`, `URL`, timers nor console: only the language built-ins.
60
+ const context = vm.createContext({});
61
+ vm.runInContext(source, context);
62
+ expect(vm.runInContext('typeof require + typeof process + typeof URL', context)).toBe(
63
+ 'undefinedundefinedundefined',
64
+ );
65
+ const engine = (context as Record<string, unknown>)[ENGINE_GLOBAL_NAME] as Engine;
66
+ expect(typeof engine.runInIsolate).toBe('function');
67
+
68
+ const values: Record<string, unknown> = {
69
+ 'input.n * 2': 42,
70
+ 'https://api.example.com/{{ vars.n }}': 'https://api.example.com/42',
71
+ 'vars.n': 42,
72
+ };
73
+ const calls: Array<{ stepId: string; capability: string; args: unknown }> = [];
74
+ const progress: string[] = [];
75
+ const host: EngineHost = {
76
+ evaluate: async (items: EvaluationItem[]) =>
77
+ items.map((item) => ({ id: item.id, ok: true as const, value: values[item.source] })),
78
+ callHost: async (stepId, capability, args) => {
79
+ calls.push({ stepId, capability, args });
80
+ return {
81
+ ok: true,
82
+ value:
83
+ capability === CoreCapability.HTTP_FETCH
84
+ ? { status: 200, headers: {}, body: null }
85
+ : null,
86
+ };
87
+ },
88
+ onProgress: (p) => progress.push(`${p.stepId}:${p.phase}`),
89
+ now: () => 0,
90
+ };
91
+
92
+ const result = await engine.runInIsolate(
93
+ {
94
+ definition,
95
+ input: { n: 21 },
96
+ capabilities: [CoreCapability.HTTP_FETCH, CoreCapability.LOG_WRITE],
97
+ budget: { maxSteps: 10, maxEffects: 10 },
98
+ },
99
+ host,
100
+ );
101
+
102
+ // Values built in the other realm: compare their JSON.
103
+ expect(JSON.parse(JSON.stringify(result))).toEqual({
104
+ kind: EngineResultKind.FINISHED,
105
+ outcome: { status: ExecutionStatus.SUCCEEDED, output: 42 },
106
+ });
107
+ expect(JSON.parse(JSON.stringify(calls))).toEqual([
108
+ {
109
+ stepId: 'fetch',
110
+ capability: CoreCapability.HTTP_FETCH,
111
+ args: { method: 'GET', url: 'https://api.example.com/42', headers: {} },
112
+ },
113
+ {
114
+ stepId: 'note',
115
+ capability: CoreCapability.LOG_WRITE,
116
+ args: { level: LogLevel.INFO, message: 'fetched' },
117
+ },
118
+ ]);
119
+ expect(progress).toHaveLength(8);
120
+ });
121
+ });
@@ -0,0 +1,53 @@
1
+ import { builtinModules } from 'module';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+
5
+ const SRC_DIR = path.resolve(__dirname, '..');
6
+ const SERVER_DIR = path.join(SRC_DIR, 'server');
7
+ const TESTS_DIR = path.join(SRC_DIR, '__tests__');
8
+
9
+ // `ws` and every Node built-in module (`fs`, `net`, `http`, `node:*`...) are forbidden outside
10
+ // `src/server`, so that the package root stays usable in a browser.
11
+ const FORBIDDEN = new Set<string>(['ws', ...builtinModules]);
12
+
13
+ const walkTsFiles = (dir: string): string[] =>
14
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
15
+ const full = path.join(dir, entry.name);
16
+ if (entry.isDirectory()) {
17
+ return full === SERVER_DIR || full === TESTS_DIR ? [] : walkTsFiles(full);
18
+ }
19
+ return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') ? [full] : [];
20
+ });
21
+
22
+ const IMPORT_PATTERNS = [
23
+ /\bfrom\s*['"]([^'"]+)['"]/g,
24
+ /\bimport\s*['"]([^'"]+)['"]/g,
25
+ /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
26
+ /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
27
+ ];
28
+
29
+ const importedSpecifiers = (text: string): string[] =>
30
+ IMPORT_PATTERNS.flatMap((pattern) => [...text.matchAll(pattern)].map((match) => match[1]));
31
+
32
+ const isForbidden = (specifier: string): boolean => {
33
+ const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;
34
+ return FORBIDDEN.has(bare) || FORBIDDEN.has(bare.split('/')[0]);
35
+ };
36
+
37
+ describe('browser-compatible package root', () => {
38
+ it('imports no Node built-in nor ws outside src/server', () => {
39
+ const offenders = walkTsFiles(SRC_DIR).flatMap((file) =>
40
+ importedSpecifiers(fs.readFileSync(file, 'utf8'))
41
+ .filter(isForbidden)
42
+ .map((specifier) => `${path.relative(SRC_DIR, file)} imports ${specifier}`),
43
+ );
44
+ expect(offenders).toEqual([]);
45
+ });
46
+
47
+ it('detects forbidden imports (guard sanity)', () => {
48
+ const source = "import { WebSocket } from 'ws';\nconst n = require('node:net');";
49
+ expect(importedSpecifiers(source)).toEqual(['ws', 'node:net']);
50
+ expect(['ws', 'node:net', 'fs/promises', 'http'].every(isForbidden)).toBe(true);
51
+ expect(['joi', './steps', '../access'].some(isForbidden)).toBe(false);
52
+ });
53
+ });
@@ -0,0 +1,24 @@
1
+ import { hostMatches } from '../host-match';
2
+
3
+ describe('hostMatches', () => {
4
+ it('matches an exact host', () => {
5
+ expect(hostMatches('api.example.com', 'api.example.com')).toBe(true);
6
+ expect(hostMatches('api.example.com', 'example.com')).toBe(false);
7
+ });
8
+
9
+ it('lets a wildcard cover any sub-domain', () => {
10
+ expect(hostMatches('api.example.com', '*.example.com')).toBe(true);
11
+ expect(hostMatches('a.b.example.com', '*.example.com')).toBe(true);
12
+ });
13
+
14
+ it('does not let a wildcard cover the apex domain', () => {
15
+ expect(hostMatches('example.com', '*.example.com')).toBe(false);
16
+ expect(hostMatches('.example.com', '*.example.com')).toBe(false);
17
+ expect(hostMatches('badexample.com', '*.example.com')).toBe(false);
18
+ });
19
+
20
+ it('ignores case', () => {
21
+ expect(hostMatches('API.Example.COM', 'api.example.com')).toBe(true);
22
+ expect(hostMatches('api.example.com', '*.EXAMPLE.com')).toBe(true);
23
+ });
24
+ });
@@ -0,0 +1,25 @@
1
+ export enum AccessKind {
2
+ /** Outbound HTTP to a list of host names (exact, or `*.domain` for any sub-domain). */
3
+ HTTP = 'HTTP',
4
+ /** One action of the host catalog, by name. */
5
+ HOST_ACTION = 'HOST_ACTION',
6
+ }
7
+
8
+ export interface HttpAccess {
9
+ kind: AccessKind.HTTP;
10
+ hosts: string[];
11
+ }
12
+
13
+ export interface HostActionAccess {
14
+ kind: AccessKind.HOST_ACTION;
15
+ action: string;
16
+ }
17
+
18
+ /**
19
+ * What a definition declares it needs (like the `permissions:` block of GitHub Actions), and,
20
+ * with the same shape, what a run is actually granted. An effect is emitted only when both
21
+ * cover it.
22
+ */
23
+ export type AccessDeclaration = HttpAccess | HostActionAccess;
24
+
25
+ export type AccessGrant = AccessDeclaration;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Whether `host` is covered by an access `pattern`: an exact host name, or `*.domain`, which
3
+ * covers any sub-domain of `domain` but not `domain` itself. Comparison ignores case.
4
+ */
5
+ export const hostMatches = (host: string, pattern: string): boolean => {
6
+ const candidate = host.toLowerCase();
7
+ const expected = pattern.toLowerCase();
8
+ if (!expected.startsWith('*.')) {
9
+ return candidate === expected;
10
+ }
11
+ const suffix = expected.slice(1);
12
+ return candidate.length > suffix.length && candidate.endsWith(suffix);
13
+ };
@@ -0,0 +1,200 @@
1
+ import {
2
+ COST_RATES,
3
+ CostedExecutionStatus,
4
+ RESOURCE_PROFILES,
5
+ ResourceProfile,
6
+ computeExecutionCost,
7
+ computeStepCost,
8
+ } from '../execution-cost';
9
+ import type { ExecutionCostInput, StepUsage } from '../execution-cost';
10
+
11
+ const NO_USAGE: StepUsage = { cpuMs: 0, wallMs: 0, netOutBytes: 0, httpCalls: 0, storeWrites: 0 };
12
+
13
+ const execution = (overrides: Partial<ExecutionCostInput> = {}): ExecutionCostInput => ({
14
+ ...NO_USAGE,
15
+ status: CostedExecutionStatus.RAN,
16
+ profile: ResourceProfile.S,
17
+ guaranteedCpu: false,
18
+ ...overrides,
19
+ });
20
+
21
+ const usage = (overrides: Partial<StepUsage>): StepUsage => ({ ...NO_USAGE, ...overrides });
22
+
23
+ const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0);
24
+
25
+ describe('resource profiles and rates', () => {
26
+ it('follow ADR-0239', () => {
27
+ expect(RESOURCE_PROFILES).toEqual({
28
+ S: { memoryMb: 128, cpuCoefficient: 1 },
29
+ M: { memoryMb: 256, cpuCoefficient: 1.05 },
30
+ L: { memoryMb: 512, cpuCoefficient: 1.1 },
31
+ XL: { memoryMb: 1024, cpuCoefficient: 1.2 },
32
+ XXL: { memoryMb: 2048, cpuCoefficient: 1.35 },
33
+ });
34
+ expect(COST_RATES).toEqual({
35
+ executionMillicredits: 10,
36
+ cpuMillicreditsPerSecond: 500,
37
+ guaranteedCpuCoefficient: 1.5,
38
+ memoryMillicreditsPerGbSecond: 100,
39
+ networkOutMillicreditsPerMb: 1000,
40
+ httpCallMillicredits: 10,
41
+ storeWriteMillicredits: 10,
42
+ });
43
+ });
44
+ });
45
+
46
+ describe('computeExecutionCost', () => {
47
+ it('prices a 3 s wait in profile S at about 0.05 credit', () => {
48
+ // 10 + 0.125 GB × 3 s × 100 = 47.5, rounded half-up.
49
+ const cost = computeExecutionCost(execution({ wallMs: 3_000 }));
50
+ expect(cost).toBe(48);
51
+ expect(cost / 1000).toBeCloseTo(0.05, 2);
52
+ });
53
+
54
+ it('prices 2 s of CPU in profile L at about 1.1 credits for the CPU part', () => {
55
+ const computing = computeExecutionCost(
56
+ execution({ profile: ResourceProfile.L, cpuMs: 2_000, wallMs: 2_000 }),
57
+ );
58
+ const waiting = computeExecutionCost(execution({ profile: ResourceProfile.L, wallMs: 2_000 }));
59
+ expect(computing - waiting).toBe(1_100);
60
+ // 10 + 1100 CPU + 0.5 GB × 2 s × 100 memory.
61
+ expect(computing).toBe(1_210);
62
+ });
63
+
64
+ it('makes a computation cost more than a wait of the same duration', () => {
65
+ const wall = { wallMs: 3_000 };
66
+ expect(computeExecutionCost(execution({ ...wall, cpuMs: 3_000 }))).toBeGreaterThan(
67
+ computeExecutionCost(execution(wall)),
68
+ );
69
+ });
70
+
71
+ it('applies the profile coefficient and the guaranteed CPU coefficient to the CPU part', () => {
72
+ const cpu = { cpuMs: 1_000 };
73
+ expect(computeExecutionCost(execution(cpu))).toBe(10 + 500);
74
+ expect(computeExecutionCost(execution({ ...cpu, guaranteedCpu: true }))).toBe(10 + 750);
75
+ expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.XXL }))).toBe(
76
+ 10 + 675,
77
+ );
78
+ expect(
79
+ computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.M, guaranteedCpu: true })),
80
+ ).toBe(10 + 788); // 500 × 1.05 × 1.5 = 787.5
81
+ });
82
+
83
+ it('prices the allocated memory, the network out and the effects', () => {
84
+ expect(computeExecutionCost(execution({ profile: ResourceProfile.XL, wallMs: 1_000 }))).toBe(
85
+ 10 + 100,
86
+ );
87
+ expect(computeExecutionCost(execution({ netOutBytes: 1024 * 1024 }))).toBe(10 + 1_000);
88
+ expect(computeExecutionCost(execution({ httpCalls: 2, storeWrites: 3 }))).toBe(10 + 50);
89
+ });
90
+
91
+ it('rounds half-up once, at the end', () => {
92
+ // 128 MB × 40 ms = 0.5 millicredit.
93
+ expect(computeExecutionCost(execution({ wallMs: 40 }))).toBe(11);
94
+ // Fractions of a millisecond count.
95
+ expect(computeExecutionCost(execution({ cpuMs: 0.999 }))).toBe(10);
96
+ expect(computeExecutionCost(execution({ cpuMs: 1 }))).toBe(11);
97
+ });
98
+
99
+ it('makes an interrupted or refused execution free', () => {
100
+ const heavy = { cpuMs: 5_000, wallMs: 9_000, netOutBytes: 10_000_000, httpCalls: 4 };
101
+ expect(
102
+ computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.INTERRUPTED })),
103
+ ).toBe(0);
104
+ expect(
105
+ computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.REFUSED })),
106
+ ).toBe(0);
107
+ });
108
+
109
+ it('charges the execution price once: a resumed segment adds only its measure', () => {
110
+ expect(computeExecutionCost(execution({ wallMs: 3_000, resumedSegment: true }))).toBe(38);
111
+ });
112
+
113
+ it('refuses a negative or non-finite measure', () => {
114
+ expect(() => computeExecutionCost(execution({ cpuMs: -1 }))).toThrow(RangeError);
115
+ expect(() => computeExecutionCost(execution({ wallMs: Number.NaN }))).toThrow(RangeError);
116
+ });
117
+ });
118
+
119
+ describe('computeStepCost', () => {
120
+ it('gives each step its share, so that steps plus the execution price equal the total', () => {
121
+ const steps = [
122
+ usage({ cpuMs: 3.3, wallMs: 12.7 }),
123
+ usage({ cpuMs: 120.25, wallMs: 450, httpCalls: 1, netOutBytes: 2_345 }),
124
+ usage({ wallMs: 3_000 }),
125
+ usage({ cpuMs: 7.77, wallMs: 9.1, storeWrites: 2 }),
126
+ ];
127
+ const total = execution({
128
+ profile: ResourceProfile.M,
129
+ guaranteedCpu: true,
130
+ // The engine between the steps adds CPU and time measured at the execution level only.
131
+ cpuMs: 140,
132
+ wallMs: 3_500,
133
+ httpCalls: 1,
134
+ storeWrites: 2,
135
+ netOutBytes: 2_345,
136
+ });
137
+ const costs = computeStepCost({ execution: total, steps });
138
+ expect(costs).toHaveLength(4);
139
+ costs.forEach((cost) => expect(Number.isInteger(cost)).toBe(true));
140
+ expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
141
+ expect(costs[2]).toBeGreaterThan(costs[0]);
142
+ });
143
+
144
+ it('holds the invariant over many shapes', () => {
145
+ for (let n = 1; n <= 40; n += 1) {
146
+ const steps = Array.from({ length: n }, (_, i) =>
147
+ usage({ cpuMs: (i * 7.3) % 11, wallMs: (i * 13.1) % 29, httpCalls: i % 3 === 0 ? 1 : 0 }),
148
+ );
149
+ const totals = steps.reduce(
150
+ (acc, step) => ({
151
+ cpuMs: acc.cpuMs + step.cpuMs,
152
+ wallMs: acc.wallMs + step.wallMs,
153
+ httpCalls: acc.httpCalls + step.httpCalls,
154
+ }),
155
+ { cpuMs: 0.37 * n, wallMs: 1.9 * n, httpCalls: 0 },
156
+ );
157
+ for (const profile of Object.values(ResourceProfile)) {
158
+ const total = execution({ ...totals, profile, guaranteedCpu: n % 2 === 0 });
159
+ const costs = computeStepCost({ execution: total, steps });
160
+ expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
161
+ }
162
+ }
163
+ });
164
+
165
+ it('rounds cumulatively instead of rounding each step', () => {
166
+ // Three steps of 0.4 millicredit each (128 MB × 32 ms): 1.2 in total.
167
+ const step = usage({ wallMs: 32 });
168
+ const total = execution({ wallMs: 96 });
169
+ expect(computeExecutionCost(total)).toBe(11);
170
+ expect(computeStepCost({ execution: total, steps: [step, step, step] })).toEqual([0, 1, 0]);
171
+ });
172
+
173
+ it('carries no execution price on a resumed segment', () => {
174
+ const total = execution({ wallMs: 3_000, resumedSegment: true });
175
+ const costs = computeStepCost({ execution: total, steps: [usage({ wallMs: 3_000 })] });
176
+ expect(sum(costs)).toBe(computeExecutionCost(total));
177
+ });
178
+
179
+ it('is zero for every step of an interrupted execution', () => {
180
+ const total = execution({
181
+ status: CostedExecutionStatus.INTERRUPTED,
182
+ cpuMs: 900,
183
+ wallMs: 2_000,
184
+ });
185
+ expect(
186
+ computeStepCost({ execution: total, steps: [usage({ cpuMs: 400 }), usage({ cpuMs: 500 })] }),
187
+ ).toEqual([0, 0]);
188
+ expect(computeExecutionCost(total)).toBe(0);
189
+ });
190
+
191
+ it('returns nothing for an execution without step', () => {
192
+ expect(computeStepCost({ execution: execution({ wallMs: 10 }), steps: [] })).toEqual([]);
193
+ });
194
+
195
+ it('refuses a negative step measure', () => {
196
+ expect(() =>
197
+ computeStepCost({ execution: execution(), steps: [usage({ httpCalls: -1 })] }),
198
+ ).toThrow(RangeError);
199
+ });
200
+ });