@akanjs/devkit 3.3.0-rc.58 → 3.3.0-rc.59

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.
@@ -8,7 +8,15 @@ import { NativeConfig } from "../mobile/nativeConfig";
8
8
  import type { PackageJson } from "../workspace/types";
9
9
  import { AkanBin } from "./akanBin";
10
10
  import { AkanAppConfig, AkanLibConfig, deriveDefaultAppId } from "./akanConfig";
11
- import { BUN_IMAGE_PIN, DEFAULT_DOCKER_IMAGE } from "./dockerImage";
11
+ import {
12
+ BUN_IMAGE_PIN,
13
+ DEFAULT_DOCKER_IMAGE,
14
+ DOCKER_INIT,
15
+ DOCKERFILE_FORMAT,
16
+ dockerfileLayoutOf,
17
+ dockerfileOf,
18
+ dockerfileSections,
19
+ } from "./dockerImage";
12
20
  import type { LibConfigInput } from "./types";
13
21
 
14
22
  const akanPackageJson = JSON.parse(
@@ -310,7 +318,7 @@ describe("AkanAppConfig", () => {
310
318
  'ENTRYPOINT ["tini","-s","--"]',
311
319
  'CMD ["bun","main.js"]',
312
320
  ];
313
- const lines = (text: string) => text.split("\n").filter((line) => line !== "");
321
+ const lines = (text: string) => text.split("\n").filter((line) => line !== "" && !line.startsWith("#"));
314
322
 
315
323
  expect(lines(new AkanAppConfig(app, [], packageJson, {}, baseDevEnv).dockerfile)).toEqual(lines(before.join("\n")));
316
324
  });
@@ -383,6 +391,7 @@ describe("AkanAppConfig", () => {
383
391
  " && ( rm -rf node_modules/a/darwin ) \\",
384
392
  " && ( find node_modules -name '*.map' -delete || true ) \\",
385
393
  ' && if [ "$TARGETARCH" = "arm64" ]; then rm -rf node_modules/a/linux/x64; fi',
394
+ "# akan:app",
386
395
  "COPY . .",
387
396
  ].join("\n"),
388
397
  );
