thunderjar 0.1.3-preview-eee7160 → 0.1.3-preview-e09ffa1

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 (81) hide show
  1. package/dist/cli.js +1934 -1721
  2. package/package.json +14 -8
  3. package/src/api/checkoutCommit.ts +35 -0
  4. package/src/api/claudeCode.ts +74 -0
  5. package/src/api/declarations.ts +176 -133
  6. package/src/api/index.ts +44 -0
  7. package/src/api/parameterNames.ts +19 -0
  8. package/src/AGENTS.md +0 -156
  9. package/src/adapters/docker/docker.ts +0 -117
  10. package/src/api/fragments.ts +0 -30
  11. package/src/api/parameter-names.d.ts +0 -16
  12. package/src/cli/commands/build/build.docker.test.ts +0 -173
  13. package/src/cli/commands/build/build.test.ts +0 -234
  14. package/src/cli/commands/build/build.ts +0 -115
  15. package/src/cli/commands/declarations.typecheck.test.ts +0 -173
  16. package/src/cli/commands/executions/executions.test.ts +0 -84
  17. package/src/cli/commands/executions/executions.ts +0 -31
  18. package/src/cli/commands/format.ts +0 -33
  19. package/src/cli/commands/generate/generate.test.ts +0 -101
  20. package/src/cli/commands/generate/generate.ts +0 -18
  21. package/src/cli/commands/generate/parameter-names.ts +0 -131
  22. package/src/cli/commands/init/init.test.ts +0 -123
  23. package/src/cli/commands/init/init.ts +0 -189
  24. package/src/cli/commands/options.ts +0 -17
  25. package/src/cli/commands/plan/plan.test.ts +0 -168
  26. package/src/cli/commands/plan/plan.ts +0 -72
  27. package/src/cli/commands/remeasure/remeasure.test.ts +0 -536
  28. package/src/cli/commands/remeasure/remeasure.ts +0 -194
  29. package/src/cli/commands/run/run.test.ts +0 -622
  30. package/src/cli/commands/run/run.ts +0 -203
  31. package/src/cli/commands/show/show.test.ts +0 -288
  32. package/src/cli/commands/show/show.ts +0 -252
  33. package/src/cli/commands/validation.test.ts +0 -200
  34. package/src/cli/index.test.ts +0 -47
  35. package/src/cli/index.ts +0 -9
  36. package/src/cli/program.ts +0 -29
  37. package/src/images/prerun-builds.ts +0 -108
  38. package/src/images/prerun.test.ts +0 -243
  39. package/src/images/prerun.ts +0 -272
  40. package/src/images/repository.ts +0 -72
  41. package/src/index.ts +0 -24
  42. package/src/instruments/instruments.test.ts +0 -240
  43. package/src/instruments/instruments.ts +0 -205
  44. package/src/matrix/execution.ts +0 -122
  45. package/src/matrix/hashing.test.ts +0 -298
  46. package/src/matrix/hashing.ts +0 -131
  47. package/src/matrix/permutations.test.ts +0 -58
  48. package/src/matrix/permutations.ts +0 -50
  49. package/src/matrix/resolve.ts +0 -63
  50. package/src/matrix/tags.test.ts +0 -15
  51. package/src/matrix/tags.ts +0 -22
  52. package/src/matrix/ulid.test.ts +0 -28
  53. package/src/matrix/ulid.ts +0 -22
  54. package/src/measuring/aggregate.test.ts +0 -188
  55. package/src/measuring/aggregate.ts +0 -154
  56. package/src/measuring/measure.test.ts +0 -105
  57. package/src/measuring/measure.ts +0 -62
  58. package/src/measuring/remeasure-templates/v1/isPrime.test.template.txt +0 -4
  59. package/src/measuring/remeasure-templates/v2/isPrime.test.template.txt +0 -5
  60. package/src/measuring/remeasure.test.ts +0 -352
  61. package/src/measuring/remeasure.ts +0 -113
  62. package/src/platform/fs.test.ts +0 -89
  63. package/src/platform/fs.ts +0 -123
  64. package/src/platform/path.test.ts +0 -38
  65. package/src/platform/path.ts +0 -72
  66. package/src/platform/signals.test.ts +0 -25
  67. package/src/platform/signals.ts +0 -68
  68. package/src/project/config.test.ts +0 -68
  69. package/src/project/config.ts +0 -297
  70. package/src/running/runner.test.ts +0 -73
  71. package/src/running/runner.ts +0 -252
  72. package/src/store/run-data-store.test.ts +0 -232
  73. package/src/store/run-data-store.ts +0 -254
  74. package/src/testing/cli.ts +0 -65
  75. package/src/testing/fake-docker.test.ts +0 -197
  76. package/src/testing/fake-docker.ts +0 -104
  77. package/src/testing/fixture-project.ts +0 -177
  78. package/src/testing/measurement-context.ts +0 -5
  79. package/src/testing/seed-repo.test.ts +0 -10
  80. package/src/testing/seed-repo.ts +0 -83
  81. package/src/testing/test-setup.ts +0 -10
