@telorun/kernel 0.12.0 → 1.2.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/LICENSE +2 -2
- package/dist/application-env.d.ts +24 -0
- package/dist/application-env.d.ts.map +1 -0
- package/dist/application-env.js +156 -0
- package/dist/application-env.js.map +1 -0
- package/dist/controller-loaders/npm-loader.d.ts +1 -6
- package/dist/controller-loaders/npm-loader.d.ts.map +1 -1
- package/dist/controller-loaders/npm-loader.js +21 -62
- package/dist/controller-loaders/npm-loader.js.map +1 -1
- package/dist/controllers/module/import-controller.d.ts +3 -2
- package/dist/controllers/module/import-controller.d.ts.map +1 -1
- package/dist/controllers/module/import-controller.js +23 -25
- package/dist/controllers/module/import-controller.js.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.d.ts +1 -0
- package/dist/controllers/resource-definition/resource-definition-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.js +3 -0
- package/dist/controllers/resource-definition/resource-definition-controller.js.map +1 -1
- package/dist/controllers/resource-definition/resource-template-controller.d.ts +5 -0
- package/dist/controllers/resource-definition/resource-template-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-template-controller.js +67 -6
- package/dist/controllers/resource-definition/resource-template-controller.js.map +1 -1
- package/dist/internal-context.d.ts +25 -0
- package/dist/internal-context.d.ts.map +1 -0
- package/dist/internal-context.js +2 -0
- package/dist/internal-context.js.map +1 -0
- package/dist/kernel.d.ts +21 -1
- package/dist/kernel.d.ts.map +1 -1
- package/dist/kernel.js +91 -4
- package/dist/kernel.js.map +1 -1
- package/dist/manifest-schemas.d.ts +7 -23
- package/dist/manifest-schemas.d.ts.map +1 -1
- package/dist/manifest-schemas.js +13 -8
- package/dist/manifest-schemas.js.map +1 -1
- package/dist/manifest-sources/analysis-stamp.d.ts +25 -0
- package/dist/manifest-sources/analysis-stamp.d.ts.map +1 -0
- package/dist/manifest-sources/analysis-stamp.js +151 -0
- package/dist/manifest-sources/analysis-stamp.js.map +1 -0
- package/dist/resource-context.d.ts +2 -0
- package/dist/resource-context.d.ts.map +1 -1
- package/dist/resource-context.js +6 -0
- package/dist/resource-context.js.map +1 -1
- package/dist/schema-validator.d.ts +28 -0
- package/dist/schema-validator.d.ts.map +1 -1
- package/dist/schema-validator.js +156 -1
- package/dist/schema-validator.js.map +1 -1
- package/package.json +7 -6
- package/src/application-env.ts +216 -0
- package/src/controller-loaders/npm-loader.ts +21 -62
- package/src/controllers/module/import-controller.ts +33 -36
- package/src/controllers/resource-definition/resource-definition-controller.ts +6 -0
- package/src/controllers/resource-definition/resource-template-controller.ts +95 -7
- package/src/internal-context.ts +25 -0
- package/src/kernel.ts +110 -4
- package/src/manifest-schemas.ts +22 -12
- package/src/manifest-sources/analysis-stamp.ts +169 -0
- package/src/resource-context.ts +8 -0
- package/src/schema-validator.ts +173 -2
- package/dist/generated/runtime-deps.json +0 -6
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telorun/kernel",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Telo Runtime - A lightweight, polyglot execution host.",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"
|
|
6
|
+
"telo",
|
|
7
7
|
"runtime",
|
|
8
8
|
"execution",
|
|
9
9
|
"manifest"
|
|
@@ -47,8 +47,7 @@
|
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@marcbachmann/cel-js": "^7.5.3",
|
|
49
49
|
"@sinclair/typebox": "^0.34.48",
|
|
50
|
-
"@telorun/analyzer": "
|
|
51
|
-
"@telorun/sdk": "0.11.1",
|
|
50
|
+
"@telorun/analyzer": "1.2.0",
|
|
52
51
|
"ajv": "^8.17.1",
|
|
53
52
|
"ajv-formats": "^3.0.1",
|
|
54
53
|
"minimatch": "^10.2.5",
|
|
@@ -60,11 +59,13 @@
|
|
|
60
59
|
"typescript": "^5.0.0",
|
|
61
60
|
"vitest": "^2.1.8"
|
|
62
61
|
},
|
|
62
|
+
"peerDependencies": {
|
|
63
|
+
"@telorun/sdk": "1.0.0"
|
|
64
|
+
},
|
|
63
65
|
"overrides": {
|
|
64
66
|
"@marcbachmann/cel-js": "$@marcbachmann/cel-js",
|
|
65
67
|
"@sinclair/typebox": "$@sinclair/typebox",
|
|
66
68
|
"@telorun/analyzer": "$@telorun/analyzer",
|
|
67
|
-
"@telorun/sdk": "$@telorun/sdk",
|
|
68
69
|
"ajv": "$ajv",
|
|
69
70
|
"ajv-formats": "$ajv-formats",
|
|
70
71
|
"minimatch": "$minimatch",
|
|
@@ -72,7 +73,7 @@
|
|
|
72
73
|
"yaml": "$yaml"
|
|
73
74
|
},
|
|
74
75
|
"scripts": {
|
|
75
|
-
"build": "tsc
|
|
76
|
+
"build": "tsc",
|
|
76
77
|
"dev": "tsc --watch",
|
|
77
78
|
"test": "vitest run",
|
|
78
79
|
"test:watch": "vitest"
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { residualEntrySchema } from "@telorun/analyzer";
|
|
2
|
+
import { RuntimeError } from "@telorun/sdk";
|
|
3
|
+
import { SchemaValidator } from "./schema-validator.js";
|
|
4
|
+
|
|
5
|
+
type EntryType = "string" | "integer" | "number" | "boolean" | "object" | "array";
|
|
6
|
+
|
|
7
|
+
interface EnvEntry {
|
|
8
|
+
env: string;
|
|
9
|
+
type: EntryType;
|
|
10
|
+
default?: unknown;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface EnvResolutionResult {
|
|
15
|
+
variables: Record<string, unknown>;
|
|
16
|
+
secrets: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Populate the root Application's `variables` / `secrets` namespaces from
|
|
21
|
+
* host environment variables, per the per-field `env:` mapping declared on
|
|
22
|
+
* each entry.
|
|
23
|
+
*
|
|
24
|
+
* Implements the polyglot env-resolution spec from
|
|
25
|
+
* kernel/nodejs/plans/application-env-variables.md: read the env var, coerce
|
|
26
|
+
* per `entry.type`, validate the coerced value (or the declared default, when
|
|
27
|
+
* the env var is unset) against the entry's residual schema, and aggregate
|
|
28
|
+
* every failure into a single `ERR_MANIFEST_VALIDATION_FAILED` error so all
|
|
29
|
+
* problems surface before any controller initializes.
|
|
30
|
+
*
|
|
31
|
+
* This must run BEFORE any Telo.Import controller initializes — imports may
|
|
32
|
+
* pass `${{ variables.X }}` as their `variables:` inputs, so the root scope
|
|
33
|
+
* has to be populated by the time the import controller evaluates those
|
|
34
|
+
* expressions.
|
|
35
|
+
*/
|
|
36
|
+
export function resolveApplicationEnv(
|
|
37
|
+
manifest: Record<string, any>,
|
|
38
|
+
env: Record<string, string | undefined>,
|
|
39
|
+
validator: SchemaValidator,
|
|
40
|
+
): EnvResolutionResult {
|
|
41
|
+
const errors: string[] = [];
|
|
42
|
+
const variables = resolveBlock(
|
|
43
|
+
manifest.variables ?? {},
|
|
44
|
+
env,
|
|
45
|
+
validator,
|
|
46
|
+
errors,
|
|
47
|
+
false,
|
|
48
|
+
);
|
|
49
|
+
const secrets = resolveBlock(
|
|
50
|
+
manifest.secrets ?? {},
|
|
51
|
+
env,
|
|
52
|
+
validator,
|
|
53
|
+
errors,
|
|
54
|
+
true,
|
|
55
|
+
);
|
|
56
|
+
if (errors.length > 0) {
|
|
57
|
+
throw new RuntimeError(
|
|
58
|
+
"ERR_MANIFEST_VALIDATION_FAILED",
|
|
59
|
+
`Application environment validation failed:\n` +
|
|
60
|
+
errors.map((e) => ` - ${e}`).join("\n"),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
return { variables, secrets };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function resolveBlock(
|
|
67
|
+
block: Record<string, EnvEntry> | unknown,
|
|
68
|
+
env: Record<string, string | undefined>,
|
|
69
|
+
validator: SchemaValidator,
|
|
70
|
+
errors: string[],
|
|
71
|
+
isSecret: boolean,
|
|
72
|
+
): Record<string, unknown> {
|
|
73
|
+
const out: Record<string, unknown> = {};
|
|
74
|
+
if (!block || typeof block !== "object" || Array.isArray(block)) {
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
for (const [name, entry] of Object.entries(block as Record<string, EnvEntry>)) {
|
|
78
|
+
if (!entry || typeof entry !== "object") continue;
|
|
79
|
+
const envKey = entry.env;
|
|
80
|
+
const raw = env[envKey];
|
|
81
|
+
const residual = residualEntrySchema(entry as Record<string, unknown>);
|
|
82
|
+
|
|
83
|
+
if (raw === undefined || raw === null) {
|
|
84
|
+
if (entry.default !== undefined) {
|
|
85
|
+
const validation = validateResidual(entry.default, residual, validator);
|
|
86
|
+
if (validation) {
|
|
87
|
+
errors.push(`${name}: ${validation}`);
|
|
88
|
+
} else {
|
|
89
|
+
out[name] = entry.default;
|
|
90
|
+
}
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
errors.push(`${name}: environment variable ${envKey} is not set (no default)`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let coerced: unknown;
|
|
98
|
+
try {
|
|
99
|
+
coerced = coerce(raw, entry.type, envKey, isSecret);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
errors.push(`${name}: ${(e as Error).message}`);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const validation = validateResidual(coerced, residual, validator);
|
|
106
|
+
if (validation) {
|
|
107
|
+
errors.push(`${name}: ${validation}`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
out[name] = coerced;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Render a raw env value for inclusion in an error message. Secret values
|
|
117
|
+
* are masked so coercion / schema diagnostics don't leak secret material
|
|
118
|
+
* into logs (the env-var name and the failure reason still surface). */
|
|
119
|
+
function renderRawForError(raw: string, isSecret: boolean): string {
|
|
120
|
+
return isSecret ? "<redacted>" : `"${raw}"`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function coerce(
|
|
124
|
+
raw: string,
|
|
125
|
+
type: EntryType,
|
|
126
|
+
envKey: string,
|
|
127
|
+
isSecret: boolean,
|
|
128
|
+
): unknown {
|
|
129
|
+
switch (type) {
|
|
130
|
+
case "string":
|
|
131
|
+
return raw;
|
|
132
|
+
case "integer": {
|
|
133
|
+
const trimmed = raw.trim();
|
|
134
|
+
if (!/^-?\d+$/.test(trimmed)) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`environment variable ${envKey}: value ${renderRawForError(raw, isSecret)} is not a valid integer`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return parseInt(trimmed, 10);
|
|
140
|
+
}
|
|
141
|
+
case "number": {
|
|
142
|
+
const n = parseFloat(raw);
|
|
143
|
+
if (Number.isNaN(n)) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`environment variable ${envKey}: value ${renderRawForError(raw, isSecret)} is not a valid number`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
return n;
|
|
149
|
+
}
|
|
150
|
+
case "boolean":
|
|
151
|
+
if (raw === "true") return true;
|
|
152
|
+
if (raw === "false") return false;
|
|
153
|
+
throw new Error(
|
|
154
|
+
`environment variable ${envKey}: value ${renderRawForError(raw, isSecret)} is not a valid boolean (expected "true" or "false")`,
|
|
155
|
+
);
|
|
156
|
+
case "object": {
|
|
157
|
+
const parsed = parseJson(raw, envKey, isSecret);
|
|
158
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`environment variable ${envKey}: expected JSON object, got ${describeJsonType(parsed)}`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
return parsed;
|
|
164
|
+
}
|
|
165
|
+
case "array": {
|
|
166
|
+
const parsed = parseJson(raw, envKey, isSecret);
|
|
167
|
+
if (!Array.isArray(parsed)) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`environment variable ${envKey}: expected JSON array, got ${describeJsonType(parsed)}`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return parsed;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function parseJson(raw: string, envKey: string, isSecret: boolean): unknown {
|
|
178
|
+
try {
|
|
179
|
+
return JSON.parse(raw);
|
|
180
|
+
} catch (e) {
|
|
181
|
+
// Node's JSON.parse error embeds the offending character / position; for
|
|
182
|
+
// secrets, swallow the parser detail and surface only the env var name.
|
|
183
|
+
const detail = isSecret ? "value is not valid JSON" : (e as Error).message;
|
|
184
|
+
throw new Error(`environment variable ${envKey}: ${isSecret ? detail : `value is not valid JSON: ${detail}`}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function describeJsonType(value: unknown): string {
|
|
189
|
+
if (value === null) return "null";
|
|
190
|
+
if (Array.isArray(value)) return "array";
|
|
191
|
+
return typeof value;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function validateResidual(
|
|
195
|
+
value: unknown,
|
|
196
|
+
residual: Record<string, unknown>,
|
|
197
|
+
validator: SchemaValidator,
|
|
198
|
+
): string | null {
|
|
199
|
+
try {
|
|
200
|
+
validator.compile(residual as any).validate(value);
|
|
201
|
+
return null;
|
|
202
|
+
} catch (e) {
|
|
203
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
204
|
+
// Strip SchemaValidator's "Invalid value passed: <JSON>. Error: " prefix
|
|
205
|
+
// so the JSON-stringified value (which can be secret material for entries
|
|
206
|
+
// under `secrets:`) never reaches the caller. The split is anchored on
|
|
207
|
+
// the literal ". Error: " delimiter — a `[^.]*` regex would have leaked
|
|
208
|
+
// any value containing a dot (URLs, versions, paths).
|
|
209
|
+
const sentinel = ". Error: ";
|
|
210
|
+
const idx = msg.indexOf(sentinel);
|
|
211
|
+
if (msg.startsWith("Invalid value passed:") && idx !== -1) {
|
|
212
|
+
return msg.slice(idx + sentinel.length);
|
|
213
|
+
}
|
|
214
|
+
return msg;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -201,25 +201,22 @@ export class NpmControllerLoader {
|
|
|
201
201
|
const entryDir = path.dirname(path.resolve(entryPath));
|
|
202
202
|
const installRoot = path.join(entryDir, ".telo", "npm");
|
|
203
203
|
|
|
204
|
-
// Build the install-root package.json: kernel-runtime deps as `file:` refs
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
//
|
|
208
|
-
//
|
|
209
|
-
//
|
|
210
|
-
const runtimeDeps = await loadRuntimeDeps();
|
|
204
|
+
// Build the install-root package.json: kernel-runtime deps as `file:` refs
|
|
205
|
+
// pointing at the kernel-side realpath. Modules declare these names as
|
|
206
|
+
// `peerDependencies`, so npm/pnpm resolve each controller's `import` to the
|
|
207
|
+
// single copy provided here — the realm-collapse mechanism that gives
|
|
208
|
+
// class-identity-sensitive types (today: `Stream`) one constructor across
|
|
209
|
+
// the kernel/controller boundary.
|
|
211
210
|
const dependencies: Record<string, string> = {};
|
|
212
|
-
const
|
|
213
|
-
for (const name of runtimeDeps) {
|
|
211
|
+
for (const name of REALM_COLLAPSE_NAMES) {
|
|
214
212
|
const resolvedPkgRoot = await resolveKernelPackageRoot(name);
|
|
215
213
|
if (!resolvedPkgRoot) {
|
|
216
214
|
// A kernel runtime dep that can't be resolved at boot is unusual but
|
|
217
|
-
// not fatal — the realm-collapse story degrades to "rely on
|
|
218
|
-
//
|
|
215
|
+
// not fatal — the realm-collapse story degrades to "rely on whatever
|
|
216
|
+
// the package manager picks" for that name. Don't crash the loader.
|
|
219
217
|
continue;
|
|
220
218
|
}
|
|
221
219
|
dependencies[name] = `file:${resolvedPkgRoot}`;
|
|
222
|
-
overrides[name] = `$${name}`;
|
|
223
220
|
}
|
|
224
221
|
|
|
225
222
|
const packageJson = {
|
|
@@ -227,8 +224,6 @@ export class NpmControllerLoader {
|
|
|
227
224
|
private: true,
|
|
228
225
|
version: "0.0.0",
|
|
229
226
|
dependencies,
|
|
230
|
-
overrides,
|
|
231
|
-
pnpm: { overrides },
|
|
232
227
|
};
|
|
233
228
|
const packageJsonPath = path.join(installRoot, "package.json");
|
|
234
229
|
const stateFile = path.join(installRoot, ".telo-state.json");
|
|
@@ -405,54 +400,18 @@ export class NpmControllerLoader {
|
|
|
405
400
|
}
|
|
406
401
|
|
|
407
402
|
/**
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
*
|
|
412
|
-
*
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
// Walk up from this file's location to the kernel-package root (the dir
|
|
419
|
-
// that contains package.json). In dev: `kernel/nodejs/`. In published:
|
|
420
|
-
// the installed package root inside `node_modules/@telorun/kernel/`.
|
|
421
|
-
// Walk-until-root rather than a fixed depth — the directory tree depth
|
|
422
|
-
// depends on whether we're in a workspace or installed tree.
|
|
423
|
-
const pkgDir = await walkUpToPackageRoot(path.dirname(here));
|
|
424
|
-
if (!pkgDir) return [];
|
|
425
|
-
|
|
426
|
-
const generated = path.join(pkgDir, "dist", "generated", "runtime-deps.json");
|
|
427
|
-
if (!(await pathExists(generated))) return [];
|
|
428
|
-
// The file is generated by `scripts/generate-runtime-deps.mjs`; if it
|
|
429
|
-
// exists but is malformed, that's a kernel-build bug. Don't swallow —
|
|
430
|
-
// surface so the cause is debuggable. Realm collapse is the whole point
|
|
431
|
-
// of this code path; quietly degrading to "no realm collapse" would
|
|
432
|
-
// silently re-introduce the very bug the file fixes.
|
|
433
|
-
const data = JSON.parse(await fs.readFile(generated, "utf8"));
|
|
434
|
-
if (!Array.isArray(data?.names)) {
|
|
435
|
-
throw new Error(
|
|
436
|
-
`[telo] ${generated} is malformed: expected { names: string[] } at top level. ` +
|
|
437
|
-
`Re-run \`node scripts/generate-runtime-deps.mjs <pkg-dir>\` to regenerate.`,
|
|
438
|
-
);
|
|
439
|
-
}
|
|
440
|
-
return data.names as string[];
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
/**
|
|
444
|
-
* Walk up from `from` until the directory contains a `package.json`.
|
|
445
|
-
* Returns null at filesystem root if none found.
|
|
403
|
+
* Names of packages whose realpath must be shared between the kernel and every
|
|
404
|
+
* loaded controller. Each name here becomes a `file:` dep in the install-root
|
|
405
|
+
* `package.json`, pinned at the kernel's own resolution; controllers declare
|
|
406
|
+
* these names as `peerDependencies` so npm/pnpm resolves them to that single
|
|
407
|
+
* copy instead of nesting their own.
|
|
408
|
+
*
|
|
409
|
+
* Add a name here if you ship another shared runtime symbol whose `instanceof`
|
|
410
|
+
* or constructor identity matters across module boundaries. Today the only
|
|
411
|
+
* such name is `@telorun/sdk` (carries the `Stream` class registered with
|
|
412
|
+
* `@marcbachmann/cel-js`).
|
|
446
413
|
*/
|
|
447
|
-
|
|
448
|
-
let dir = from;
|
|
449
|
-
while (true) {
|
|
450
|
-
if (await pathExists(path.join(dir, "package.json"))) return dir;
|
|
451
|
-
const parent = path.dirname(dir);
|
|
452
|
-
if (parent === dir) return null;
|
|
453
|
-
dir = parent;
|
|
454
|
-
}
|
|
455
|
-
}
|
|
414
|
+
const REALM_COLLAPSE_NAMES: ReadonlyArray<string> = ["@telorun/sdk"];
|
|
456
415
|
|
|
457
416
|
/**
|
|
458
417
|
* Resolve a kernel-runtime dep name to the realpath of its package directory.
|
|
@@ -954,7 +913,7 @@ export const __testing__ = {
|
|
|
954
913
|
resolvePackageExportTarget,
|
|
955
914
|
resolveExportTargetValue,
|
|
956
915
|
tryResolveFile,
|
|
957
|
-
walkUpToPackageRoot,
|
|
958
916
|
EXPORTS_MAX_DEPTH,
|
|
959
917
|
DEFAULT_RESOLVER_CONDITIONS,
|
|
918
|
+
REALM_COLLAPSE_NAMES,
|
|
960
919
|
};
|
|
@@ -1,26 +1,14 @@
|
|
|
1
1
|
import { DiagnosticSeverity, StaticAnalyzer } from "@telorun/analyzer";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ResourceInstance } from "@telorun/sdk";
|
|
3
3
|
import { RuntimeError } from "@telorun/sdk";
|
|
4
|
+
import type { BuiltinControllerContext } from "../../internal-context.js";
|
|
4
5
|
import { ModuleContext } from "../../module-context.js";
|
|
5
6
|
import { isDefaultPolicy, normalizeRuntime } from "../../runtime-registry.js";
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
>
|
|
11
|
-
|
|
12
|
-
// Only resolve relative/absolute-path sources against the importer's URL. Registry refs
|
|
13
|
-
// (std/foo@1.2.3) and absolute URLs (https://, file://) must pass through unchanged so the
|
|
14
|
-
// loader's source chain can dispatch them — otherwise `new URL("std/foo@1", "file:///srv/telo.yaml")`
|
|
15
|
-
// turns a registry ref into a bogus file path and LocalFileSource ENOENTs on it.
|
|
16
|
-
function resolveImportSource(source: string, baseSource: string): string {
|
|
17
|
-
if (source.startsWith(".") || source.startsWith("/")) {
|
|
18
|
-
return new URL(source, baseSource).toString();
|
|
19
|
-
}
|
|
20
|
-
return source;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export async function create(resource: any, ctx: ResourceContext): Promise<ResourceInstance> {
|
|
8
|
+
export async function create(
|
|
9
|
+
resource: any,
|
|
10
|
+
ctx: BuiltinControllerContext,
|
|
11
|
+
): Promise<ResourceInstance> {
|
|
24
12
|
const alias = resource.metadata.name as string;
|
|
25
13
|
|
|
26
14
|
const moduleSource: string = resource.module ?? resource.source;
|
|
@@ -36,27 +24,36 @@ export async function create(resource: any, ctx: ResourceContext): Promise<Resou
|
|
|
36
24
|
// Validate the imported module and all its transitive imports before loading for runtime.
|
|
37
25
|
// loadManifests() follows Telo.Import chains so definitions from sub-imports are present,
|
|
38
26
|
// preventing false UNDEFINED_KIND errors for kinds that come from the module's own imports.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
27
|
+
//
|
|
28
|
+
// Route URL resolution through the kernel/loader's own helper rather than
|
|
29
|
+
// a hand-rolled `new URL(...).toString()`. For LocalFileSource the
|
|
30
|
+
// outputs match; for any custom `ManifestSource` with a non-trivial
|
|
31
|
+
// `resolveRelative`, only this path produces the canonical URL the
|
|
32
|
+
// loader keyed its caches under — without which fast paths like
|
|
33
|
+
// `isImportValidatedAtLoad` silently miss.
|
|
34
|
+
const resolvedUrl = ctx.resolveImportUrl(base, moduleSource);
|
|
35
|
+
|
|
36
|
+
// Fast path: when the kernel's load-time `analyzeErrors` already covered
|
|
37
|
+
// this import's subtree (the common case — every Telo.Import declared in
|
|
38
|
+
// the entry graph is walked by `loadGraph` and validated by
|
|
39
|
+
// `kernel.load`), skip the redundant per-import StaticAnalyzer pass.
|
|
40
|
+
// Falls through to the full analysis for URLs that arrived
|
|
41
|
+
// programmatically after `load()` (e.g. dynamically constructed imports
|
|
42
|
+
// in tests). Two Telo.Imports with the same source but distinct
|
|
43
|
+
// metadata.name would each re-run analysis here — a memoisation hook
|
|
44
|
+
// can be reintroduced if that turns into a measurable cost.
|
|
45
|
+
if (!ctx.isImportValidatedAtLoad(resolvedUrl)) {
|
|
46
|
+
const analysisManifests = await ctx.loadManifests(resolvedUrl);
|
|
48
47
|
const diagnostics = new StaticAnalyzer().analyze(analysisManifests);
|
|
49
|
-
errors = diagnostics
|
|
48
|
+
const errors = diagnostics
|
|
50
49
|
.filter((d) => d.severity === DiagnosticSeverity.Error)
|
|
51
50
|
.map((d) => d.message);
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
errors.join("\n"),
|
|
59
|
-
);
|
|
51
|
+
if (errors.length > 0) {
|
|
52
|
+
throw new RuntimeError(
|
|
53
|
+
"ERR_MANIFEST_VALIDATION_FAILED",
|
|
54
|
+
errors.join("\n"),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
60
57
|
}
|
|
61
58
|
|
|
62
59
|
// Load target module manifests for runtime. Inject variables/secrets as compile context so
|
|
@@ -18,6 +18,7 @@ type ResourceDefinitionResource = RuntimeResource & {
|
|
|
18
18
|
schema: Record<string, any>;
|
|
19
19
|
capability?: string;
|
|
20
20
|
controllers?: Array<string>;
|
|
21
|
+
provide?: unknown;
|
|
21
22
|
};
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -31,6 +32,11 @@ class ResourceDefinition implements ResourceInstance {
|
|
|
31
32
|
|
|
32
33
|
async init(ctx: ResourceContext) {
|
|
33
34
|
if (!this.resource.controllers?.length) {
|
|
35
|
+
if (this.resource.capability === "Telo.Provider" && this.resource.provide == null) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Telo.Definition '${this.resource.metadata.name}': 'capability: Telo.Provider' requires either 'controllers:' (TS-backed) or 'provide:' (template-backed).`,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
34
40
|
const controllerInstance = createTemplateController(this.resource as any);
|
|
35
41
|
ctx.registerDefinition(this.resource);
|
|
36
42
|
await ctx.registerController(
|
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
import type { ControllerInstance, ResourceContext, ResourceInstance } from "@telorun/sdk";
|
|
2
2
|
import { isCompiledValue } from "@telorun/sdk";
|
|
3
3
|
|
|
4
|
+
/** Reports the resources: entries available to dispatch against, by expanded
|
|
5
|
+
* name and kind. Used in error messages to guide the developer back to the
|
|
6
|
+
* template's `resources:` array when a dispatch target doesn't match. */
|
|
7
|
+
function describeAvailableTargets(
|
|
8
|
+
ctx: ResourceContext,
|
|
9
|
+
resources: any[] | undefined,
|
|
10
|
+
self: Record<string, unknown>,
|
|
11
|
+
): string {
|
|
12
|
+
if (!resources || resources.length === 0) return "<none>";
|
|
13
|
+
return resources
|
|
14
|
+
.map((r) => {
|
|
15
|
+
const expanded = ctx.moduleContext.expandWith(r?.metadata?.name ?? "", { self }) as string;
|
|
16
|
+
const kind = typeof r?.kind === "string" ? r.kind : "<unknown-kind>";
|
|
17
|
+
return `'${expanded || "<unnamed>"}' (${kind})`;
|
|
18
|
+
})
|
|
19
|
+
.join(", ");
|
|
20
|
+
}
|
|
21
|
+
|
|
4
22
|
export function createTemplateController(definition: {
|
|
5
23
|
schema: Record<string, any>;
|
|
6
24
|
resources?: any[];
|
|
7
25
|
invoke?: string | { kind?: string; name: string };
|
|
8
26
|
inputs?: Record<string, any>;
|
|
9
27
|
run?: string;
|
|
28
|
+
provide?: { kind: string; name: string };
|
|
29
|
+
result?: Record<string, any>;
|
|
10
30
|
}): ControllerInstance {
|
|
11
31
|
return {
|
|
12
32
|
schema: definition.schema ?? { type: "object", additionalProperties: true },
|
|
@@ -32,6 +52,9 @@ export function createTemplateController(definition: {
|
|
|
32
52
|
const runTarget = definition.run
|
|
33
53
|
? (ctx.moduleContext.expandWith(definition.run, { self }) as string)
|
|
34
54
|
: null;
|
|
55
|
+
const provideTarget = definition.provide?.name
|
|
56
|
+
? (ctx.moduleContext.expandWith(definition.provide.name, { self }) as string)
|
|
57
|
+
: null;
|
|
35
58
|
|
|
36
59
|
const persistentManifests: any[] = [];
|
|
37
60
|
let ephemeralTemplate: any = null;
|
|
@@ -40,7 +63,10 @@ export function createTemplateController(definition: {
|
|
|
40
63
|
const expandedName = ctx.moduleContext.expandWith(template.metadata?.name ?? "", {
|
|
41
64
|
self,
|
|
42
65
|
}) as string;
|
|
43
|
-
const isTarget =
|
|
66
|
+
const isTarget =
|
|
67
|
+
expandedName === invokeTarget ||
|
|
68
|
+
expandedName === runTarget ||
|
|
69
|
+
expandedName === provideTarget;
|
|
44
70
|
if (isTarget) {
|
|
45
71
|
ephemeralTemplate = template;
|
|
46
72
|
} else {
|
|
@@ -84,7 +110,8 @@ export function createTemplateController(definition: {
|
|
|
84
110
|
invoke: async (inputs: any) => {
|
|
85
111
|
if (!ephemeralTemplate) {
|
|
86
112
|
throw new Error(
|
|
87
|
-
`Template '${resource.metadata.name}':
|
|
113
|
+
`Template '${resource.metadata.name}': 'invoke:' targets '${invokeTarget}' ` +
|
|
114
|
+
`but no entry in 'resources:' has that metadata.name. Available: ${describeAvailableTargets(ctx, definition.resources, self)}.`,
|
|
88
115
|
);
|
|
89
116
|
}
|
|
90
117
|
const extraContext = { self, inputs };
|
|
@@ -95,7 +122,13 @@ export function createTemplateController(definition: {
|
|
|
95
122
|
return withEphemeral(expanded, async (name) => {
|
|
96
123
|
const entry = ctx.moduleContext.resourceInstances.get(name);
|
|
97
124
|
if (!entry?.instance?.invoke) {
|
|
98
|
-
|
|
125
|
+
const targetKind = (entry?.resource?.kind ?? expanded?.kind ?? "<unknown-kind>") as string;
|
|
126
|
+
const targetDef = ctx.moduleContext.getDefinition?.(targetKind);
|
|
127
|
+
const actualCap = typeof targetDef?.capability === "string" ? targetDef.capability : "<unknown>";
|
|
128
|
+
throw new Error(
|
|
129
|
+
`Template '${resource.metadata.name}': 'invoke:' target '${targetKind}/${invokeTarget}' ` +
|
|
130
|
+
`has capability '${actualCap}', not Telo.Invocable. Update 'invoke:' to a Telo.Invocable kind, or change the target's kind in 'resources:'.`,
|
|
131
|
+
);
|
|
99
132
|
}
|
|
100
133
|
// Top-level `inputs:` (sibling of `invoke:`) carries the values passed
|
|
101
134
|
// to the dispatch target's invoke(). When absent, fall back to the
|
|
@@ -108,7 +141,13 @@ export function createTemplateController(definition: {
|
|
|
108
141
|
extraContext,
|
|
109
142
|
)
|
|
110
143
|
: expanded.inputs ?? inputs;
|
|
111
|
-
|
|
144
|
+
const raw = await entry.instance.invoke(invokeInputs);
|
|
145
|
+
if (definition.result == null) return raw;
|
|
146
|
+
const resultContext = { self, result: raw };
|
|
147
|
+
return ctx.moduleContext.expandWith(
|
|
148
|
+
ctx.moduleContext.expandWith(definition.result, resultContext),
|
|
149
|
+
resultContext,
|
|
150
|
+
);
|
|
112
151
|
});
|
|
113
152
|
},
|
|
114
153
|
}),
|
|
@@ -117,24 +156,73 @@ export function createTemplateController(definition: {
|
|
|
117
156
|
run: async () => {
|
|
118
157
|
if (!ephemeralTemplate) {
|
|
119
158
|
throw new Error(
|
|
120
|
-
`Template '${resource.metadata.name}':
|
|
159
|
+
`Template '${resource.metadata.name}': 'run:' targets '${runTarget}' ` +
|
|
160
|
+
`but no entry in 'resources:' has that metadata.name. Available: ${describeAvailableTargets(ctx, definition.resources, self)}.`,
|
|
121
161
|
);
|
|
122
162
|
}
|
|
123
163
|
const extraContext = { self };
|
|
124
164
|
const expanded = ctx.moduleContext.expandWith(
|
|
125
165
|
ctx.moduleContext.expandWith(ephemeralTemplate, extraContext),
|
|
126
166
|
extraContext,
|
|
127
|
-
);
|
|
167
|
+
) as any;
|
|
128
168
|
return withEphemeral(expanded, async (name) => {
|
|
129
169
|
const entry = ctx.moduleContext.resourceInstances.get(name);
|
|
130
170
|
if (!entry?.instance?.run) {
|
|
131
|
-
|
|
171
|
+
const targetKind = (entry?.resource?.kind ?? expanded?.kind ?? "<unknown-kind>") as string;
|
|
172
|
+
const targetDef = ctx.moduleContext.getDefinition?.(targetKind);
|
|
173
|
+
const actualCap = typeof targetDef?.capability === "string" ? targetDef.capability : "<unknown>";
|
|
174
|
+
throw new Error(
|
|
175
|
+
`Template '${resource.metadata.name}': 'run:' target '${targetKind}/${runTarget}' ` +
|
|
176
|
+
`has capability '${actualCap}', not Telo.Runnable. Update 'run:' to a Telo.Runnable kind, or change the target's kind in 'resources:'.`,
|
|
177
|
+
);
|
|
132
178
|
}
|
|
133
179
|
return entry.instance.run();
|
|
134
180
|
});
|
|
135
181
|
},
|
|
136
182
|
}),
|
|
137
183
|
|
|
184
|
+
...(provideTarget && {
|
|
185
|
+
provide: async () => {
|
|
186
|
+
if (!ephemeralTemplate) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`Template '${resource.metadata.name}': 'provide:' targets '${provideTarget}' ` +
|
|
189
|
+
`but no entry in 'resources:' has that metadata.name. Available: ${describeAvailableTargets(ctx, definition.resources, self)}.`,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
const extraContext = { self };
|
|
193
|
+
const expanded = ctx.moduleContext.expandWith(
|
|
194
|
+
ctx.moduleContext.expandWith(ephemeralTemplate, extraContext),
|
|
195
|
+
extraContext,
|
|
196
|
+
) as any;
|
|
197
|
+
return withEphemeral(expanded, async (name) => {
|
|
198
|
+
const entry = ctx.moduleContext.resourceInstances.get(name);
|
|
199
|
+
if (!entry?.instance?.invoke) {
|
|
200
|
+
const targetKind = (entry?.resource?.kind ?? expanded?.kind ?? "<unknown-kind>") as string;
|
|
201
|
+
const targetDef = ctx.moduleContext.getDefinition?.(targetKind);
|
|
202
|
+
const actualCap = typeof targetDef?.capability === "string" ? targetDef.capability : "<unknown>";
|
|
203
|
+
throw new Error(
|
|
204
|
+
`Template '${resource.metadata.name}': 'provide:' target '${targetKind}/${provideTarget}' ` +
|
|
205
|
+
`has capability '${actualCap}', not Telo.Invocable. Update 'provide:' to a Telo.Invocable kind, or change the target's kind in 'resources:'.`,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
const provideInputs: any =
|
|
209
|
+
definition.inputs != null
|
|
210
|
+
? ctx.moduleContext.expandWith(
|
|
211
|
+
ctx.moduleContext.expandWith(definition.inputs, extraContext),
|
|
212
|
+
extraContext,
|
|
213
|
+
)
|
|
214
|
+
: {};
|
|
215
|
+
const raw = await entry.instance.invoke(provideInputs);
|
|
216
|
+
if (definition.result == null) return raw;
|
|
217
|
+
const resultContext = { self, result: raw };
|
|
218
|
+
return ctx.moduleContext.expandWith(
|
|
219
|
+
ctx.moduleContext.expandWith(definition.result, resultContext),
|
|
220
|
+
resultContext,
|
|
221
|
+
);
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
}),
|
|
225
|
+
|
|
138
226
|
teardown: async () => {
|
|
139
227
|
await childContext.teardownResources();
|
|
140
228
|
},
|