@@ -394,19 +403,26 @@ describe("AkanAppConfig", () => {
394
403
  const target = lines.lastIndexOf(`FROM ${DEFAULT_DOCKER_IMAGE}`);
395
404
 
396
405
  expect(lines.slice(0, target)).toEqual([
406
+ "# akan:dockerfile 1",
407
+ "# akan:install-stage",
397
408
  `FROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install`,
398
409
  "ARG TARGETARCH",
399
410
  "WORKDIR /workspace",
400
411
  "COPY ./package.json ./bun.lock ./",
401
412
  'RUN bun install --production --frozen-lockfile --os linux --cpu "$(echo "$TARGETARCH" | sed s/amd64/x64/)" \\',
402
413
  " && ( echo prune )",
414
+ "# akan:base",
403
415
  ]);
404
416
  expect(lines.slice(target).filter((line) => line.includes("bun install"))).toEqual([]);
405
- expect(lines.slice(lines.indexOf("RUN echo pre"), lines.indexOf("COPY . .") + 1)).toEqual([
417
+ expect(lines.slice(lines.indexOf("# akan:pre-runs"), lines.indexOf("COPY . .") + 1)).toEqual([
418
+ "# akan:pre-runs",
406
419
  "RUN echo pre",
420
+ "# akan:install",
407
421
  "WORKDIR /workspace",
408
422
  "COPY --from=install /workspace ./",
423
+ "# akan:post-runs",
409
424
  "RUN echo post",
425
+ "# akan:app",
410
426
  "COPY . .",
411
427
  ]);
412
428
  });
@@ -415,12 +431,125 @@ describe("AkanAppConfig", () => {
415
431
  const docker = { crossBuild: true, image: { arm64: "vendor/bun:arm64" } };
416
432
  const local = new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv).dockerfileFor("local");
417
433
 
418
- expect(local).toStartWith(`FROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install\n`);
434
+ expect(local).toContain(
435
+ `# akan:install-stage\nFROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install\n`,
436
+ );
419
437
  expect(local).toContain(
420
438
  `FROM ${DEFAULT_DOCKER_IMAGE} AS amd64\nFROM vendor/bun:arm64 AS arm64\nFROM $TARGETARCH\nARG AKAN_ALLOW_LOCAL_IMAGE\n`,
421
439
  );
422
440
  });
423
441
 
442
+ test("lays docker.env over the build's ENV lines in place, quoting a value Docker would split", () => {
443
+ const docker = { env: { AKAN_PUBLIC_OPERATION_MODE: "edge", EDGE_MODE: "camera", MOTD: 'say "hi" there' } };
444
+ const env = new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv).dockerfile
445
+ .split("\n")
446
+ .filter((line) => line.startsWith("ENV "));
447
+ const plain = new AkanAppConfig(app, [], packageJson, {}, baseDevEnv).dockerfile
448
+ .split("\n")
449
+ .filter((line) => line.startsWith("ENV "));
450
+
451
+ expect(env).toEqual([
452
+ ...plain.map((line) =>
453
+ line === "ENV AKAN_PUBLIC_OPERATION_MODE=cloud" ? "ENV AKAN_PUBLIC_OPERATION_MODE=edge" : line,
454
+ ),
455
+ "ENV EDGE_MODE=camera",
456
+ 'ENV MOTD="say \\"hi\\" there"',
457
+ ]);
458
+ });
459
+
460
+ test("refuses a docker.env key that names no variable and a value holding a line break", () => {
461
+ const configOf = (docker: object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
462
+
463
+ expect(() => configOf({ env: { "EDGE MODE": "camera" } })).toThrow('docker.env names "EDGE MODE"');
464
+ expect(() => configOf({ variants: { edge: { env: { EDGE_MODE: "a\nb" } } } })).toThrow(
465
+ "docker.variants.edge.env.EDGE_MODE holds a line break",
466
+ );
467
+ });
468
+
469
+ test("a variant is the app's docker with its named fields replaced and its env laid over the app's, and a lib's steps reach it", () => {
470
+ const tools = "curl -fsSL https://example.com/kubectl -o /usr/local/bin/kubectl";
471
+ const docker = {
472
+ preRuns: [tools],
473
+ postRuns: ["echo post"],
474
+ env: { REGION: "seoul", EDGE_MODE: "off" },
475
+ variants: {
476
+ edge: { preRuns: [], crossBuild: true, env: { AKAN_PUBLIC_OPERATION_MODE: "edge", EDGE_MODE: "camera" } },
477
+ },
478
+ };
479
+ const lib = { externalLibs: [], docker: { preRuns: ["echo lib"], installRuns: [], postRuns: [] } };
480
+ const config = new AkanAppConfig(app, ["vision"], packageJson, { docker }, baseDevEnv, [], lib);
481
+ const edge = config.dockerfileFor("main", { variant: "edge" });
482
+
483
+ expect(config.dockerVariants).toEqual({
484
+ edge: {
485
+ image: DEFAULT_DOCKER_IMAGE,
486
+ preRuns: ["echo lib"],
487
+ installRuns: [],
488
+ postRuns: ["echo post"],
489
+ command: ["bun", "main.js"],
490
+ crossBuild: true,
491
+ env: { REGION: "seoul", EDGE_MODE: "camera", AKAN_PUBLIC_OPERATION_MODE: "edge" },
492
+ },
493
+ });
494
+ expect(config.dockerfileFor("main")).toContain("ENV EDGE_MODE=off\n");
495
+ expect(config.dockerfileFor("main")).toContain(`RUN echo lib\nRUN ${tools}\n`);
496
+ expect(config.dockerfileFor("main")).toContain("ENV AKAN_PUBLIC_OPERATION_MODE=cloud\n");
497
+ expect(config.dockerfileFor("main")).toContain("ENV REGION=seoul\n");
498
+ expect(edge).toContain(`# akan:install-stage\nFROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install\n`);
499
+ expect(edge).toContain("RUN echo lib\n# akan:install\nWORKDIR /workspace\n");
500
+ expect(edge).not.toContain("kubectl");
501
+ expect(edge).toContain("ENV AKAN_PUBLIC_OPERATION_MODE=edge\n");
502
+ expect(edge).toContain("ENV EDGE_MODE=camera\n");
503
+ expect(edge).toContain("ENV REGION=seoul\n");
504
+ expect(edge).not.toContain("EDGE_MODE=off");
505
+ });
506
+
507
+ test("refuses a variant name that cannot end a file name, and a variant nothing declares", () => {
508
+ const configOf = (docker: string | object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
509
+
510
+ expect(() => configOf({ variants: { "Edge Box": {} } })).toThrow('docker.variants names "Edge Box"');
511
+ expect(() => configOf({ variants: { edge: {} } }).dockerfileFor("main", { variant: "kiosk" })).toThrow(
512
+ 'declares no docker variant "kiosk"',
513
+ );
514
+ expect(configOf("FROM scratch").dockerVariants).toEqual({});
515
+ });
516
+
517
+ test("opens the Dockerfile with its format and marks each section it wrote, so a tool finds one without matching its instructions", () => {
518
+ const plain = dockerfileLayoutOf(new AkanAppConfig(app, [], packageJson, {}, baseDevEnv).dockerfile);
519
+ expect(plain?.format).toBe(DOCKERFILE_FORMAT);
520
+ expect([...(plain?.sections.keys() ?? [])]).toEqual(["base", "install", "app"]);
521
+ expect(plain?.sections.get("install")).toEqual([
522
+ "WORKDIR /workspace",
523
+ "COPY ./package.json ./bun.lock ./",
524
+ "RUN bun install --production --frozen-lockfile",
525
+ ]);
526
+ expect(plain?.sections.get("base")?.[0]).toBe(`FROM ${DEFAULT_DOCKER_IMAGE}`);
527
+ expect(plain?.sections.get("app")?.at(-2)).toBe(`ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}`);
528
+
529
+ const docker = { crossBuild: true, preRuns: ["echo pre"], installRuns: ["echo prune"], postRuns: ["echo post"] };
530
+ const every = dockerfileLayoutOf(new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv).dockerfile);
531
+ expect([...(every?.sections.keys() ?? [])]).toEqual([...dockerfileSections]);
532
+ expect(every?.sections.get("install")).toEqual(["WORKDIR /workspace", "COPY --from=install /workspace ./"]);
533
+ expect(every?.sections.get("install-stage")?.at(-1)).toBe(" && ( echo prune )");
534
+ });
535
+
536
+ test("reads no layout from a Dockerfile it did not write, and the format of one a later version wrote", () => {
537
+ expect(dockerfileLayoutOf('FROM oven/bun:1-slim\nCOPY . .\nCMD ["bun","main.js"]')).toBeNull();
538
+ expect(dockerfileLayoutOf("# akan:base\nFROM scratch")).toBeNull();
539
+ const later = dockerfileLayoutOf("# akan:dockerfile 7\n# akan:base\nFROM scratch\n# akan:warm\nRUN true");
540
+ expect(later?.format).toBe(7);
541
+ expect(later?.sections.get("warm")).toEqual(["RUN true"]);
542
+ });
543
+
544
+ test("the akanConfig entry carries the generator, for a tool that checks its edits against the installed one", async () => {
545
+ const entry = await import("./index");
546
+ expect(entry.dockerfileOf).toBe(dockerfileOf);
547
+ expect(entry.dockerfileLayoutOf).toBe(dockerfileLayoutOf);
548
+ expect(entry.DEFAULT_DOCKER_IMAGE).toBe(DEFAULT_DOCKER_IMAGE);
549
+ expect(entry.DOCKER_INIT).toBe(DOCKER_INIT);
550
+ expect(entry.DOCKERFILE_FORMAT).toBe(DOCKERFILE_FORMAT);
551
+ });
552
+
424
553
  test("keeps a declared Dockerfile string verbatim", () => {
425
554
  const dockerfile = 'FROM oven/bun:1-slim\nCOPY . .\nCMD ["bun","main.js"]';
426
555
  const config = new AkanAppConfig(app, [], packageJson, { docker: dockerfile }, baseDevEnv);
@@ -439,6 +568,7 @@ describe("AkanAppConfig", () => {
439
568
  postRuns: [],
440
569
  command: ["bun", "main.js"],
441
570
  crossBuild: false,
571
+ env: {},
442
572
  });
443
573
  });
444
574
 
@@ -11,7 +11,7 @@ import type { BaseDevEnv, PackageJson } from "../workspace/types";
11
11
  import { AkanBin } from "./akanBin";
12
12
  import { AkanWorkers, type LibWorkers } from "./akanWorkers";
13
13
  import { DesktopServerConfig } from "./desktopServerConfig";
14
- import { DEFAULT_DOCKER_IMAGE, dockerfileOf } from "./dockerImage";
14
+ import { dockerfileOf, resolveDocker, resolveDockerVariants } from "./dockerImage";
15
15
  import { NativeFileSettings } from "./nativeFileSettings";
16
16
  import { nativeKeys } from "./nativeKeys";
17
17
  import type {
@@ -33,8 +33,8 @@ import type {
33
33
  DatabaseMode,
34
34
  DeepPartial,
35
35
  DockerConfig,
36
+ DockerImageConfig,
36
37
  DockerOption,
37
- DockerRun,
38
38
  LibAssetsConfig,
39
39
  LibConfigResult,
40
40
  LibDockerConfig,
@@ -148,13 +148,6 @@ const normalizeKeepFonts = (keepFonts: string[] | undefined) => [
148
148
  ...new Set((keepFonts ?? []).map((glob) => glob.trim().replace(/^\/+/, "")).filter(Boolean)),
149
149
  ];
150
150
 
151
- /** First occurrence wins, so a step a lib and its app both declare becomes one layer. */
152
- const dedupeDockerRuns = (runs: DockerRun[]): DockerRun[] => {
153
- const byKey = new Map<string, DockerRun>();
154
- for (const run of runs) byKey.set(typeof run === "string" ? run : JSON.stringify(run), run);
155
- return [...byKey.values()];
156
- };
157
-
158
151
  class LibConfigRefusal extends Error {}
159
152
 
160
153
  export class AkanAppConfig implements AppConfigResult {
@@ -163,6 +156,8 @@ export class AkanAppConfig implements AppConfigResult {
163
156
  docker: DockerConfig;
164
157
  /** The Dockerfile `akan build` writes: the declared string verbatim, or one assembled from the parts. */
165
158
  dockerfile: string;
159
+ /** Each is the app's `docker` with the variant's fields replaced; a lib's steps reach every one. */
160
+ dockerVariants: Record<string, DockerImageConfig>;
166
161
  database: AkanDatabaseConfig;
167
162
  web: AkanWebConfig;
168
163
  externalLibs: string[];
@@ -260,7 +255,8 @@ export class AkanAppConfig implements AppConfigResult {
260
255
  this.hasNativeConfig = Boolean(config.native);
261
256
  this.native = this.#resolveNativeConfig(config.native);
262
257
  this.web = this.#resolveWebConfig(config.web);
263
- this.docker = AkanAppConfig.#resolveDocker(config.docker, libContributions.docker);
258
+ this.docker = resolveDocker(config.docker, libContributions.docker);
259
+ this.dockerVariants = resolveDockerVariants(config.docker, libContributions.docker);
264
260
  this.dockerfile = this.#makeDockerfile();
265
261
  }
266
262
  #resolveWebConfig(web: AkanWebOption | undefined): AkanWebConfig {
@@ -438,18 +434,6 @@ export class AkanAppConfig implements AppConfigResult {
438
434
  this.branches.forEach((domain) => void domains.add(`${basePath}-${domain}.${serveDomain}`));
439
435
  });
440
436
  }
441
- /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
442
- static #resolveDocker(docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig {
443
- if (typeof docker === "string") return docker;
444
- return {
445
- image: docker?.image ?? DEFAULT_DOCKER_IMAGE,
446
- preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker?.preRuns ?? [])]),
447
- installRuns: dedupeDockerRuns([...libDocker.installRuns, ...(docker?.installRuns ?? [])]),
448
- postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker?.postRuns ?? [])]),
449
- command: docker?.command ?? ["bun", "main.js"],
450
- crossBuild: docker?.crossBuild ?? false,
451
- };
452
- }
453
437
  /** What the built server runs with in its image; a desktop app's carried server starts from the same values. */
