@olivervea/pipelines 0.0.0-stage → 2.0.0-beta.10
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 +21 -0
- package/README.md +467 -2
- package/manifest.schema.json +674 -0
- package/package.json +60 -4
- package/src/assets.d.ts +10 -0
- package/src/build/build.ts +127 -0
- package/src/build/cli.ts +52 -0
- package/src/build/elf.ts +35 -0
- package/src/build/hashes.ts +96 -0
- package/src/build/project.ts +107 -0
- package/src/builder/pipeline.ts +373 -0
- package/src/builder/refs.ts +26 -0
- package/src/core/brands.ts +15 -0
- package/src/core/config-refs.ts +77 -0
- package/src/core/config.ts +147 -0
- package/src/core/handlers.ts +50 -0
- package/src/core/models.ts +69 -0
- package/src/core/origin.ts +20 -0
- package/src/core/secrets.ts +13 -0
- package/src/core/steps.ts +138 -0
- package/src/core/types.ts +6 -0
- package/src/core/webhooks.ts +30 -0
- package/src/ctx/files.ts +161 -0
- package/src/ctx/index.ts +122 -0
- package/src/ctx/sh.ts +197 -0
- package/src/ctx/types.ts +116 -0
- package/src/describe/describe.ts +565 -0
- package/src/describe/manifest-schema.ts +179 -0
- package/src/describe/mapper-source.ts +238 -0
- package/src/describe/record.ts +107 -0
- package/src/dev/cli.ts +87 -0
- package/src/harness/env.ts +58 -0
- package/src/harness/execute.ts +97 -0
- package/src/harness/exit.ts +19 -0
- package/src/harness/index.ts +9 -0
- package/src/harness/main.ts +270 -0
- package/src/harness/result.ts +75 -0
- package/src/harness/validate.ts +92 -0
- package/src/index.ts +15 -0
- package/src/library/checks.ts +23 -0
- package/src/library/compose-deploy.ts +96 -0
- package/src/library/github-source.ts +100 -0
- package/src/library/helm-deploy-ssh.ts +358 -0
- package/src/library/helm-deploy.ts +271 -0
- package/src/library/http-health.ts +34 -0
- package/src/library/image-build.ts +418 -0
- package/src/library/index.ts +18 -0
- package/src/library/models.ts +79 -0
- package/src/library/ssh.ts +50 -0
- package/src/testing/index.ts +82 -0
- package/src/util/canonical.ts +19 -0
- package/src/util/handler-hash.ts +22 -0
- package/src/util/hash.ts +22 -0
- package/src/util/tar.ts +167 -0
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@olivervea/pipelines",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0-beta.10",
|
|
4
|
+
"description": "Olve.Pipelines v2 SDK: typed pipeline authoring, the step harness, and the build tool.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Oliver Vea",
|
|
8
|
+
"homepage": "https://github.com/OliverVea/Olve.Pipelines/tree/v2/sdk#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/OliverVea/Olve.Pipelines.git",
|
|
12
|
+
"directory": "sdk"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/OliverVea/Olve.Pipelines/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"pipelines",
|
|
19
|
+
"cd",
|
|
20
|
+
"gitops",
|
|
21
|
+
"kubernetes",
|
|
22
|
+
"bun"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"bun": ">=1.4.3"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./src/index.ts",
|
|
29
|
+
"./harness": "./src/harness/index.ts",
|
|
30
|
+
"./testing": "./src/testing/index.ts",
|
|
31
|
+
"./assets": "./src/assets.d.ts",
|
|
32
|
+
"./manifest.schema.json": "./manifest.schema.json"
|
|
33
|
+
},
|
|
34
|
+
"bin": {
|
|
35
|
+
"olve-build": "./src/build/cli.ts",
|
|
36
|
+
"olve-dev": "./src/dev/cli.ts"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"src",
|
|
40
|
+
"manifest.schema.json",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public",
|
|
46
|
+
"tag": "beta"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"typecheck": "tsc --noEmit -p .",
|
|
50
|
+
"test": "bun test",
|
|
51
|
+
"check-compile-fail": "bun scripts/check-compile-fail.ts",
|
|
52
|
+
"gen-schema": "bun scripts/gen-manifest-schema.ts",
|
|
53
|
+
"check": "tsc --noEmit -p . && bun scripts/check-compile-fail.ts && bun test"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"zod": "4.6.7"
|
|
57
|
+
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"@types/bun": "1.4.3",
|
|
60
|
+
"typescript": "7.0.2"
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/assets.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// `import script from "./scripts/x.sh" with { type: "file" }` yields a path string
|
|
2
|
+
// (inside the compiled binary it points into the embedded /$bunfs filesystem).
|
|
3
|
+
declare module "*.sh" {
|
|
4
|
+
const path: string;
|
|
5
|
+
export default path;
|
|
6
|
+
}
|
|
7
|
+
declare module "*.bash" {
|
|
8
|
+
const path: string;
|
|
9
|
+
export default path;
|
|
10
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// olve-build: pipeline dir → single executable + step.tar.zst + manifest.json.
|
|
2
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { canonicalJson } from "../util/canonical.ts";
|
|
5
|
+
import { sha256File } from "../util/hash.ts";
|
|
6
|
+
import type { HarnessInfo } from "../util/handler-hash.ts";
|
|
7
|
+
import { writeTarZst } from "../util/tar.ts";
|
|
8
|
+
import { MANIFEST_BEGIN, MANIFEST_END, uploadFile } from "../harness/result.ts";
|
|
9
|
+
import { GLIBC_INTERP, MUSL_INTERP, readInterpreter } from "./elf.ts";
|
|
10
|
+
import { handlerHashes, kindHashes, type HandlerHash } from "./hashes.ts";
|
|
11
|
+
import { harnessInfo, loadPipeline, loadProject, relPosix, type Project } from "./project.ts";
|
|
12
|
+
|
|
13
|
+
export const BUILD_FLAGS = ["--no-compile-autoload-dotenv", "--no-compile-autoload-bunfig", "--bytecode", "--format=esm"] as const;
|
|
14
|
+
export type Target = "bun-linux-x64" | "bun-linux-x64-musl";
|
|
15
|
+
|
|
16
|
+
export class BuildError extends Error {
|
|
17
|
+
override name = "BuildError";
|
|
18
|
+
constructor(message: string, readonly exitCode = 1) {
|
|
19
|
+
super(message);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface BuildOptions {
|
|
24
|
+
out: string;
|
|
25
|
+
target?: Target;
|
|
26
|
+
/** Pre-signed PUT for the step archive. */
|
|
27
|
+
uploadUrl?: string;
|
|
28
|
+
/** Print the manifest between sentinels on stdout (for the build Job's pod log). */
|
|
29
|
+
sentinels?: boolean;
|
|
30
|
+
log?: (line: string) => void;
|
|
31
|
+
stdout?: (text: string) => Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface BuildResult {
|
|
35
|
+
binary: string;
|
|
36
|
+
archive: string;
|
|
37
|
+
manifestFile: string;
|
|
38
|
+
manifest: string;
|
|
39
|
+
hashes: Record<string, HandlerHash>;
|
|
40
|
+
harness: HarnessInfo;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Writes `<dir>/.olve/gen/{handlers,entry}.ts`: the literal-import handler registry + binary entry. */
|
|
44
|
+
export function generateEntry(project: Project, hashes: Record<string, string>, harness: HarnessInfo, kinds: Record<string, string> = {}): string {
|
|
45
|
+
const gen = join(project.dir, ".olve", "gen");
|
|
46
|
+
mkdirSync(gen, { recursive: true });
|
|
47
|
+
const registry = project.handlers.map(([name, file]) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(relPosix(gen, file))}),`).join("\n");
|
|
48
|
+
writeFileSync(
|
|
49
|
+
join(gen, "handlers.ts"),
|
|
50
|
+
`// GENERATED by olve-build — do not edit.\n` +
|
|
51
|
+
`import type { HandlerRegistry, HarnessInfo } from "@olivervea/pipelines/harness";\n\n` +
|
|
52
|
+
`export const handlers: HandlerRegistry = {\n${registry}\n};\n\n` +
|
|
53
|
+
`export const handlerHashes: Record<string, string> = ${JSON.stringify(hashes, null, 2)};\n\n` +
|
|
54
|
+
`export const kindHashes: Record<string, string> = ${JSON.stringify(kinds, null, 2)};\n\n` +
|
|
55
|
+
`export const harness: HarnessInfo = ${JSON.stringify(harness, null, 2)};\n`,
|
|
56
|
+
);
|
|
57
|
+
const entry = join(gen, "entry.ts");
|
|
58
|
+
writeFileSync(
|
|
59
|
+
entry,
|
|
60
|
+
`// GENERATED by olve-build — do not edit. Entry point of the step binary.\n` +
|
|
61
|
+
`import pipeline from ${JSON.stringify(relPosix(gen, project.pipelineFile))};\n` +
|
|
62
|
+
`import { runHarness } from "@olivervea/pipelines/harness";\n` +
|
|
63
|
+
`import { handlers, handlerHashes, kindHashes, harness } from "./handlers.ts";\n\n` +
|
|
64
|
+
`process.exit(await runHarness({ pipeline, handlers, handlerHashes, kindHashes, harness }, process.argv.slice(2)));\n`,
|
|
65
|
+
);
|
|
66
|
+
return entry;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function build(dir: string, opts: BuildOptions): Promise<BuildResult> {
|
|
70
|
+
const log = opts.log ?? ((l: string) => process.stderr.write(l + "\n"));
|
|
71
|
+
const stdout = opts.stdout ?? (async (t: string) => void (await Bun.write(Bun.stdout, t)));
|
|
72
|
+
const target = opts.target ?? "bun-linux-x64";
|
|
73
|
+
const project = await loadProject(dir);
|
|
74
|
+
const out = resolve(opts.out);
|
|
75
|
+
mkdirSync(out, { recursive: true });
|
|
76
|
+
const harness = harnessInfo();
|
|
77
|
+
|
|
78
|
+
const t0 = performance.now();
|
|
79
|
+
const hashes = await handlerHashes(project, harness);
|
|
80
|
+
const kinds = await kindHashes(project, await loadPipeline(project));
|
|
81
|
+
const entry = generateEntry(project, Object.fromEntries(Object.entries(hashes).map(([k, v]) => [k, v.handlerHash])), harness, kinds);
|
|
82
|
+
log(`olve-build: ${project.handlers.length} handler(s) hashed in ${((performance.now() - t0) / 1000).toFixed(2)}s`);
|
|
83
|
+
|
|
84
|
+
// 1. compile
|
|
85
|
+
const binary = join(out, "step");
|
|
86
|
+
rmSync(binary, { force: true });
|
|
87
|
+
const t1 = performance.now();
|
|
88
|
+
const p = Bun.spawnSync([process.execPath, "build", "--compile", `--target=${target}`, ...BUILD_FLAGS, entry, `--outfile=${binary}`], {
|
|
89
|
+
cwd: project.dir,
|
|
90
|
+
stdout: "pipe",
|
|
91
|
+
stderr: "pipe",
|
|
92
|
+
env: { ...process.env, NO_COLOR: "1" },
|
|
93
|
+
});
|
|
94
|
+
if (p.exitCode !== 0 || !existsSync(binary))
|
|
95
|
+
throw new BuildError(`bun build --compile failed (exit ${p.exitCode}):\n${p.stdout.toString()}${p.stderr.toString()}`);
|
|
96
|
+
log(`olve-build: compiled ${target} in ${((performance.now() - t1) / 1000).toFixed(2)}s`);
|
|
97
|
+
|
|
98
|
+
// 2. loader check: the harness launches the binary through /olve/lib/<loader>; a musl binary
|
|
99
|
+
// (e.g. compiled on alpine, where bun-linux-x64 silently yields musl) would not start.
|
|
100
|
+
const expected = target === "bun-linux-x64" ? GLIBC_INTERP : MUSL_INTERP;
|
|
101
|
+
const interp = readInterpreter(binary);
|
|
102
|
+
if (interp !== expected)
|
|
103
|
+
throw new BuildError(`compiled binary has PT_INTERP ${interp ?? "(none)"}, expected ${expected} — compile on a glibc Bun image (oven/bun:<version>-slim), not alpine`);
|
|
104
|
+
|
|
105
|
+
// 3. describe (runs the real binary: the manifest is exactly what the step pods will see)
|
|
106
|
+
const d = Bun.spawnSync([binary, "describe"], { cwd: out, stdout: "pipe", stderr: "pipe", env: { PATH: process.env.PATH ?? "/usr/bin:/bin" } });
|
|
107
|
+
if (d.exitCode !== 0) throw new BuildError(`describe failed (exit ${d.exitCode}):\n${d.stderr.toString()}`, d.exitCode ?? 1);
|
|
108
|
+
const manifest = d.stdout.toString();
|
|
109
|
+
const manifestFile = join(out, "manifest.json");
|
|
110
|
+
writeFileSync(manifestFile, manifest);
|
|
111
|
+
|
|
112
|
+
// 4. step.tar.zst (deterministic: `step` at the root, 0755, mtime 0)
|
|
113
|
+
const archive = join(out, "step.tar.zst");
|
|
114
|
+
await writeTarZst(archive, [{ path: "step", type: "file", mode: 0o755, source: binary }]);
|
|
115
|
+
writeFileSync(
|
|
116
|
+
join(out, "build.json"),
|
|
117
|
+
canonicalJson({ target, flags: BUILD_FLAGS, harness, handlers: hashes, kinds, binarySha256: sha256File(binary), archiveSha256: sha256File(archive) }),
|
|
118
|
+
);
|
|
119
|
+
log(`olve-build: wrote ${archive}`);
|
|
120
|
+
|
|
121
|
+
if (opts.uploadUrl) {
|
|
122
|
+
await uploadFile(opts.uploadUrl, archive, log);
|
|
123
|
+
log("olve-build: uploaded step.tar.zst");
|
|
124
|
+
}
|
|
125
|
+
if (opts.sentinels) await stdout(`${MANIFEST_BEGIN}\n${manifest}${MANIFEST_END}\n`);
|
|
126
|
+
return { binary, archive, manifestFile, manifest, hashes, harness };
|
|
127
|
+
}
|
package/src/build/cli.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// olve-build <pipelineDir> --out <dir> [--target bun-linux-x64|bun-linux-x64-musl] [--upload-url <url>] [--sentinels] [--hash-only]
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { canonicalJson } from "../util/canonical.ts";
|
|
5
|
+
import { build, BuildError, type Target } from "./build.ts";
|
|
6
|
+
import { handlerHashes } from "./hashes.ts";
|
|
7
|
+
import { harnessInfo, loadProject, ProjectError } from "./project.ts";
|
|
8
|
+
|
|
9
|
+
const USAGE = "usage: olve-build <pipelineDir> --out <dir> [--target bun-linux-x64|bun-linux-x64-musl] [--upload-url <url>] [--sentinels]\n olve-build <pipelineDir> --hash-only";
|
|
10
|
+
|
|
11
|
+
async function main(): Promise<number> {
|
|
12
|
+
let parsed;
|
|
13
|
+
try {
|
|
14
|
+
parsed = parseArgs({
|
|
15
|
+
allowPositionals: true,
|
|
16
|
+
options: {
|
|
17
|
+
out: { type: "string" },
|
|
18
|
+
target: { type: "string" },
|
|
19
|
+
"upload-url": { type: "string" },
|
|
20
|
+
sentinels: { type: "boolean", default: false },
|
|
21
|
+
"hash-only": { type: "boolean", default: false },
|
|
22
|
+
help: { type: "boolean", short: "h", default: false },
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
} catch (e) {
|
|
26
|
+
console.error(`${(e as Error).message}\n${USAGE}`);
|
|
27
|
+
return 64;
|
|
28
|
+
}
|
|
29
|
+
const { values, positionals } = parsed;
|
|
30
|
+
if (values.help) return console.log(USAGE), 0;
|
|
31
|
+
if (positionals.length !== 1) return console.error(USAGE), 64;
|
|
32
|
+
const dir = positionals[0]!;
|
|
33
|
+
try {
|
|
34
|
+
if (values["hash-only"]) {
|
|
35
|
+
const h = await handlerHashes(await loadProject(dir), harnessInfo());
|
|
36
|
+
await Bun.write(Bun.stdout, canonicalJson({ harness: harnessInfo(), handlers: h }));
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
if (!values.out) return console.error(`--out is required\n${USAGE}`), 64;
|
|
40
|
+
const target = (values.target ?? "bun-linux-x64") as Target;
|
|
41
|
+
if (target !== "bun-linux-x64" && target !== "bun-linux-x64-musl") return console.error(`unsupported target ${target}`), 64;
|
|
42
|
+
await build(dir, { out: values.out, target, uploadUrl: values["upload-url"], sentinels: values.sentinels });
|
|
43
|
+
return 0;
|
|
44
|
+
} catch (e) {
|
|
45
|
+
if (e instanceof BuildError) return console.error(e.message), e.exitCode;
|
|
46
|
+
if (e instanceof ProjectError) return console.error(e.message), 78;
|
|
47
|
+
console.error((e as Error)?.stack ?? String(e));
|
|
48
|
+
return 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (import.meta.main) process.exit(await main());
|
package/src/build/elf.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
export const GLIBC_INTERP = "/lib64/ld-linux-x86-64.so.2";
|
|
4
|
+
export const MUSL_INTERP = "/lib/ld-musl-x86-64.so.1";
|
|
5
|
+
|
|
6
|
+
function read(fd: number, pos: number, len: number): Buffer {
|
|
7
|
+
const b = Buffer.alloc(len);
|
|
8
|
+
const n = readSync(fd, b, 0, len, pos);
|
|
9
|
+
if (n !== len) throw new Error("truncated ELF file");
|
|
10
|
+
return b;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** PT_INTERP of an x86-64 ELF executable, or null if it has none (static). */
|
|
14
|
+
export function readInterpreter(path: string): string | null {
|
|
15
|
+
const fd = openSync(path, "r");
|
|
16
|
+
try {
|
|
17
|
+
const h = read(fd, 0, 64);
|
|
18
|
+
if (h.readUInt32BE(0) !== 0x7f454c46) throw new Error(`${path} is not an ELF file`);
|
|
19
|
+
if (h[4] !== 2 || h[5] !== 1) throw new Error(`${path} is not a 64-bit little-endian ELF file`);
|
|
20
|
+
const phoff = Number(h.readBigUInt64LE(0x20));
|
|
21
|
+
const phentsize = h.readUInt16LE(0x36);
|
|
22
|
+
const phnum = h.readUInt16LE(0x38);
|
|
23
|
+
for (let i = 0; i < phnum; i++) {
|
|
24
|
+
const ph = read(fd, phoff + i * phentsize, phentsize);
|
|
25
|
+
if (ph.readUInt32LE(0) === 3 /* PT_INTERP */) {
|
|
26
|
+
const off = Number(ph.readBigUInt64LE(0x08));
|
|
27
|
+
const size = Number(ph.readBigUInt64LE(0x20));
|
|
28
|
+
return read(fd, off, size).toString("latin1").replace(/\0+$/, "");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
} finally {
|
|
33
|
+
closeSync(fd);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Per-handler hashes: bundle each handler on its own with the contract files and the SDK external
|
|
2
|
+
// (tree-shaken → function-level granularity; embedded scripts are bundle outputs too), then hash the
|
|
3
|
+
// outputs. Contract changes are versioned through the manifest's model/step entries, SDK changes
|
|
4
|
+
// through `harness`; both are combined in composeHandlerHash.
|
|
5
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
6
|
+
import type { BunPlugin } from "bun";
|
|
7
|
+
import { isImplementation } from "../core/handlers.ts";
|
|
8
|
+
import { originsOf } from "../core/origin.ts";
|
|
9
|
+
import { pipelineData } from "../builder/pipeline.ts";
|
|
10
|
+
import { allSteps } from "../harness/main.ts";
|
|
11
|
+
import { composeHandlerHash, type HarnessInfo } from "../util/handler-hash.ts";
|
|
12
|
+
import { sha256Hex } from "../util/hash.ts";
|
|
13
|
+
import type { Project } from "./project.ts";
|
|
14
|
+
|
|
15
|
+
export interface HandlerHash {
|
|
16
|
+
/** Hash of the bundle outputs alone. */
|
|
17
|
+
bundleHash: string;
|
|
18
|
+
/** composeHandlerHash(bundleHash, harness) — what the manifest carries. */
|
|
19
|
+
handlerHash: string;
|
|
20
|
+
/** Bundle output names (for diagnostics). */
|
|
21
|
+
outputs: string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function externals(project: Project): BunPlugin {
|
|
25
|
+
const contracts = new Set(project.contractFiles);
|
|
26
|
+
return {
|
|
27
|
+
name: "olve-handler-hash-externals",
|
|
28
|
+
setup(b) {
|
|
29
|
+
b.onResolve({ filter: /^@olivervea\/pipelines(\/.*)?$/ }, (args) => ({ path: args.path, external: true }));
|
|
30
|
+
b.onResolve({ filter: /^\.{1,2}\// }, (args) => {
|
|
31
|
+
const base = resolve(dirname(args.importer), args.path);
|
|
32
|
+
for (const cand of [base, `${base}.ts`, join(base, "index.ts")]) if (contracts.has(cand)) return { path: args.path, external: true };
|
|
33
|
+
return undefined;
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function bundleHash(project: Project, entry: string): Promise<{ hash: string; outputs: string[] }> {
|
|
40
|
+
const inside = !relative(project.dir, entry).startsWith("..");
|
|
41
|
+
const r = await Bun.build({
|
|
42
|
+
entrypoints: [entry],
|
|
43
|
+
target: "bun",
|
|
44
|
+
format: "esm",
|
|
45
|
+
root: inside ? project.dir : dirname(entry),
|
|
46
|
+
naming: { entry: "[dir]/[name].[ext]", chunk: "[dir]/[name].[ext]", asset: "[dir]/[name].[ext]" },
|
|
47
|
+
plugins: [externals(project)],
|
|
48
|
+
throw: false,
|
|
49
|
+
});
|
|
50
|
+
if (!r.success) throw new AggregateError(r.logs, `bundling ${entry} failed:\n${r.logs.map(String).join("\n")}`);
|
|
51
|
+
const parts: string[] = [];
|
|
52
|
+
const outputs: string[] = [];
|
|
53
|
+
for (const o of [...r.outputs].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
|
|
54
|
+
const name = o.path.replace(/^\.\//, "");
|
|
55
|
+
outputs.push(name);
|
|
56
|
+
const bytes = new Uint8Array(await o.arrayBuffer());
|
|
57
|
+
// Bun prefixes each module with a `// <path>` comment relative to the *process cwd*; drop those
|
|
58
|
+
// so the hash depends only on code, not on where the repo or the build tool runs.
|
|
59
|
+
const content = name.endsWith(".js") ? new TextDecoder().decode(bytes).replace(/^\/\/ \S+\n/gm, "") : bytes;
|
|
60
|
+
parts.push(`${name}\0${sha256Hex(content)}`);
|
|
61
|
+
}
|
|
62
|
+
return { hash: "sha256:" + sha256Hex(parts.join("\n")), outputs };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function handlerHashes(project: Project, harness: HarnessInfo): Promise<Record<string, HandlerHash>> {
|
|
66
|
+
const out: Record<string, HandlerHash> = {};
|
|
67
|
+
for (const [name, file] of project.handlers) {
|
|
68
|
+
const b = await bundleHash(project, file);
|
|
69
|
+
out[name] = { bundleHash: b.hash, handlerHash: composeHandlerHash(b.hash, harness), outputs: b.outputs };
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Kind → hash of the modules that implement the steps of that kind which carry their implementation
|
|
76
|
+
* (each module bundled like a handler: the SDK and contract files external).
|
|
77
|
+
*/
|
|
78
|
+
export async function kindHashes(project: Project, pipeline: unknown): Promise<Record<string, string>> {
|
|
79
|
+
const origins = new Map<string, Set<string>>();
|
|
80
|
+
for (const s of allSteps(pipelineData(pipeline))) {
|
|
81
|
+
if (!isImplementation(s)) continue;
|
|
82
|
+
const files = originsOf(s).filter((f) => !project.contractFiles.includes(f));
|
|
83
|
+
if (files.length === 0)
|
|
84
|
+
throw new Error(`step '${s.name}' carries its implementation but is defined in ${project.contractFiles.map((f) => relative(project.dir, f)).join(" or ")}; define and implement it in a module of its own (or a package)`);
|
|
85
|
+
const set = origins.get(s.kind) ?? new Set<string>();
|
|
86
|
+
for (const f of files) set.add(f);
|
|
87
|
+
origins.set(s.kind, set);
|
|
88
|
+
}
|
|
89
|
+
const out: Record<string, string> = {};
|
|
90
|
+
for (const [kind, files] of [...origins].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
91
|
+
const parts: string[] = [];
|
|
92
|
+
for (const f of [...files].sort()) parts.push((await bundleHash(project, f)).hash);
|
|
93
|
+
out[kind] = "sha256:" + sha256Hex(parts.join("\n"));
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Layout of a pipeline directory and the identity of the SDK building it.
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { isImplementation } from "../core/handlers.ts";
|
|
5
|
+
import { sha256Hex } from "../util/hash.ts";
|
|
6
|
+
import type { HarnessInfo } from "../util/handler-hash.ts";
|
|
7
|
+
|
|
8
|
+
export const SDK_ROOT = resolve(import.meta.dir, "../..");
|
|
9
|
+
|
|
10
|
+
export interface Project {
|
|
11
|
+
dir: string;
|
|
12
|
+
pipelineFile: string;
|
|
13
|
+
/** Contract files (excluded from handler bundles): pipeline.ts, models.ts. */
|
|
14
|
+
contractFiles: string[];
|
|
15
|
+
/** step name → absolute handler file, sorted by step name. The step is the one the file's `implement(step, …)` names. */
|
|
16
|
+
handlers: [string, string][];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class ProjectError extends Error {
|
|
20
|
+
override name = "ProjectError";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function loadProject(dirArg: string): Promise<Project> {
|
|
24
|
+
const dir = resolve(dirArg);
|
|
25
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new ProjectError(`${dirArg} is not a directory`);
|
|
26
|
+
const pipelineFile = join(dir, "pipeline.ts");
|
|
27
|
+
if (!existsSync(pipelineFile)) throw new ProjectError(`${join(dirArg, "pipeline.ts")} not found (it must default-export pipeline({...}))`);
|
|
28
|
+
const contractFiles = ["pipeline.ts", "models.ts"].map((f) => join(dir, f)).filter((f) => existsSync(f));
|
|
29
|
+
const hdir = join(dir, "handlers");
|
|
30
|
+
const files = existsSync(hdir)
|
|
31
|
+
? readdirSync(hdir)
|
|
32
|
+
.filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts") && !f.endsWith(".d.ts") && statSync(join(hdir, f)).isFile())
|
|
33
|
+
.sort()
|
|
34
|
+
: [];
|
|
35
|
+
return { dir, pipelineFile, contractFiles, handlers: await resolveHandlers(hdir, files) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The default export of pipeline.ts. */
|
|
39
|
+
export async function loadPipeline(project: Project): Promise<unknown> {
|
|
40
|
+
const mod = (await import(project.pipelineFile)) as { default?: unknown };
|
|
41
|
+
if (!mod.default) throw new ProjectError(`${project.pipelineFile} has no default export (export default pipeline({...})...)`);
|
|
42
|
+
return mod.default;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Pairs each handler file with the step its default export implements (file names don't matter). */
|
|
46
|
+
async function resolveHandlers(hdir: string, files: string[]): Promise<[string, string][]> {
|
|
47
|
+
const byStep = new Map<string, string>();
|
|
48
|
+
for (const f of files) {
|
|
49
|
+
const file = join(hdir, f);
|
|
50
|
+
let impl: unknown;
|
|
51
|
+
try {
|
|
52
|
+
impl = ((await import(file)) as { default?: unknown }).default;
|
|
53
|
+
} catch (e) {
|
|
54
|
+
throw new ProjectError(`handlers/${f} failed to load: ${(e as Error)?.message ?? String(e)}`);
|
|
55
|
+
}
|
|
56
|
+
if (!isImplementation(impl))
|
|
57
|
+
throw new ProjectError(`handlers/${f} must default-export implement(<step>, …); put shared code in a subfolder such as handlers/lib/`);
|
|
58
|
+
const step = (impl.step as { name: string }).name;
|
|
59
|
+
const other = byStep.get(step);
|
|
60
|
+
if (other) throw new ProjectError(`handlers/${other.slice(hdir.length + 1)} and handlers/${f} both implement step '${step}'`);
|
|
61
|
+
byStep.set(step, file);
|
|
62
|
+
}
|
|
63
|
+
return [...byStep].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function listFiles(dir: string): string[] {
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
69
|
+
const p = join(dir, e.name);
|
|
70
|
+
if (e.isDirectory()) out.push(...listFiles(p));
|
|
71
|
+
else if (e.isFile()) out.push(p);
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let cached: HarnessInfo | undefined;
|
|
77
|
+
/**
|
|
78
|
+
* Harness identity: Bun version, SDK version, and a hash over the SDK's runtime sources (src/,
|
|
79
|
+
* without the build and dev tools) plus the zod version the SDK resolves.
|
|
80
|
+
*/
|
|
81
|
+
export function harnessInfo(): HarnessInfo {
|
|
82
|
+
if (cached) return cached;
|
|
83
|
+
const pkg = JSON.parse(readFileSync(join(SDK_ROOT, "package.json"), "utf8")) as { version: string };
|
|
84
|
+
const src = join(SDK_ROOT, "src");
|
|
85
|
+
const files = listFiles(src)
|
|
86
|
+
.map((f) => relative(src, f).split("\\").join("/"))
|
|
87
|
+
.filter((f) => !f.startsWith("build/") && !f.startsWith("dev/") && !f.startsWith("testing/") && f.endsWith(".ts"))
|
|
88
|
+
.sort();
|
|
89
|
+
const h = new Bun.CryptoHasher("sha256");
|
|
90
|
+
for (const f of files) h.update(`${f}\0${sha256Hex(readFileSync(join(src, f)))}\n`);
|
|
91
|
+
let zodVersion = "unknown";
|
|
92
|
+
try {
|
|
93
|
+
const zodPkg = Bun.resolveSync("zod/package.json", SDK_ROOT);
|
|
94
|
+
zodVersion = (JSON.parse(readFileSync(zodPkg, "utf8")) as { version: string }).version;
|
|
95
|
+
} catch {
|
|
96
|
+
/* keep unknown */
|
|
97
|
+
}
|
|
98
|
+
h.update(`zod@${zodVersion}\n`);
|
|
99
|
+
cached = { bun: Bun.version, sdk: pkg.version, sdkHash: "sha256:" + h.digest("hex") };
|
|
100
|
+
return cached;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export const relPosix = (from: string, to: string) => {
|
|
104
|
+
const r = relative(from, to).split("\\").join("/");
|
|
105
|
+
return r.startsWith(".") ? r : `./${r}`;
|
|
106
|
+
};
|
|
107
|
+
export { dirname };
|