@@ -1,33 +0,0 @@
1
- // How commands print things they share: counts, durations, measured values, times. A command
2
- // never imports another command; what two of them print alike lives here.
3
-
4
- import type { RecordedOutcome } from "../../store/run-data-store.ts";
5
-
6
- /** `1 permutation`, `2 permutations`. */
7
- export const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? "" : "s"}`;
8
-
9
- /** A measured value as `run` prints it: JSON, but with an object's keys unquoted, `{passed: 4, failed: 1}`. */
10
- export const showValue = (value: unknown): string =>
11
- typeof value === "object" && value !== null && !Array.isArray(value)
12
- ? `{${Object.entries(value)
13
- .map(([key, v]) => `${key}: ${showValue(v)}`)
14
- .join(", ")}}`
15
- : (JSON.stringify(value) ?? String(value));
16
-
17
- /** A measure as `run` and `remeasure` print it: its value, or what kept it from having one. */
18
- export const showOutcome = (outcome: RecordedOutcome) =>
19
- outcome.outcome === "measured"
20
- ? showValue(outcome.data)
21
- : outcome.outcome === "skipped"
22
- ? "skipped"
23
- : `erroredWhileMeasuring: ${outcome.error.message}`;
24
-
25
- /** Milliseconds as a duration: `0.04s`. */
26
- export const seconds = (ms: number) => `${(ms / 1000).toFixed(2)}s`;
27
-
28
- /** How long a container run took: `0.04s`. */
29
- export const duration = ({ startedAt, finishedAt }: { startedAt: number; finishedAt: number }) =>
30
- seconds(finishedAt - startedAt);
31
-
32
- /** `2026-09-29 14:30`, from an ISO timestamp. */
33
- export const minute = (iso: string) => iso.slice(0, 16).replace("T", " ");
@@ -1,101 +0,0 @@
1
- // `thunderjar generate`, through the CLI, in the checked-in fixtureTests/ scenarios, in place. It
2
- // writes only the gitignored `.thunderjar/_generated/parameter-names.d.ts`, so each test deletes
3
- // that file first, then asserts on what was written. Any of these can be run by hand:
4
- //
5
- // bun run fixture scenario_2 generate
6
-
7
- import { describe, expect, test } from "bun:test";
8
- import { remove } from "../../../platform/fs.ts";
9
- import { join } from "../../../platform/path.ts";
10
- import { scenario, thunderjar } from "../../../testing/cli.ts";
11
-
12
- /** Runs `generate` in `fixtures` with no earlier output left, returning its output and the file. */
13
- async function generateIn(fixtures: string) {
14
- const path = join(fixtures, ".thunderjar", "_generated", "parameter-names.d.ts");
15
- await remove(path);
16
- const result = await thunderjar(fixtures, ["generate"]);
17
- return { ...result, path, content: await Bun.file(path).text() };
18
- }
19
-
20
- describe("scenario_1_minimal_initial_setup", () => {
21
- const fixtures = scenario("scenario_1_minimal_initial_setup");
22
-
23
- test("generate: one of everything", async () => {
24
- const { stdout, stderr, exitCode, path, content } = await generateIn(fixtures);
25
-
26
- expect(stderr).toBe("");
27
- expect(exitCode).toBe(0);
28
- expect(stdout).toBe(`generated ${path}\n`);
29
- expect(content).toBe(`// _generated/parameter-names.d.ts — generated by \`thunderjar generate\`, not edited
30
-
31
- type BaseImageName = "node20";
32
- type CodeStateName = "baseline";
33
- type PromptSetName = "snerk";
34
- type TaskName = "is-prime";
35
- type InitialPromptNames = {
36
- "is-prime": "plain";
37
- };
38
- type HarnessModelName = \`fake-harness-alpha@\${"1.0.0"}/\${"fake-model-small"}\`;
39
- `);
40
- });
41
- });
42
-
43
- describe("scenario_2_typical_project", () => {
44
- const fixtures = scenario("scenario_2_typical_project");
45
-
46
- test("generate: sorted unions of every name, and a harness model pair per family", async () => {
47
- const { stdout, stderr, exitCode, path, content } = await generateIn(fixtures);
48
-
49
- expect(stderr).toBe("");
50
- expect(exitCode).toBe(0);
51
- expect(stdout).toBe(`generated ${path}\n`);
52
- expect(content).toBe(`// _generated/parameter-names.d.ts — generated by \`thunderjar generate\`, not edited
53
-
54
- type BaseImageName = "node-lts" | "node20";
55
- type CodeStateName = "baseline";
56
- type PromptSetName = "glurk" | "glurk-reworded" | "snerk";
57
- type TaskName = "is-prime" | "no-measures";
58
- type InitialPromptNames = {
59
- "is-prime": "plain" | "terse";
60
- "no-measures": "plain";
61
- };
62
- type HarnessModelName =
63
- | \`fake-harness-alpha@\${"1.0.0" | "1.1.0"}/\${"fake-model-large" | "fake-model-small"}\`
64
- | \`fake-harness-beta@\${"1.0.0"}/\${"fake-model-large" | "fake-model-small"}\`;
65
- `);
66
- });
67
-
68
- test("generate: from a folder below the project, writes into the project's .thunderjar/", async () => {
69
- const below = join(fixtures, ".thunderjar", "test-cases");
70
- const path = join(fixtures, ".thunderjar", "_generated", "parameter-names.d.ts");
71
- await remove(path);
72
-
73
- const { stdout, stderr, exitCode } = await thunderjar(below, ["generate"]);
74
-
75
- expect(stderr).toBe("");
76
- expect(exitCode).toBe(0);
77
- expect(stdout).toBe(`generated ${path}\n`);
78
- expect(await Bun.file(path).text()).toContain('type CodeStateName = "baseline";');
79
- });
80
- });
81
-
82
- describe("scenario_5_empty_parameter_folders", () => {
83
- const fixtures = scenario("scenario_5_empty_parameter_folders");
84
-
85
- test("generate: empty parameter folders render as never", async () => {
86
- const { stdout, stderr, exitCode, path, content } = await generateIn(fixtures);
87
-
88
- expect(stderr).toBe("");
89
- expect(exitCode).toBe(0);
90
- expect(stdout).toBe(`generated ${path}\n`);
91
- expect(content).toBe(`// _generated/parameter-names.d.ts — generated by \`thunderjar generate\`, not edited
92
-
93
- type BaseImageName = never;
94
- type CodeStateName = never;
95
- type PromptSetName = never;
96
- type TaskName = never;
97
- type InitialPromptNames = Record<string, never>;
98
- type HarnessModelName = never;
99
- `);
100
- });
101
- });
@@ -1,18 +0,0 @@
1
- // `thunderjar generate` — spec/100-cli-reference.md#generate.
2
-
3
- import { Command } from "commander";
4
- import { findThunderjarRoot } from "../../../project/config.ts";
5
- import { writeGeneratedTypes } from "./parameter-names.ts";
6
-
7
- export async function generate(cwd: string = process.cwd()): Promise<{ path: string }> {
8
- const root = findThunderjarRoot(cwd);
9
- const { path } = await writeGeneratedTypes(root);
10
- return { path };
11
- }
12
-
13
- export function createGenerateCommand(): Command {
14
- return new Command("generate").description("Write the parameter-name types for this project.").action(async () => {
15
- const { path } = await generate();
16
- console.log(`generated ${path}`);
17
- });
18
- }
@@ -1,131 +0,0 @@
1
- // Reads parameter names and harness family version/model maps under
2
- // `test-case-parameters/` and renders `_generated/parameter-names.d.ts` —
3
- // spec/055-declaring-test-cases.md#typed-names.
4
-
5
- import { listEntries } from "../../../platform/fs.ts";
6
- import { join } from "../../../platform/path.ts";
7
- import { InvalidConfigError, loadDeclaration, type Problem } from "../../../project/config.ts";
8
-
9
- interface HarnessFamilyNames {
10
- versions: string[];
11
- models: string[];
12
- }
13
-
14
- export interface ParameterNames {
15
- baseImages: string[];
16
- codeStates: string[];
17
- promptSets: string[];
18
- tasks: Record<string, string[]>; // task name -> initial prompt names
19
- harnessFamilies: Record<string, HarnessFamilyNames>;
20
- }
21
-
22
- async function listDirNames(dir: string): Promise<string[]> {
23
- try {
24
- return listEntries(dir)
25
- .filter((entry) => entry.isDirectory)
26
- .map((entry) => entry.path)
27
- .sort();
28
- } catch {
29
- return [];
30
- }
31
- }
32
-
33
- async function listFileStems(dir: string): Promise<string[]> {
34
- try {
35
- return listEntries(dir)
36
- .filter((entry) => !entry.isDirectory && entry.path.endsWith(".ts"))
37
- .map((entry) => entry.path.slice(0, -".ts".length))
38
- .sort();
39
- } catch {
40
- return [];
41
- }
42
- }
43
-
44
- async function loadFamilyNames(root: string, family: string, problems: Problem[]): Promise<HarnessFamilyNames> {
45
- const familyDir = `test-case-parameters/harnessModels/${family}`;
46
- const models = await loadDeclaration(root, `${familyDir}/models.ts`, "declareHarnessModels", problems);
47
- const versions = await loadDeclaration(root, `${familyDir}/versions.ts`, "declareHarnessVersions", problems);
48
- return {
49
- models: Object.keys(models ?? {}).sort(),
50
- versions: Object.keys(versions ?? {}).sort(),
51
- };
52
- }
53
-
54
- /** Scans a `.thunderjar/` root's `test-case-parameters/` folder for declared names. */
55
- export async function collectParameterNames(root: string): Promise<ParameterNames> {
56
- const parameters = join(root, "test-case-parameters");
57
-
58
- const [baseImages, codeStates, promptSets, taskNames, familyNames] = await Promise.all([
59
- listDirNames(join(parameters, "baseImages")),
60
- listDirNames(join(parameters, "codeStates")),
61
- listDirNames(join(parameters, "promptSets")),
62
- listDirNames(join(parameters, "tasks")),
63
- listDirNames(join(parameters, "harnessModels")),
64
- ]);
65
-
66
- const tasks: Record<string, string[]> = {};
67
- for (const task of taskNames) {
68
- tasks[task] = await listFileStems(join(parameters, "tasks", task, "initial-prompts"));
69
- }
70
-
71
- const harnessFamilies: Record<string, HarnessFamilyNames> = {};
72
- const problems: Problem[] = [];
73
- for (const family of familyNames) {
74
- harnessFamilies[family] = await loadFamilyNames(root, family, problems);
75
- }
76
- if (problems.length > 0) throw new InvalidConfigError(problems);
77
-
78
- return { baseImages, codeStates, promptSets, tasks, harnessFamilies };
79
- }
80
-
81
- function literalUnion(names: string[]): string {
82
- return names.length === 0 ? "never" : names.map((name) => JSON.stringify(name)).join(" | ");
83
- }
84
-
85
- /** Renders `_generated/parameter-names.d.ts`'s contents from scanned names. */
86
- export function renderParameterNames(names: ParameterNames): string {
87
- const lines = [
88
- "// _generated/parameter-names.d.ts — generated by `thunderjar generate`, not edited",
89
- "",
90
- `type BaseImageName = ${literalUnion(names.baseImages)};`,
91
- `type CodeStateName = ${literalUnion(names.codeStates)};`,
92
- `type PromptSetName = ${literalUnion(names.promptSets)};`,
93
- `type TaskName = ${literalUnion(Object.keys(names.tasks))};`,
94
- ];
95
-
96
- const tasks = Object.entries(names.tasks);
97
- if (tasks.length === 0) {
98
- lines.push("type InitialPromptNames = Record<string, never>;");
99
- } else {
100
- lines.push("type InitialPromptNames = {");
101
- for (const [task, prompts] of tasks) {
102
- lines.push(` ${JSON.stringify(task)}: ${literalUnion(prompts)};`);
103
- }
104
- lines.push("};");
105
- }
106
-
107
- const pairs = Object.entries(names.harnessFamilies)
108
- .filter(([, { versions, models }]) => versions.length > 0 && models.length > 0)
109
- .map(([family, { versions, models }]) => "`" + family + "@${" + literalUnion(versions) + "}/${" + literalUnion(models) + "}`");
110
- if (pairs.length === 0) {
111
- lines.push("type HarnessModelName = never;");
112
- } else if (pairs.length === 1) {
113
- lines.push(`type HarnessModelName = ${pairs[0]};`);
114
- } else {
115
- lines.push("type HarnessModelName =");
116
- lines.push(...pairs.map((pair) => ` | ${pair}`));
117
- lines[lines.length - 1] += ";";
118
- }
119
- lines.push("");
120
-
121
- return lines.join("\n");
122
- }
123
-
124
- /** Scans `root` and writes `_generated/parameter-names.d.ts`, returning its path. */
125
- export async function writeGeneratedTypes(root: string): Promise<{ path: string; content: string }> {
126
- const names = await collectParameterNames(root);
127
- const content = renderParameterNames(names);
128
- const path = join(root, "_generated", "parameter-names.d.ts");
129
- await Bun.write(path, content);
130
- return { path, content };
131
- }
@@ -1,123 +0,0 @@
1
- // `thunderjar init`, through the CLI, in a copy of a checked-in fixtureTests/ scenario, because it
2
- // writes into the project. Each test asserts on what it printed and the files it created or
3
- // skipped. Any of these can be run by hand, in a scratch copy of the scenario:
4
- //
5
- // cp -r fixtureTests/scenario_6_uninitialised_project/fixtures /tmp/s6 && cd /tmp/s6 && thunderjar init
6
-
7
- import { describe, expect, test } from "bun:test";
8
- import { listEntries } from "../../../platform/fs.ts";
9
- import { join } from "../../../platform/path.ts";
10
- import { copyOfFixtures, scenario, thunderjar } from "../../../testing/cli.ts";
11
-
12
- /** Every file under `.thunderjar/` in `dir`, sorted. */
13
- const filesIn = (dir: string) =>
14
- listEntries(join(dir, ".thunderjar"), { recursive: true })
15
- .filter((entry) => !entry.isDirectory)
16
- .map((entry) => entry.path)
17
- .toSorted();
18
-
19
- const read = (dir: string, rel: string) => Bun.file(join(dir, ".thunderjar", rel)).text();
20
-
21
- /** What `init` scaffolds in any project, in the order it prints them. */
22
- const SCAFFOLD = [
23
- "thunderjar.config.ts",
24
- "tsconfig.json",
25
- "test-cases/example.ts",
26
- "test-case-parameters/baseImages/node20/index.ts",
27
- "test-case-parameters/codeStates/baseline/index.ts",
28
- "test-case-parameters/promptSets/snerk/index.ts",
29
- "test-case-parameters/harnessModels/claude-code/index.ts",
30
- "test-case-parameters/harnessModels/claude-code/models.ts",
31
- "test-case-parameters/harnessModels/claude-code/versions.ts",
32
- "test-case-parameters/harnessModels/claude-code/collectTokenCosts.ts",
33
- "test-case-parameters/tasks/is-prime/initial-prompts/plain.ts",
34
- "test-case-parameters/tasks/is-prime/measurements/isPrimeTsExists.ts",
35
- ];
36
-
37
- describe("scenario_6_uninitialised_project", () => {
38
- const fixtures = scenario("scenario_6_uninitialised_project");
39
-
40
- test("init: scaffolds .thunderjar/, with a nested package.json and node_modules ignored", async () => {
41
- const dir = await copyOfFixtures(fixtures);
42
-
43
- const { stdout, stderr, exitCode } = await thunderjar(dir, ["init"]);
44
-
45
- expect(stderr).toBe("");
46
- expect(exitCode).toBe(0);
47
- const created = [...SCAFFOLD, "package.json", ".gitignore"];
48
- expect(stdout).toBe(created.map((f) => `created .thunderjar/${f}\n`).join(""));
49
- expect(filesIn(dir)).toEqual(created.toSorted());
50
- expect(await read(dir, ".gitignore")).toBe("_generated/\n.data/\nnode_modules/\n");
51
- expect(JSON.parse(await read(dir, "package.json"))).toEqual({
52
- name: "thunderjar-config",
53
- private: true,
54
- type: "module",
55
- dependencies: { thunderjar: "latest" },
56
- });
57
- expect(await read(dir, "thunderjar.config.ts")).toBe(`import { declareConfig, sqliteStore } from "thunderjar";
58
-
59
- export default declareConfig({
60
- imageStore: { repository: "ghcr.io/your-org/thunderjar-images" },
61
- runDataStore: sqliteStore({ path: "./.thunderjar/.data/runs.sqlite" }),
62
- });
63
- `);
64
- });
65
-
66
- test("init: every TypeScript file it scaffolds resolves its thunderjar imports", async () => {
67
- const dir = await copyOfFixtures(fixtures);
68
-
69
- await thunderjar(dir, ["init"]);
70
-
71
- for (const file of filesIn(dir).filter((f) => f.endsWith(".ts"))) {
72
- await import(join(dir, ".thunderjar", file));
73
- }
74
- });
75
- });
76
-
77
- describe("scenario_7_uninitialised_js_project", () => {
78
- const fixtures = scenario("scenario_7_uninitialised_js_project");
79
-
80
- test("init: a project with a root package.json gets no nested one", async () => {
81
- const dir = await copyOfFixtures(fixtures);
82
-
83
- const { stdout, stderr, exitCode } = await thunderjar(dir, ["init"]);
84
-
85
- expect(stderr).toBe("");
86
- expect(exitCode).toBe(0);
87
- const created = [...SCAFFOLD, ".gitignore"];
88
- expect(stdout).toBe(created.map((f) => `created .thunderjar/${f}\n`).join(""));
89
- expect(filesIn(dir)).toEqual(created.toSorted());
90
- expect(await read(dir, ".gitignore")).toBe("_generated/\n.data/\n");
91
- });
92
- });
93
-
94
- describe("scenario_1_minimal_initial_setup", () => {
95
- const fixtures = scenario("scenario_1_minimal_initial_setup");
96
-
97
- test("init: in an existing project, creates only what's missing and leaves the rest as it was", async () => {
98
- const dir = await copyOfFixtures(fixtures);
99
- const before = new Map(await Promise.all(filesIn(dir).map(async (f) => [f, await read(dir, f)] as const)));
100
-
101
- const { stdout, stderr, exitCode } = await thunderjar(dir, ["init"]);
102
-
103
- expect(stderr).toBe("");
104
- expect(exitCode).toBe(0);
105
- expect(stdout).toBe(`created .thunderjar/tsconfig.json
106
- created .thunderjar/test-case-parameters/harnessModels/claude-code/index.ts
107
- created .thunderjar/test-case-parameters/harnessModels/claude-code/models.ts
108
- created .thunderjar/test-case-parameters/harnessModels/claude-code/versions.ts
109
- created .thunderjar/test-case-parameters/harnessModels/claude-code/collectTokenCosts.ts
110
- created .thunderjar/package.json
111
- exists .thunderjar/thunderjar.config.ts
112
- exists .thunderjar/test-cases/example.ts
113
- exists .thunderjar/test-case-parameters/baseImages/node20/index.ts
114
- exists .thunderjar/test-case-parameters/codeStates/baseline/index.ts
115
- exists .thunderjar/test-case-parameters/promptSets/snerk/index.ts
116
- exists .thunderjar/test-case-parameters/tasks/is-prime/initial-prompts/plain.ts
117
- exists .thunderjar/test-case-parameters/tasks/is-prime/measurements/isPrimeTsExists.ts
118
- exists .thunderjar/.gitignore
119
- `);
120
- for (const [file, content] of before) expect(await read(dir, file)).toBe(content);
121
- expect(await read(dir, "test-cases/example.ts")).toContain("fake-harness-alpha@1.0.0/fake-model-small");
122
- });
123
- });
@@ -1,189 +0,0 @@
1
- import { Command } from "commander";
2
- import { existsSync } from "../../../platform/fs.ts";
3
- import { join } from "../../../platform/path.ts";
4
-
5
- const config = `import { declareConfig, sqliteStore } from "thunderjar";
6
-
7
- export default declareConfig({
8
- imageStore: { repository: "ghcr.io/your-org/thunderjar-images" },
9
- runDataStore: sqliteStore({ path: "./.thunderjar/.data/runs.sqlite" }),
10
- });
11
- `;
12
-
13
- const stub = (fn: string, body: string) => `import { ${fn} } from "thunderjar";\n\nexport default ${fn}(${body});\n`;
14
-
15
- const baseImage = stub(
16
- "declareBaseImage",
17
- `{
18
- applyParameter: () => \`FROM node:20-bookworm\`,
19
- }`,
20
- );
21
-
22
- // Applying a parameter is up to its applyParameter. These read commits from the repository
23
- // Thunderjar is run in: checkoutCommit clones the code state's commit, with no later history,
24
- // into /workspace, and ctx.git.show reads one file at a commit into the build context.
25
- const codeState = `import { checkoutCommit, declareCodeState } from "thunderjar";
26
-
27
- export default declareCodeState({
28
- config: { commit: "a1b2c3" },
29
- applyParameter: (config, ctx) => \`\${checkoutCommit(ctx, config.commit)}\\nRUN npm ci\`,
30
- });
31
- `;
32
-
33
- const promptSet = stub(
34
- "declarePromptSet",
35
- `{
36
- config: { commit: "e4f5a6" },
37
- applyParameter: (config, ctx) => \`COPY \${ctx.git.show(config.commit, "prompts/snerk.md")} /workspace/CLAUDE.md\`,
38
- }`,
39
- );
40
-
41
- const harnessIndex = stub(
42
- "declareHarness",
43
- `{
44
- applyParameter: (_config, ctx) => \`RUN npm install -g @anthropic-ai/claude-code@\${ctx.version}\`,
45
- cli: (ctx) => \`claude -p "\${ctx.initialPrompt}" --model \${ctx.modelId} > \${ctx.resultPath}\`,
46
- requiredEnv: ["ANTHROPIC_API_KEY"],
47
- }`,
48
- );
49
-
50
- const harnessModels = stub(
51
- "declareHarnessModels",
52
- `{
53
- "haiku-4-5": "claude-haiku-4-5-20251001",
54
- }`,
55
- );
56
-
57
- const harnessVersions = stub(
58
- "declareHarnessVersions",
59
- `{
60
- "2.1.283": { version: "2.1.283" },
61
- }`,
62
- );
63
-
64
- const collectTokenCosts = stub(
65
- "declareTokenCostCollector",
66
- `(_raw, _ctx) => {
67
- return { outcome: "unavailable", reason: "notReported" };
68
- }`,
69
- );
70
-
71
- const initialPrompt = stub(
72
- "declareInitialPrompt",
73
- `{
74
- prompt: "Create a file isPrime.ts exporting a function that tests for primality.",
75
- timeoutSeconds: 600,
76
- applyParameter: () => \`\`,
77
- }`,
78
- );
79
-
80
- const measurement = stub(
81
- "declareMeasurement",
82
- `{
83
- instrument: "fileCreated",
84
- config: { glob: "**/isPrime.ts" },
85
- aggregate: ["rate"],
86
- }`,
87
- );
88
-
89
- const testCase = stub(
90
- "declareTestCase",
91
- `{
92
- baseImage: ["node20"],
93
- codeState: ["baseline"],
94
- promptSet: ["snerk"],
95
- harnessModel: ["claude-code@2.1.283/haiku-4-5"],
96
- task: "is-prime",
97
- initialPrompt: ["plain"],
98
- iterations: 1,
99
- }`,
100
- );
101
-
102
- // Brings _generated/parameter-names.d.ts into the editor's program alongside the files
103
- // that use its names — without it they don't resolve, and nothing is checked
104
- // (spec/055-declaring-test-cases.md#typed-names). `allowImportingTsExtensions` because
105
- // thunderjar ships its TypeScript source.
106
- const tsconfig =
107
- JSON.stringify(
108
- {
109
- compilerOptions: {
110
- target: "ESNext",
111
- module: "ESNext",
112
- moduleResolution: "bundler",
113
- strict: true,
114
- noEmit: true,
115
- skipLibCheck: true,
116
- allowImportingTsExtensions: true,
117
- },
118
- include: ["**/*.ts"],
119
- // A templateTest template isn't TypeScript until it is rendered.
120
- exclude: ["node_modules", ".data", "**/*.template.ts"],
121
- },
122
- null,
123
- 2,
124
- ) + "\n";
125
-
126
- const P = "test-case-parameters";
127
-
128
- /** Files `init` creates under `.thunderjar/`, keyed by relative path. */
129
- function scaffold(): Record<string, string> {
130
- return {
131
- "thunderjar.config.ts": config,
132
- "tsconfig.json": tsconfig,
133
- "test-cases/example.ts": testCase,
134
- [`${P}/baseImages/node20/index.ts`]: baseImage,
135
- [`${P}/codeStates/baseline/index.ts`]: codeState,
136
- [`${P}/promptSets/snerk/index.ts`]: promptSet,
137
- [`${P}/harnessModels/claude-code/index.ts`]: harnessIndex,
138
- [`${P}/harnessModels/claude-code/models.ts`]: harnessModels,
139
- [`${P}/harnessModels/claude-code/versions.ts`]: harnessVersions,
140
- [`${P}/harnessModels/claude-code/collectTokenCosts.ts`]: collectTokenCosts,
141
- [`${P}/tasks/is-prime/initial-prompts/plain.ts`]: initialPrompt,
142
- [`${P}/tasks/is-prime/measurements/isPrimeTsExists.ts`]: measurement,
143
- };
144
- }
145
-
146
- export interface InitResult {
147
- created: string[];
148
- skipped: string[];
149
- }
150
-
151
- /**
152
- * Scaffolds `<projectRoot>/.thunderjar/`. Existing files are never overwritten.
153
- * A nested package.json is created only when the project has no root one.
154
- */
155
- export async function init(projectRoot: string): Promise<InitResult> {
156
- const root = join(projectRoot, ".thunderjar");
157
- const nested = !existsSync(join(projectRoot, "package.json"));
158
-
159
- const files = scaffold();
160
- if (nested) {
161
- files["package.json"] =
162
- JSON.stringify(
163
- { name: "thunderjar-config", private: true, type: "module", dependencies: { thunderjar: "latest" } },
164
- null,
165
- 2,
166
- ) + "\n";
167
- }
168
- files[".gitignore"] = ["_generated/", ".data/", ...(nested ? ["node_modules/"] : [])].join("\n") + "\n";
169
-
170
- const result: InitResult = { created: [], skipped: [] };
171
- for (const [rel, content] of Object.entries(files)) {
172
- const path = join(root, rel);
173
- if (existsSync(path)) {
174
- result.skipped.push(rel);
175
- continue;
176
- }
177
- await Bun.write(path, content);
178
- result.created.push(rel);
179
- }
180
- return result;
181
- }
182
-
183
- export function createInitCommand(): Command {
184
- return new Command("init").description("Create .thunderjar/ in this project.").action(async () => {
185
- const { created, skipped } = await init(process.cwd());
186
- for (const f of created) console.log(`created .thunderjar/${f}`);
187
- for (const f of skipped) console.log(`exists .thunderjar/${f}`);
188
- });
189
- }
@@ -1,17 +0,0 @@
1
- // Options several commands share.
2
-
3
- import { InvalidArgumentError, Option } from "commander";
4
-
5
- /** An option that takes a value, may be given only once, and whose value isn't another flag. */
6
- function valueOption(flags: string, description: string): Option {
7
- return new Option(flags, description).argParser((value: string, previous: string | undefined) => {
8
- if (previous !== undefined) throw new InvalidArgumentError("It may only be given once.");
9
- if (value.startsWith("-")) throw new InvalidArgumentError("It needs a value, not another flag.");
10
- return value;
11
- });
12
- }
13
-
14
- export const imagePrefixOption = (description: string) => valueOption("--image-prefix <name>", description);
15
-
16
- export const dataDirOption = () =>
17
- valueOption("--data-dir <dir>", "keep the run data store in this folder, in place of .thunderjar/.data/");