454
438
  getProductionEnv(environment: string = this.baseDevEnv.env): Record<string, string> {
455
439
  return {
@@ -479,13 +463,24 @@ export class AkanAppConfig implements AppConfigResult {
479
463
  "ARG AKAN_ALLOW_LOCAL_IMAGE",
480
464
  `RUN if [ "$AKAN_ALLOW_LOCAL_IMAGE" != "1" ]; then echo "This build ran with AKAN_PUBLIC_ENV=local, so the server runs without endpoint rate limits and on local defaults for Redis and the database mode. Build for the environment it deploys to with akan build --env, or pass --build-arg AKAN_ALLOW_LOCAL_IMAGE=1." >&2; exit 1; fi`,
481
465
  ].join("\n");
482
- dockerfileFor(environment: string, options: { lockfile?: boolean; env?: Record<string, string> } = {}): string {
483
- return this.#makeDockerfile(environment, options.lockfile ?? true, options.env);
466
+ dockerfileFor(
467
+ environment: string,
468
+ options: { lockfile?: boolean; env?: Record<string, string>; variant?: string } = {},
469
+ ): string {
470
+ return this.#makeDockerfile(environment, options.lockfile ?? true, options.env, options.variant);
484
471
  }
485
- #makeDockerfile(environment?: string, lockfile = true, env = this.getProductionEnv(environment)): string {
472
+ #makeDockerfile(
473
+ environment?: string,
474
+ lockfile = true,
475
+ env = this.getProductionEnv(environment),
476
+ variant?: string,
477
+ ): string {
486
478
  if (typeof this.docker === "string") return this.docker;
479
+ const docker = variant === undefined ? this.docker : this.dockerVariants[variant];
480
+ if (!docker)
481
+ throw new Error(`[docker] apps/${this.app.name}/akan.config.ts declares no docker variant "${variant}"`);
487
482
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
488
- return dockerfileOf(this.docker, { env, lockfile, guard: isLocal ? AkanAppConfig.localImageGuard : undefined });
483
+ return dockerfileOf(docker, { env, lockfile, guard: isLocal ? AkanAppConfig.localImageGuard : undefined });
489
484
  }
490
485
  static #importGeneration = 0;
491
486
  // Bun caches dynamic imports by path; a fresh query string re-evaluates the config module (its imports stay cached).
@@ -1,4 +1,12 @@
1
- import { type Arch, archs, type DockerImageConfig, type DockerRun } from "./types";
1
+ import {
2
+ type Arch,
3
+ archs,
4
+ type DockerConfig,
5
+ type DockerImageConfig,
6
+ type DockerOption,
7
+ type DockerRun,
8
+ type LibDockerConfig,
9
+ } from "./types";
2
10
 
3
11
  //? A Bun bump changes both: `docker buildx imagetools inspect oven/bun:<version>-slim` prints the new multi-arch digest.
4
12
  export const BUN_IMAGE_PIN = {
@@ -20,8 +28,20 @@ export const DOCKER_WRITE_DIRS = [
20
28
  "/workspace/.akan/artifact/image-cache",
21
29
  ];
22
30
 
23
- export const DOCKER_IGNORED = [...DOCKER_WRITE_DIRS.map((dir) => dir.slice("/workspace/".length)), "node_modules"];
31
+ export const DOCKER_VARIANT_FILE_PREFIX = "Dockerfile.";
32
+ export const DOCKER_IGNORED = [
33
+ ...DOCKER_WRITE_DIRS.map((dir) => dir.slice("/workspace/".length)),
34
+ "node_modules",
35
+ //? Copied in, a variant's Dockerfile would rebuild every other image's `COPY . .` layer when it alone changed.
36
+ `${DOCKER_VARIANT_FILE_PREFIX}*`,
37
+ ];
24
38
  export const DOCKER_INSTALL_STAGE = "install";
39
+ //? Raised when the sections change: a tool editing the file then meets a number it does not know, and can say so.
40
+ export const DOCKERFILE_FORMAT = 1;
41
+ export const dockerfileSections = ["install-stage", "base", "pre-runs", "install", "post-runs", "app"] as const;
42
+ export type DockerfileSection = (typeof dockerfileSections)[number];
43
+ const DOCKERFILE_MARK = "# akan:";
44
+ const DOCKERFILE_HEAD = `${DOCKERFILE_MARK}dockerfile `;
25
45
  //? Bun names the CPU x64 where Docker's TARGETARCH says amd64.
26
46
  const DOCKER_INSTALL_TARGET = `--os linux --cpu "$(echo "$TARGETARCH" | sed s/amd64/x64/)"`;
27
47
 
@@ -44,6 +64,15 @@ export const dockerImageScript = (image: string | { [key in Arch]?: string }) =>
44
64
  ? `FROM ${image}`
45
65
  : [...archs.map((arch) => `FROM ${image[arch] ?? DEFAULT_DOCKER_IMAGE} AS ${arch}`), "FROM $TARGETARCH"].join("\n");
46
66
 
67
+ //? Docker ends an unquoted ENV value at a space; inside quotes it still expands `$NAME`.
68
+ const dockerEnvValue = (value: string) => (/[\s"'\\]/.test(value) ? JSON.stringify(value) : value);
69
+
70
+ const dockerEnvLines = (build: Record<string, string>, declared: Record<string, string>) => {
71
+ const lines = new Map(Object.entries(build).map(([key, value]) => [key, `ENV ${key}=${value}`]));
72
+ for (const [key, value] of Object.entries(declared)) lines.set(key, `ENV ${key}=${dockerEnvValue(value)}`);
73
+ return [...lines.values()];
74
+ };
75
+
47
76
  export interface DockerfileParts {
48
77
  env: Record<string, string>;
49
78
  lockfile: boolean;
@@ -67,31 +96,121 @@ const dockerInstallScripts = (
67
96
  ];
68
97
  };
69
98
 
99
+ const dockerfileSectionOf = (section: DockerfileSection, instructions: string[]) =>
100
+ instructions.length ? [`${DOCKERFILE_MARK}${section}`, ...instructions] : [];
101
+
70
102
  export const dockerfileOf = (docker: DockerImageConfig, { env, lockfile, guard }: DockerfileParts) => {
71
103
  const { image, preRuns, postRuns, command, crossBuild } = docker;
72
104
  const install = dockerInstallScripts(docker, lockfile);
73
105
  return [
74
- ...(crossBuild
75
- ? [
76
- //? One image for every target: the stage runs on the build machine, where a per-architecture image may not.
77
- `FROM --platform=$BUILDPLATFORM ${typeof image === "string" ? image : DEFAULT_DOCKER_IMAGE} AS ${DOCKER_INSTALL_STAGE}`,
78
- "ARG TARGETARCH",
79
- ...install,
80
- ]
81
- : []),
82
- dockerImageScript(image),
83
- ...(guard ? [guard] : []),
84
- "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
85
- "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
86
- "ARG TARGETARCH",
87
- ...dockerRunScripts(preRuns),
88
- ...(crossBuild ? ["WORKDIR /workspace", `COPY --from=${DOCKER_INSTALL_STAGE} /workspace ./`] : install),
89
- ...dockerRunScripts(postRuns),
90
- "COPY . .",
91
- `RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}`,
92
- ...Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`),
93
- `USER ${DOCKER_RUN_USER}`,
94
- `ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}`,
95
- `CMD ${JSON.stringify(command)}`,
106
+ `${DOCKERFILE_HEAD}${DOCKERFILE_FORMAT}`,
107
+ ...dockerfileSectionOf(
108
+ "install-stage",
109
+ crossBuild
110
+ ? [
111
+ //? One image for every target: the stage runs on the build machine, where a per-architecture image may not.
112
+ `FROM --platform=$BUILDPLATFORM ${typeof image === "string" ? image : DEFAULT_DOCKER_IMAGE} AS ${DOCKER_INSTALL_STAGE}`,
113
+ "ARG TARGETARCH",
114
+ ...install,
115
+ ]
116
+ : [],
117
+ ),
118
+ ...dockerfileSectionOf("base", [
119
+ dockerImageScript(image),
120
+ ...(guard ? [guard] : []),
121
+ "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
122
+ "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
123
+ "ARG TARGETARCH",
124
+ ]),
125
+ ...dockerfileSectionOf("pre-runs", dockerRunScripts(preRuns)),
126
+ ...dockerfileSectionOf(
127
+ "install",
128
+ crossBuild ? ["WORKDIR /workspace", `COPY --from=${DOCKER_INSTALL_STAGE} /workspace ./`] : install,
129
+ ),
130
+ ...dockerfileSectionOf("post-runs", dockerRunScripts(postRuns)),
131
+ ...dockerfileSectionOf("app", [
132
+ "COPY . .",
133
+ `RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}`,
134
+ ...dockerEnvLines(env, docker.env),
135
+ `USER ${DOCKER_RUN_USER}`,
136
+ `ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}`,
137
+ `CMD ${JSON.stringify(command)}`,
138
+ ]),
96
139
  ].join("\n");
97
140
  };
141
+
142
+ export interface DockerfileLayout {
143
+ format: number;
144
+ /** Each section's lines under its marker, in the file's order; a newer format may name one this version lacks. */
145
+ sections: Map<string, string[]>;
146
+ }
147
+
148
+ export const dockerfileLayoutOf = (dockerfile: string): DockerfileLayout | null => {
149
+ const [head = "", ...lines] = dockerfile.split("\n");
150
+ if (!/^# akan:dockerfile \d+$/.test(head)) return null;
151
+ const sections = new Map<string, string[]>();
152
+ let current: string[] | null = null;
153
+ for (const line of lines) {
154
+ if (line.startsWith(DOCKERFILE_MARK)) {
155
+ current = [];
156
+ sections.set(line.slice(DOCKERFILE_MARK.length), current);
157
+ } else current?.push(line);
158
+ }
159
+ return { format: Number(head.slice(DOCKERFILE_HEAD.length)), sections };
160
+ };
161
+
162
+ /** First occurrence wins, so a step a lib and its app both declare becomes one layer. */
163
+ const dedupeDockerRuns = (runs: DockerRun[]): DockerRun[] => {
164
+ const byKey = new Map<string, DockerRun>();
165
+ for (const run of runs) byKey.set(typeof run === "string" ? run : JSON.stringify(run), run);
166
+ return [...byKey.values()];
167
+ };
168
+
169
+ const dockerEnvKeyPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
170
+ //? The name ends `Dockerfile.<name>`, which a shell, a CI step and `docker build -f` all take unquoted.
171
+ const dockerVariantNamePattern = /^[a-z][a-z0-9-]*$/;
172
+
173
+ const resolveDockerImage = (
174
+ docker: Partial<DockerImageConfig>,
175
+ libDocker: LibDockerConfig,
176
+ envOwner: string,
177
+ ): DockerImageConfig => {
178
+ const env = docker.env ?? {};
179
+ for (const [key, value] of Object.entries(env)) {
180
+ if (!dockerEnvKeyPattern.test(key))
181
+ throw new Error(`[docker] ${envOwner} names "${key}", which is not an environment variable name`);
182
+ if (/[\r\n]/.test(value))
183
+ throw new Error(`[docker] ${envOwner}.${key} holds a line break, which an ENV line cannot carry`);
184
+ }
185
+ return {
186
+ image: docker.image ?? DEFAULT_DOCKER_IMAGE,
187
+ preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker.preRuns ?? [])]),
188
+ installRuns: dedupeDockerRuns([...libDocker.installRuns, ...(docker.installRuns ?? [])]),
189
+ postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker.postRuns ?? [])]),
190
+ command: docker.command ?? ["bun", "main.js"],
191
+ crossBuild: docker.crossBuild ?? false,
192
+ env,
193
+ };
194
+ };
195
+
196
+ /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
197
+ export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig =>
198
+ typeof docker === "string" ? docker : resolveDockerImage(docker ?? {}, libDocker, "docker.env");
199
+
200
+ export const resolveDockerVariants = (
201
+ docker: DockerOption | undefined,
202
+ libDocker: LibDockerConfig,
203
+ ): Record<string, DockerImageConfig> => {
204
+ if (typeof docker === "string" || !docker?.variants) return {};
205
+ const { variants, ...base } = docker;
206
+ return Object.fromEntries(
207
+ Object.entries(variants).map(([name, variant]) => {
208
+ if (!dockerVariantNamePattern.test(name))
209
+ throw new Error(
210
+ `[docker] docker.variants names "${name}", which cannot end a file name: use lowercase letters, digits and "-"`,
211
+ );
212
+ const env = { ...base.env, ...variant.env };
213
+ return [name, resolveDockerImage({ ...base, ...variant, env }, libDocker, `docker.variants.${name}.env`)];
214
+ }),
215
+ );
216
+ };
@@ -2,4 +2,5 @@ export * from "./akanBin";
2
2
  export * from "./akanConfig";
3
3
  export * from "./akanWorkers";
4
4
  export * from "./akanWorkspaceConfig";
5
+ export * from "./dockerImage";
5
6
  export * from "./types";
@@ -44,6 +44,7 @@ export type {
44
44
  DockerImageConfig,
45
45
  DockerOption,
46
46
  DockerRun,
47
+ DockerVariantOption,
47
48
  FileConventionScanResult,
48
49
  LibAssetsConfig,
49
50
  LibConfig,
@@ -96,6 +96,37 @@ console.info(new SampleService().name);
96
96
  }
97
97
  });
98
98
 
99
+ test("writes each docker variant beside the Dockerfile as Dockerfile.<name>, for the build's environment", async () => {
100
+ const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
101
+ const config = new AkanAppConfig(
102
+ { name: "portal" } as never,
103
+ [],
104
+ { name: "repo", version: "1.0.0", description: "repo" },
105
+ { docker: { variants: { edge: { env: { AKAN_PUBLIC_OPERATION_MODE: "edge" } } } } },
106
+ { repoName: "akanjs", serveDomain: "akanjs.com", env: "local", portOffset: 0, workspaceRoot: root },
107
+ );
108
+ const app = {
109
+ getConfig: async () => config,
110
+ getScanInfo: () => ({ getLibs: () => [] }),
111
+ dist: new Executor("dist", root),
112
+ workspace: { workspaceRoot: root },
113
+ logger: { warn: () => undefined },
114
+ } as unknown as App;
115
+ try {
116
+ await new ApplicationBuildRunner(app, { environment: "debug" }).buildAppMeta();
117
+ const image = await readFile(path.join(root, "Dockerfile"), "utf8");
118
+ const edge = await readFile(path.join(root, "Dockerfile.edge"), "utf8");
119
+ expect(image).toContain("ENV AKAN_PUBLIC_OPERATION_MODE=cloud\n");
120
+ expect(edge).toBe(
121
+ image.replace("ENV AKAN_PUBLIC_OPERATION_MODE=cloud\n", "ENV AKAN_PUBLIC_OPERATION_MODE=edge\n"),
122
+ );
123
+ expect(edge).toContain("ENV AKAN_PUBLIC_ENV=debug\n");
124
+ expect((await readFile(path.join(root, ".dockerignore"), "utf8")).split("\n")).toContain("Dockerfile.*");
125
+ } finally {
126
+ await rm(root, { recursive: true, force: true });
127
+ }
128
+ });
129
+
99
130
  test("writes beside main.js the env its Dockerfile sets, so a host without the image runs the build as is", async () => {
100
131
  const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
101
132
  const config = new AkanAppConfig(
@@ -5,7 +5,7 @@ import { BUILD_ENV_FILE, BUILD_ENV_MODULE } from "akanjs/server/lifecycle/buildE
5
5
  import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
6
  import type { BunPlugin } from "bun";
7
7
  import { AkanBin } from "../akanConfig/akanBin";
8
- import { DOCKER_IGNORED } from "../akanConfig/dockerImage";
8
+ import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
9
9
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
10
10
  import type { App } from "../commandDecorators";
11
11
  import { parseEnvFile, WorkspaceExecutor } from "../executors";
@@ -412,10 +412,12 @@ export class ApplicationBuildRunner {
412
412
  ? `The build carries ${carried.join(", ")} in ${AppBin.dir}/<TARGETARCH>/; apps/${this.#app.name}/akan.config.ts writes its own Dockerfile, which puts that folder on PATH itself (ENV PATH=${AkanBin.imagePath(AppBin.dir)}).`
413
413
  : `The image carries ${carried.join(", ")} from bin, first on its PATH.`,
414
414
  );
415
- const dockerfile = akanConfig.dockerfileFor(environment, {
415
+ const imageParts = {
416
416
  lockfile: lockfile !== null,
417
417
  env: { ...(carried.length ? { PATH: AkanBin.imagePath(AppBin.dir) } : {}), ...env },
418
- });
418
+ };
419
+ const dockerfile = akanConfig.dockerfileFor(environment, imageParts);
420
+ const variants = Object.keys(akanConfig.dockerVariants);
419
421
  const { dist } = this.#app;
420
422
  const buildInfo = {
421
423
  buildId: await this.#resolveBuildId(),
@@ -430,6 +432,13 @@ export class ApplicationBuildRunner {
430
432
  ? [dist.writeFile(`${dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile, silent)]
431
433
  : []),
432
434
  dist.writeFile(`${dist.cwdPath}/Dockerfile`, dockerfile, silent),
435
+ ...variants.map((variant) =>
436
+ dist.writeFile(
437
+ `${dist.cwdPath}/${DOCKER_VARIANT_FILE_PREFIX}${variant}`,
438
+ akanConfig.dockerfileFor(environment, { ...imageParts, variant }),
439
+ silent,
440
+ ),
441
+ ),
433
442
  //? A build run by hand writes its database beside main.js, and `COPY . .` would carry it into the image.
434
443
  dist.writeFile(`${dist.cwdPath}/.dockerignore`, `${DOCKER_IGNORED.join("\n")}\n`, silent),
435
444
  dist.writeJson("akan.build.json", buildInfo, silent),
@@ -14,7 +14,7 @@ the server errors logged meanwhile, console errors and warnings, and layout smel
14
14
  - It uses the dev server that answers for this app and checkout. With none, it starts one for the run and
15
15
  stops it after; `--keep` leaves it up for the next preview. It never starts a second server beside a
16
16
  running one.
17
- - Paths are comma-separated (`akan preview <app> /board,/board/new`) and get the default locale when they lack
17
+ - Paths are space- or comma-separated (`akan preview <app> /board /board/new`) and get the default locale when they lack
18
18
  one, unless the app sets `localePrefix: "as-needed"` and `--csr` is off. What the server answers outside a
19
19
  locale opens as written, with no locale and no CSR boot query: a `/_akan` route such as Studio
20
20
  (`/_akan/studio?view=runtime`), a route under the API prefix, `/__csr`, `/__rsc`, `/.well-known`,
@@ -71,7 +71,9 @@ File names, stages, the `.render()` order and what a route file must never do ar
71
71
  `.notFound(() => <><title>Not found</title>…</>)`, except below a `.loading()`, where the head is already out.
72
72
  - `<Link href="/books/OL45804W">`: write the path without the locale; Link adds it, or leaves it off for the default
73
73
  locale under `i18n.localePrefix: "as-needed"`. It renders an `<a>` and takes its attributes; `activeClassName`
74
- marks the current one.
74
+ marks the current one from the press, before its page arrives; an `active` prop from a layout's render is late.
75
+ - An SSR page still loading: `pendingClassName` / `data-pending` on its `Link`, and `usePendingNavigation()`
76
+ (`akanjs/client`) for its `{ path, searchParams }`, `null` once the page is drawn.
75
77
  - From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
76
78
  - A page state a push opens in the query (a record in `?id=`): close it with `router.backTo(href)`, never
77
79
  `router.back()` or a `renderMode` branch. A CSR or native stack rewrites a push that keeps the pathname rather than
@@ -15,7 +15,7 @@ the agent guide's Path Rules table.
15
15
  | --- | --- |
16
16
  | API only, or no CSR bundle for native apps | `web: false`, `web: { csr: false }` |
17
17
  | Move the API or websocket mount | `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in `api: { … }`; read with `getApiPrefix()` / `getWsPrefix()` |
18
- | The production image | `docker: string \| { image, preRuns, installRuns, postRuns, command, crossBuild }` |
18
+ | The production image | `docker: string \| { image, preRuns, installRuns, postRuns, command, crossBuild, env, variants }` |
19
19
  | iOS, Android, desktop | the `native` section; `desktop: { server: true }` carries the server |
20
20
  | SQLite, several databases, a cluster | `database: { modes: [...] }` (`single`, `multiple`, `cluster`), picked by `AKAN_DATABASE_MODE` |
21
21
  | A secret of `env/env.server.<env>.ts` in a deployed server | nothing to declare: `akan build` leaves it out and the server reads it from a variable named after its key path; `akan secret-env <app> --env <env>` lists them |
@@ -33,7 +33,7 @@ import {
33
33
  import { camelToKebabCase } from "./camelToKebabCase";
34
34
  import { CliError, type CliErrorCode } from "./cliError";
35
35
  import { CommandContainer } from "./dependencyBuilder";
36
- import { formatCommandHelp, formatHelp } from "./helpFormatter";
36
+ import { formatCommandHelp, formatHelp, usageArgsOf } from "./helpFormatter";
37
37
  import {
38
38
  type CommandCls,
39
39
  getTargetCommandNames,
@@ -88,13 +88,17 @@ const failureReporterOf =
88
88
 
89
89
  //? commander refuses a flag, an argument or a command before any action runs, having printed why to stderr.
90
90
  //? Thrown, not exited: the failure path awaits onFailure, and an exit drops what a pipe still buffers.
91
- const usageRefusalOf = (error: CommanderError) => {
91
+ const usageRefusalOf = (error: CommanderError, hint = "") => {
92
92
  if (error.exitCode === 0) process.exit(0);
93
- const refused = new CliError("usage", error.message.replace(/^error: /, ""));
93
+ if (hint) process.stderr.write(`${hint}\n`);
94
+ const refused = new CliError("usage", `${error.message.replace(/^error: /, "")}${hint ? ` ${hint}` : ""}`);
94
95
  loggedCliErrorObjects.add(refused);
95
96
  return refused;
96
97
  };
97
98
 
99
+ export const excessArgumentHintOf = (commandName: string, argMetas: (ArgMeta | InternalArgMeta)[]) =>
100
+ `\`akan ${commandName}\` takes ${usageArgsOf(argMetas).join(" ") || "no argument"}: see \`akan ${commandName} --help\`.`;
101
+
98
102
  const handleOption = (programCommand: Command, argMeta: ArgMeta) => {
99
103
  const {
100
104
  type,
@@ -118,7 +122,7 @@ const handleOption = (programCommand: Command, argMeta: ArgMeta) => {
118
122
  const handleArgument = (programCommand: Command, argMeta: ArgMeta) => {
119
123
  const kebabName = camelToKebabCase(argMeta.name);
120
124
  programCommand.argument(
121
- `[${kebabName}]`,
125
+ `[${kebabName}${argMeta.argsOption.multiple ? "..." : ""}]`,
122
126
  `${argMeta.argsOption.desc}${argMeta.argsOption.example ? ` (example: ${argMeta.argsOption.example})` : ""}`,
123
127
  );
124
128
  return programCommand;
@@ -257,11 +261,17 @@ export const getOptionValue = async (argMeta: ArgMeta, opt: Record<string, unkno
257
261
  } else return convertArgValue(await input({ message: inputMessageOf(argMeta) }), type ?? "string");
258
262
  };
259
263
 
260
- export const getArgumentValue = async (argMeta: ArgMeta, value: string | undefined) => {
264
+ export const getArgumentValue = async (argMeta: ArgMeta, value: string | string[] | undefined) => {
261
265
  const { default: defaultValue, type, nullable } = argMeta.argsOption;
262
- if (value !== undefined) {
263
- assertEnumChoice(argMeta, value);
264
- return convertArgValue(value, type ?? "string");
266
+ if (argMeta.argsOption.multiple) {
267
+ const values = operandListOf(value);
268
+ for (const each of values) assertEnumChoice(argMeta, each);
269
+ return values.map((each) => convertArgValue(each, type ?? "string"));
270
+ }
271
+ const given = Array.isArray(value) ? value[0] : value;
272
+ if (given !== undefined) {
273
+ assertEnumChoice(argMeta, given);
274
+ return convertArgValue(given, type ?? "string");
265
275
  } else if (defaultValue !== undefined) return defaultValue;
266
276
  else if (nullable) return null;
267
277
  const { enum: enumChoices } = argMeta.argsOption;
@@ -326,7 +336,7 @@ export const rerunCommandOf =
326
336
  const rerunRemedyOf = (rerun: RerunOf | undefined, placeholder: string) =>
327
337
  rerun ? { remedy: `rerun it as \`${rerun(placeholder)}\`` } : {};
328
338
 
329
- const parseAppNameList = (value: string | string[] | undefined): string[] =>
339
+ const operandListOf = (value: string | string[] | undefined): string[] =>
330
340
  (Array.isArray(value) ? value : value === undefined ? [] : [value])
331
341
  .flatMap((entry) => entry.split(","))
332
342
  .map((entry) => entry.trim())
@@ -340,7 +350,7 @@ export const getAppsArgumentValue = async (
340
350
  ): Promise<AppExecutor[]> => {
341
351
  const appNames = await workspace.getApps();
342
352
  if (appNames.length === 0) throw new Error("No apps found in this workspace (apps/<appName>/akan.config.ts)");
343
- const requested = parseAppNameList(value);
353
+ const requested = operandListOf(value);
344
354
  if (requested.includes("all")) return appNames.map((name) => AppExecutor.from(workspace, name));
345
355
  if (requested.length) {
346
356
  const unknown = requested.filter((name) => !appNames.includes(name));
@@ -549,7 +559,10 @@ export const runCommands = async (...commands: CommandCls[]) => {
549
559
  const { onFailure } = targetMeta.targetOption;
550
560
  const [allArgMetas] = getArgMetas(command, targetMeta.key);
551
561
  programCommand.exitOverride((error) => {
552
- const refused = usageRefusalOf(error);
562
+ const refused = usageRefusalOf(
563
+ error,
564
+ error.code === "commander.excessArguments" ? excessArgumentHintOf(commandName, allArgMetas) : "",
565
+ );
553
566
  failure.usageExitCode = targetUsageExitCode;
554
567
  const given = givenOptionsOf(allArgMetas, programCommand.opts());
555
568
  failure.report = failureReporterOf(asksJson(allArgMetas, given), onFailure, { usage: true, given });
@@ -607,7 +620,10 @@ export const runCommands = async (...commands: CommandCls[]) => {
607
620
  if (argMeta.type === "Option")
608
621
  commandArgs[argMeta.idx] = await getOptionValue(argMeta, opt, commandContext);
609
622
  else if (argMeta.type === "Argument")
610
- commandArgs[argMeta.idx] = await getArgumentValue(argMeta, cmdArgs[argMeta.idx] as string);
623
+ commandArgs[argMeta.idx] = await getArgumentValue(
624
+ argMeta,
625
+ cmdArgs[argMeta.idx] as string | string[] | undefined,
626
+ );
611
627
  else if (argMeta.type === "Apps")
612
628
  commandArgs[argMeta.idx] = await getAppsArgumentValue(
613
629
  cmdArgs[argMeta.idx] as string | string[] | undefined,
@@ -82,10 +82,16 @@ const argMetaOf = (
82
82
  argsOption: Pick<ArgsOption, "multiple"> | undefined,
83
83
  idx: number,
84
84
  ): ArgMeta => {
85
- if (type === "Argument" && argsOption?.multiple) throw new Error(`argument '${name}' cannot be multiple`);
86
85
  return { name, argsOption: { ...argsOption, type: normalizePrimitiveArgType(primitive) }, key: "", idx, type };
87
86
  };
88
87
 
88
+ //? commander gives a variadic argument every word left on the line, and throws for one declared before another.
89
+ const assertListArgumentIsLast = (args: (ArgMeta | InternalArgMeta)[]) => {
90
+ const positionals = args.filter((arg) => arg.type !== "Option" && arg.type !== "Workspace");
91
+ const list = positionals.slice(0, -1).find((arg) => arg.type === "Argument" && arg.argsOption.multiple);
92
+ if (list?.type === "Argument") throw new Error(`argument '${list.name}' takes a list, so it must be declared last`);
93
+ };
94
+
89
95
  class TargetBuilder<Deps extends readonly DependencyCls[], Params extends unknown[] = [], Context = object> {
90
96
  readonly #args: (ArgMeta | InternalArgMeta)[];
91
97
 
@@ -128,6 +134,7 @@ class TargetBuilder<Deps extends readonly DependencyCls[], Params extends unknow
128
134
  }
129
135
 
130
136
  exec(handler: CommandHandler<Deps, Params>) {
137
+ assertListArgumentIsLast(this.#args);
131
138
  return {
132
139
  args: this.#args,
133
140
  handler: handler as TargetMeta["handler"],
@@ -1058,7 +1058,7 @@ describe("a repeatable option", () => {
1058
1058
  );
1059
1059
  });
1060
1060
 
1061
- test("types the exec parameter as a list, and a positional argument cannot repeat", () => {
1061
+ test("types the exec parameter as a list, and a list argument must be the last positional", () => {
1062
1062
  const expectType = <Expected>(_value: Expected) => undefined;
1063
1063
  class RepeatRunner extends runner("repeat") {}
1064
1064
  class RepeatScript extends script("repeat", [RepeatRunner]) {}
@@ -1072,13 +1072,37 @@ describe("a repeatable option", () => {
1072
1072
  }),
1073
1073
  })) {}
1074
1074
  expect(getTargetMetas(RepeatCommand)[0]?.key).toBe("run");
1075
+ class ListCommand extends command("list", [RepeatScript], ({ public: target }) => ({
1076
+ run: target({ desc: "run" })
1077
+ .arg("action", String)
1078
+ .arg("names", String, { multiple: true })
1079
+ .option("force", Boolean)
1080
+ .exec(async (action, names) => {
1081
+ expectType<string>(action);
1082
+ expectType<string[]>(names);
1083
+ }),
1084
+ })) {}
1085
+ expect(stripAnsi(formatCommandHelp(ListCommand, "run"))).toContain("akan run [action] [names...]");
1075
1086
  expect(() =>
1076
- command("repeatArg", [RepeatScript], ({ public: target }) => ({
1087
+ command("listFirst", [RepeatScript], ({ public: target }) => ({
1077
1088
  run: target({ desc: "run" })
1078
1089
  .arg("names", String, { multiple: true })
1090
+ .arg("action", String)
1079
1091
  .exec(async () => undefined),
1080
1092
  })),
1081
- ).toThrow("argument 'names' cannot be multiple");
1093
+ ).toThrow("argument 'names' takes a list, so it must be declared last");
1094
+ });
1095
+
1096
+ test("a list argument reads its words space- or comma-separated, each against the choices, and none as empty", async () => {
1097
+ const names: ArgMeta = { ...meta, name: "names", type: "Argument" };
1098
+ expect(await getArgumentValue(names, ["a.test.ts", "b.test.ts,c.test.ts", " "])).toEqual([
1099
+ "a.test.ts",
1100
+ "b.test.ts",
1101
+ "c.test.ts",
1102
+ ]);
1103
+ expect(await getArgumentValue(names, undefined)).toEqual([]);
1104
+ const choices = { ...names, argsOption: { ...names.argsOption, enum: ["a", "b"] } };
1105
+ await expect(getArgumentValue(choices, ["a", "c"])).rejects.toThrow("argument 'names' argument 'c' is invalid");
1082
1106
  });
1083
1107
 
1084
1108
  test("collects each time the flag is given, long or short", async () => {
@@ -1098,6 +1122,17 @@ describe("a repeatable option", () => {
1098
1122
  " .exec(async function (param) {",
1099
1123
  " process.stdout.write(JSON.stringify(param));",
1100
1124
  " }),",
1125
+ ' gather: target({ desc: "gathers", stdio: true })',
1126
+ ' .arg("action", String)',
1127
+ ' .arg("files", String, { multiple: true })',
1128
+ " .exec(async function (action, files) {",
1129
+ " process.stdout.write(JSON.stringify([action, files]));",
1130
+ " }),",
1131
+ ' single: target({ desc: "takes one", stdio: true })',
1132
+ ' .arg("action", String, { nullable: true })',
1133
+ ' .option("format", String, { default: "text", enum: ["text", "json"] })',
1134
+ " .exec(async function () {}),",
1135
+ ' bare: target({ desc: "takes none", stdio: true }).exec(async function () {}),',
1101
1136
  "})) {}",
1102
1137
  "await runCommands(CollectCommand);",
1103
1138
  "",
@@ -1110,6 +1145,38 @@ describe("a repeatable option", () => {
1110
1145
  };
1111
1146
  expect(await collect("--param", "a=1", "-p", "b=x=y")).toEqual(["a=1", "b=x=y"]);
1112
1147
  expect(await collect()).toEqual([]);
1148
+
1149
+ const run = async (...args: string[]) => {
1150
+ const proc = Bun.spawn(["bun", entry, ...args], { cwd: root, stdout: "pipe", stderr: "pipe" });
1151
+ const [stdout, stderr, code] = await Promise.all([
1152
+ new Response(proc.stdout).text(),
1153
+ new Response(proc.stderr).text(),
1154
+ proc.exited,
1155
+ ]);
1156
+ return { stdout, stderr, code };
1157
+ };
1158
+ expect((await run("gather", "scan", "a.test.ts", "b.test.ts,c.test.ts")).stdout).toBe(
1159
+ '["scan",["a.test.ts","b.test.ts","c.test.ts"]]',
1160
+ );
1161
+ expect((await run("gather", "scan")).stdout).toBe('["scan",[]]');
1162
+
1163
+ const excess = await run("single", "scan", "web");
1164
+ expect(excess.code).toBe(2);
1165
+ expect(excess.stderr).toBe(
1166
+ [
1167
+ "error: too many arguments for 'single'. Expected 1 argument but got 2: scan, web.",
1168
+ "`akan single` takes [action]: see `akan single --help`.",
1169
+ "",
1170
+ ].join("\n"),
1171
+ );
1172
+ const excessJson = await run("single", "scan", "web", "--format", "json");
1173
+ expect(JSON.parse(excessJson.stdout)).toEqual({
1174
+ ok: false,
1175
+ code: "usage",
1176
+ error:
1177
+ "too many arguments for 'single'. Expected 1 argument but got 2: scan, web. `akan single` takes [action]: see `akan single --help`.",
1178
+ });
1179
+ expect((await run("bare", "web")).stderr).toContain("`akan bare` takes no argument: see `akan bare --help`.");
1113
1180
  }, 30_000);
1114
1181
  });
1115
1182
 
@@ -1,11 +1,22 @@
1
1
  import chalk from "chalk";
2
2
 
3
- import { type EnumChoice, getArgMetas } from "./argMeta";
3
+ import { type ArgMeta, type EnumChoice, getArgMetas, type InternalArgMeta } from "./argMeta";
4
4
  import { camelToKebabCase } from "./camelToKebabCase";
5
5
  import { type CommandCls, getTargetMetas } from "./targetMeta";
6
6
 
7
7
  const formatChoice = (choice: EnumChoice) => (typeof choice === "object" ? choice.label : choice.toString());
8
8
 
9
+ const argumentNameOf = (arg: ArgMeta) => `${camelToKebabCase(arg.name)}${arg.argsOption.multiple ? "..." : ""}`;
10
+
11
+ export const usageArgsOf = (argMetas: (ArgMeta | InternalArgMeta)[]) =>
12
+ argMetas.flatMap((arg) => {
13
+ if (arg.type === "Option" || arg.type === "Workspace") return [];
14
+ if (arg.type === "Module") return ["[sys:module]"];
15
+ if (arg.type === "Apps") return ["[apps...]"];
16
+ if (arg.type === "Argument") return [`[${argumentNameOf(arg)}]`];
17
+ return [`[${arg.type.toLowerCase()}]`];
18
+ });
19
+
9
20
  const groupCommands = (commands: CommandCls[]) => {
10
21
  const groups = new Map<string, { key: string; args: string[]; desc?: string }[]>();
11
22
  for (const command of commands) {
@@ -87,16 +98,7 @@ export const formatCommandHelp = (command: CommandCls, key: string) => {
87
98
  const kebabKey = camelToKebabCase(key);
88
99
  const commandDesc = getTargetMetas(command).find((t) => t.key === key)?.targetOption.desc;
89
100
  const nonOptionArgs = allArgMetas.filter((arg) => arg.type !== "Option");
90
- const args = nonOptionArgs
91
- .map((arg) => {
92
- if (arg.type === "Workspace") return "";
93
- if (arg.type === "Module") return "[sys:module]";
94
- if (arg.type === "Apps") return "[apps...]";
95
- if (arg.type === "Argument") return `[${camelToKebabCase(arg.name)}]`;
96
- return `[${arg.type.toLowerCase()}]`;
97
- })
98
- .filter(Boolean)
99
- .join(" ");
101
+ const args = usageArgsOf(allArgMetas).join(" ");
100
102
 
101
103
  const lines = ["", chalk.bold.cyan(` Command: ${kebabKey}`)];
102
104
  if (commandDesc) lines.push(chalk.gray(` ${commandDesc}`));
@@ -115,7 +117,7 @@ export const formatCommandHelp = (command: CommandCls, key: string) => {
115
117
  let argDesc: string;
116
118
  let example = "";
117
119
  if (arg.type === "Argument") {
118
- argName = camelToKebabCase(arg.name);
120
+ argName = argumentNameOf(arg);
119
121
  argDesc = arg.argsOption.desc ?? "";
120
122
  example = arg.argsOption.example ? chalk.gray(` (e.g., ${String(arg.argsOption.example)})`) : "";
121
123
  } else if (arg.type === "Module") {
@@ -95,9 +95,7 @@ export class SysExecutor extends Executor {
95
95
  this.writeFile(path.join(envDir, fileName), content, { overwrite: false, silent: true }),
96
96
  ),
97
97
  );
98
- this.logger.info(
99
- `${missing.map(({ fileName }) => `env/${fileName}`).join(", ")} were missing (gitignored, so a clone has none) and now hold local defaults: put this machine's values in them, or fetch the team's with \`akan download-env\`.`,
100
- );
98
+ for (const notice of EnvSeed.notices(missing)) this.logger.info(notice);
101
99
  return written;
102
100
  }
103
101
  //? `synced` is the app or lib whose sync this is: a lib's files are written by the sync of each app mounting it.
@@ -155,6 +155,7 @@ describe("DesktopServerStage", () => {
155
155
  ];
156
156
  const imageOnly = [
157
157
  "Dockerfile",
158
+ "Dockerfile.edge",
158
159
  ".dockerignore",
159
160
  "akan.env.json",
160
161
  "package.json",
@@ -4,6 +4,7 @@ import { toError } from "akanjs/common";
4
4
  import type { ServerPolicy } from "akanjs/native/api";
5
5
  import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
6
6
  import type { AkanAppConfig, NativeEnv } from "../akanConfig";
7
+ import { DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
7
8
  import type { App } from "../commandDecorators";
8
9
  import type { PackageJson } from "../workspace/types";
9
10
  import { DesktopBin } from "./desktopBin";
@@ -190,7 +191,7 @@ export class DesktopServerStage {
190
191
  const dist = this.app.dist.cwdPath;
191
192
  await mkdir(this.dir, { recursive: true });
192
193
  for (const name of await readdir(dist))
193
- if (!DesktopServerStage.uncarried.has(name))
194
+ if (!DesktopServerStage.uncarried.has(name) && !name.startsWith(DOCKER_VARIANT_FILE_PREFIX))
194
195
  await cp(path.join(dist, name), path.join(this.dir, name), { recursive: true });
195
196
  const scanInfo = this.app.getScanInfo({ allowEmpty: true }) ?? (await this.app.scan({ write: false }));
196
197
  const carried = [...DesktopBin.select(config, scanInfo.getLibs()).keys()];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.58",
3
+ "version": "3.3.0-rc.59",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.58",
53
+ "@akanjs/language": "3.3.0-rc.59",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.58",
62
+ "akanjs": "3.3.0-rc.59",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { tempDirs, writeText } from "../test/testHelpers";
5
5
  import { EnvSeed } from "./envSeed";
@@ -69,6 +69,35 @@ describe("EnvSeed", () => {
69
69
  expect(await seededIn(envDir)).toEqual({ "env.server.local.ts": example, "env.server.testing.ts": example });
70
70
  });
71
71
 
72
+ test("in a linked worktree, copies the main checkout's file of the same path and seeds only what that lacks", async () => {
73
+ const root = await realpath(await makeEnvDir());
74
+ const main = path.join(root, "main");
75
+ const worktree = path.join(root, "linked");
76
+ const gitDir = path.join(main, ".git/worktrees/linked");
77
+ await writeText(path.join(gitDir, "commondir"), "../..\n");
78
+ await writeText(path.join(worktree, ".git"), `gitdir: ${gitDir}\n`);
79
+ const held =
80
+ 'import type { ModulesOptions } from "../lib/option";\n\nexport const env: ModulesOptions = { port: 7 };\n';
81
+ await writeText(path.join(main, "apps/portal/env/env.server.local.ts"), held);
82
+ const envDir = path.join(worktree, "apps/portal/env");
83
+ await writeText(path.join(envDir, "env.server.ts"), selector("server", ["local"]));
84
+
85
+ const seeded = await new EnvSeed(envDir).missing();
86
+
87
+ expect(seeded).toEqual([
88
+ {
89
+ fileName: "env.server.local.ts",
90
+ content: held,
91
+ copiedFrom: path.join(main, "apps/portal/env/env.server.local.ts"),
92
+ },
93
+ { fileName: "env.server.testing.ts", content: await template("app/env/env.server.testing.ts.template") },
94
+ ]);
95
+ expect(EnvSeed.notices(seeded)).toEqual([
96
+ `env/env.server.local.ts were missing in this worktree (gitignored, so a worktree has none) and now hold a copy of the main checkout's, from ${path.join(main, "apps/portal/env")}: a later change there does not reach the copy.`,
97
+ "env/env.server.testing.ts were missing (gitignored, so a clone has none) and now hold local defaults: put this machine's values in them, or fetch the team's with `akan download-env`.",
98
+ ]);
99
+ });
100
+
72
101
  test("leaves a client env untyped when the folder has no env.client.type.ts to type it", async () => {
73
102
  const envDir = await makeEnvDir();
74
103
  await writeText(path.join(envDir, "env.client.ts"), selector("client", ["local"]));
@@ -1,9 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { FileSys } from "../util/fileSys";
3
+ import { MainCheckout } from "./mainCheckout";
3
4
 
4
5
  export interface EnvSeedFile {
5
6
  fileName: string;
6
7
  content: string;
8
+ /** The main checkout's file the content is a copy of, when the folder is in a linked worktree that has none. */
9
+ copiedFrom?: string;
7
10
  }
8
11
 
9
12
  //? These files are gitignored for the secrets they hold, so a fresh clone has none of them.
@@ -39,7 +42,33 @@ export const env: AppClientEnv = {};
39
42
  const wanted = [...new Set([EnvSeed.#testing, ...(await this.#selected())])].sort();
40
43
  const exists = await Promise.all(wanted.map((fileName) => FileSys.fileExists(path.join(this.#envDir, fileName))));
41
44
  const missing = wanted.filter((_, idx) => !exists[idx]);
42
- return await Promise.all(missing.map(async (fileName) => ({ fileName, content: await this.#contentOf(fileName) })));
45
+ return await Promise.all(missing.map(async (fileName) => await this.#seedOf(fileName)));
46
+ }
47
+
48
+ //? Copied, not linked: a symlinked env file resolves its `../lib/option` import from the main checkout's tree.
49
+ async #seedOf(fileName: string): Promise<EnvSeedFile> {
50
+ const copiedFrom = await MainCheckout.counterpartOf(path.join(this.#envDir, fileName));
51
+ if (copiedFrom) return { fileName, content: await FileSys.readText(copiedFrom), copiedFrom };
52
+ return { fileName, content: await this.#contentOf(fileName) };
53
+ }
54
+
55
+ static notices(seeded: EnvSeedFile[]): string[] {
56
+ const named = (files: EnvSeedFile[]) => files.map(({ fileName }) => `env/${fileName}`).join(", ");
57
+ const copied = seeded.filter((file) => file.copiedFrom !== undefined);
58
+ const defaults = seeded.filter((file) => file.copiedFrom === undefined);
59
+ const source = copied.map(({ copiedFrom }) => copiedFrom).find((file) => file !== undefined);
60
+ return [
61
+ ...(source
62
+ ? [
63
+ `${named(copied)} were missing in this worktree (gitignored, so a worktree has none) and now hold a copy of the main checkout's, from ${path.dirname(source)}: a later change there does not reach the copy.`,
64
+ ]
65
+ : []),
66
+ ...(defaults.length
67
+ ? [
68
+ `${named(defaults)} were missing (gitignored, so a clone has none) and now hold local defaults: put this machine's values in them, or fetch the team's with \`akan download-env\`.`,
69
+ ]
70
+ : []),
71
+ ];
43
72
  }
44
73
 
45
74
  async #selected() {
@@ -0,0 +1,55 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs, writeText } from "../test/testHelpers";
5
+ import { MainCheckout } from "./mainCheckout";
6
+
7
+ const makeRoot = tempDirs("akan-main-checkout-");
8
+
9
+ const git = async (cwd: string, ...args: string[]) => {
10
+ const identity = ["-c", "user.name=akan", "-c", "user.email=akan@example.com", "-c", "commit.gpgsign=false"];
11
+ const proc = Bun.spawn(["git", ...identity, ...args], { cwd, stdout: "ignore", stderr: "pipe" });
12
+ if ((await proc.exited) !== 0) throw new Error(await new Response(proc.stderr).text());
13
+ };
14
+
15
+ const makeWorktree = async () => {
16
+ const root = await realpath(await makeRoot());
17
+ const main = path.join(root, "main");
18
+ const worktree = path.join(root, "linked");
19
+ await mkdir(main);
20
+ await git(main, "init", "-q", "-b", "main");
21
+ await git(main, "commit", "-q", "--allow-empty", "-m", "init");
22
+ await git(main, "worktree", "add", "-q", worktree, "-b", "linked");
23
+ return { main, worktree };
24
+ };
25
+
26
+ describe("MainCheckout", () => {
27
+ test("finds the main checkout from any folder of a linked worktree, and none from the main checkout itself", async () => {
28
+ const { main, worktree } = await makeWorktree();
29
+ await mkdir(path.join(worktree, "apps/portal/env"), { recursive: true });
30
+
31
+ expect(await MainCheckout.rootsOf(path.join(worktree, "apps/portal/env"))).toEqual({ worktree, main });
32
+ expect(await MainCheckout.rootsOf(worktree)).toEqual({ worktree, main });
33
+ expect(await MainCheckout.rootsOf(main)).toBeNull();
34
+ });
35
+
36
+ test("names the main checkout's file of the same path only when it is there", async () => {
37
+ const { main, worktree } = await makeWorktree();
38
+ await writeText(path.join(main, "apps/portal/env/env.server.local.ts"), "export const env = {};\n");
39
+
40
+ expect(await MainCheckout.counterpartOf(path.join(worktree, "apps/portal/env/env.server.local.ts"))).toBe(
41
+ path.join(main, "apps/portal/env/env.server.local.ts"),
42
+ );
43
+ expect(await MainCheckout.counterpartOf(path.join(worktree, "apps/portal/env/env.server.debug.ts"))).toBeNull();
44
+ });
45
+
46
+ test("takes a folder under no repository, and a submodule's .git file, for no linked worktree", async () => {
47
+ const root = await realpath(await makeRoot());
48
+ const submodule = path.join(root, "vendor");
49
+ await mkdir(path.join(root, "modules/vendor"), { recursive: true });
50
+ await writeText(path.join(submodule, ".git"), "gitdir: ../modules/vendor\n");
51
+
52
+ expect(await MainCheckout.rootsOf(path.join(root, "nowhere"))).toBeNull();
53
+ expect(await MainCheckout.rootsOf(submodule)).toBeNull();
54
+ });
55
+ });
@@ -0,0 +1,38 @@
1
+ import path from "node:path";
2
+ import { FileSys } from "../util/fileSys";
3
+
4
+ export interface LinkedWorktree {
5
+ worktree: string;
6
+ main: string;
7
+ }
8
+
9
+ export class MainCheckout {
10
+ //? A linked worktree's `.git` is a file naming its gitdir, whose `commondir` names the main checkout's `.git`.
11
+ //? A submodule's `.git` is a file too, with no `commondir`, and a bare repository has no checkout beside it.
12
+ static async rootsOf(dir: string): Promise<LinkedWorktree | null> {
13
+ const worktree = await MainCheckout.#nearestRepo(path.resolve(dir));
14
+ if (!worktree) return null;
15
+ const dotGit = path.join(worktree, ".git");
16
+ if (!(await FileSys.fileExists(dotGit))) return null;
17
+ const named = (await FileSys.readText(dotGit)).match(/^gitdir: (.+)$/m)?.[1]?.trim();
18
+ if (!named) return null;
19
+ const gitDir = path.resolve(worktree, named);
20
+ const commonDirFile = path.join(gitDir, "commondir");
21
+ if (!(await FileSys.fileExists(commonDirFile))) return null;
22
+ const commonDir = path.resolve(gitDir, (await FileSys.readText(commonDirFile)).trim());
23
+ return path.basename(commonDir) === ".git" ? { worktree, main: path.dirname(commonDir) } : null;
24
+ }
25
+
26
+ static async counterpartOf(file: string): Promise<string | null> {
27
+ const roots = await MainCheckout.rootsOf(path.dirname(file));
28
+ if (!roots) return null;
29
+ const counterpart = path.join(roots.main, path.relative(roots.worktree, path.resolve(file)));
30
+ return (await FileSys.fileExists(counterpart)) ? counterpart : null;
31
+ }
32
+
33
+ static async #nearestRepo(dir: string): Promise<string | null> {
34
+ if (await FileSys.exists(path.join(dir, ".git"))) return dir;
35
+ const parent = path.dirname(dir);
36
+ return parent === dir ? null : await MainCheckout.#nearestRepo(parent);
37
+ }
38
+ }