@akanjs/devkit 3.3.0-rc.70 → 3.3.0-rc.71

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.
@@ -18,6 +18,7 @@ import {
18
18
  dockerfileLayoutOf,
19
19
  dockerfileOf,
20
20
  dockerfileSections,
21
+ dockerProfilesOf,
21
22
  } from "./dockerImage";
22
23
  import type { LibConfigInput } from "./types";
23
24
 
@@ -517,6 +518,43 @@ describe("AkanAppConfig", () => {
517
518
  expect(configOf("FROM scratch").dockerVariants).toEqual({});
518
519
  });
519
520
 
521
+ test("a variant's profile becomes its AKAN_ENV_PROFILE line and one of the profiles an image build carries", () => {
522
+ const configOf = (docker: string | object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
523
+ const config = configOf({
524
+ env: { EDGE_MODE: "camera" },
525
+ variants: {
526
+ edge: { profile: "edge", env: { AKAN_PUBLIC_OPERATION_MODE: "edge" } },
527
+ kiosk: { profile: "edge" },
528
+ desk: { profile: "desk" },
529
+ plain: {},
530
+ },
531
+ });
532
+ expect(dockerProfilesOf(config.dockerVariants)).toEqual(["edge", "desk"]);
533
+ expect(config.dockerVariants.edge.env).toEqual({
534
+ EDGE_MODE: "camera",
535
+ AKAN_PUBLIC_OPERATION_MODE: "edge",
536
+ AKAN_ENV_PROFILE: "edge",
537
+ });
538
+ expect(config.dockerfileFor("main", { variant: "edge" })).toContain("ENV AKAN_ENV_PROFILE=edge\n");
539
+ expect(config.dockerfileFor("main", { variant: "plain" })).not.toContain("AKAN_ENV_PROFILE");
540
+ expect(config.dockerfileFor("main")).not.toContain("AKAN_ENV_PROFILE");
541
+ expect(dockerProfilesOf(configOf({}).dockerVariants)).toEqual([]);
542
+ expect(dockerProfilesOf(configOf("FROM scratch").dockerVariants)).toEqual([]);
543
+ });
544
+
545
+ test("refuses a profile that is no profile name, and AKAN_ENV_PROFILE set as a plain env line", () => {
546
+ const configOf = (docker: string | object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
547
+ expect(() => configOf({ variants: { edge: { profile: "Edge Box" } } })).toThrow(
548
+ 'docker.variants.edge.profile is "Edge Box", which is not a server env profile name',
549
+ );
550
+ expect(() => configOf({ env: { AKAN_ENV_PROFILE: "edge" } })).toThrow(
551
+ "docker.env sets AKAN_ENV_PROFILE, which the build has to know to carry the profile: name it as docker.variants.<name>.profile",
552
+ );
553
+ expect(() => configOf({ variants: { edge: { env: { AKAN_ENV_PROFILE: "edge" } } } })).toThrow(
554
+ "docker.variants.edge.env sets AKAN_ENV_PROFILE",
555
+ );
556
+ });
557
+
520
558
  test("opens the Dockerfile with its format and marks each section it wrote, so a tool finds one without matching its instructions", () => {
521
559
  const plain = dockerfileLayoutOf(new AkanAppConfig(app, [], packageJson, {}, baseDevEnv).dockerfile);
522
560
  expect(plain?.format).toBe(DOCKERFILE_FORMAT);
@@ -1,3 +1,4 @@
1
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
1
2
  import {
2
3
  type Arch,
3
4
  archs,
@@ -206,9 +207,20 @@ const resolveDockerImage = (
206
207
  };
207
208
  };
208
209
 
210
+ //? A build carries a profile only when a variant names it; set as a plain `ENV`, the server would refuse to start.
211
+ const assertProfileNamed = (env: Record<string, string> | undefined, owner: string) => {
212
+ if (env && EnvProfile.key in env)
213
+ throw new Error(
214
+ `[docker] ${owner}.env sets ${EnvProfile.key}, which the build has to know to carry the profile: name it as docker.variants.<name>.profile`,
215
+ );
216
+ };
217
+
209
218
  /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
210
- export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig =>
211
- typeof docker === "string" ? docker : resolveDockerImage(docker ?? {}, libDocker, "docker");
219
+ export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig => {
220
+ if (typeof docker === "string") return docker;
221
+ assertProfileNamed(docker?.env, "docker");
222
+ return resolveDockerImage(docker ?? {}, libDocker, "docker");
223
+ };
212
224
 
213
225
  export const resolveDockerVariants = (
214
226
  docker: DockerOption | undefined,
@@ -217,13 +229,22 @@ export const resolveDockerVariants = (
217
229
  if (typeof docker === "string" || !docker?.variants) return {};
218
230
  const { variants, ...base } = docker;
219
231
  return Object.fromEntries(
220
- Object.entries(variants).map(([name, variant]) => {
232
+ Object.entries(variants).map(([name, { profile, ...variant }]) => {
221
233
  if (!dockerVariantNamePattern.test(name))
222
234
  throw new Error(
223
235
  `[docker] docker.variants names "${name}", which cannot end a file name: use lowercase letters, digits and "-"`,
224
236
  );
225
- const env = { ...base.env, ...variant.env };
237
+ assertProfileNamed(variant.env, `docker.variants.${name}`);
238
+ if (profile !== undefined && !EnvProfile.namePattern.test(profile))
239
+ throw new Error(
240
+ `[docker] docker.variants.${name}.profile is "${profile}", which is not a server env profile name: a lowercase-first name of letters, digits and dashes`,
241
+ );
242
+ const env = { ...base.env, ...variant.env, ...(profile ? { [EnvProfile.key]: profile } : {}) };
226
243
  return [name, resolveDockerImage({ ...base, ...variant, env }, libDocker, `docker.variants.${name}`)];
227
244
  }),
228
245
  );
229
246
  };
247
+
248
+ export const dockerProfilesOf = (variants: Record<string, DockerImageConfig>): string[] => [
249
+ ...new Set(Object.values(variants).flatMap(({ env }) => (env[EnvProfile.key] ? [env[EnvProfile.key]] : []))),
250
+ ];
@@ -127,6 +127,36 @@ console.info(new SampleService().name);
127
127
  }
128
128
  });
129
129
 
130
+ test("a variant on an env profile names it and asks for none of the secret env values the image's own lists", async () => {
131
+ const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
132
+ const config = new AkanAppConfig(
133
+ { name: "portal" } as never,
134
+ [],
135
+ { name: "repo", version: "1.0.0", description: "repo" },
136
+ { docker: { variants: { edge: { profile: "edge" }, mirror: {} } } },
137
+ { repoName: "akanjs", serveDomain: "akanjs.com", env: "local", portOffset: 0, workspaceRoot: root },
138
+ );
139
+ const app = {
140
+ getConfig: async () => config,
141
+ getScanInfo: () => ({ getLibs: () => [] }),
142
+ dist: new Executor("dist", root),
143
+ workspace: { workspaceRoot: root },
144
+ logger: { warn: () => undefined },
145
+ } as unknown as App;
146
+ const runner = new ApplicationBuildRunner(app, { environment: "debug" });
147
+ try {
148
+ await runner.buildAppMeta();
149
+ const [image, edge, mirror] = await Promise.all(
150
+ ["Dockerfile", "Dockerfile.edge", "Dockerfile.mirror"].map((name) => readFile(path.join(root, name), "utf8")),
151
+ );
152
+ expect(edge).toContain("ENV AKAN_ENV_PROFILE=edge\n");
153
+ expect(image).not.toContain("AKAN_ENV_PROFILE");
154
+ expect(mirror).toBe(image);
155
+ } finally {
156
+ await rm(root, { recursive: true, force: true });
157
+ }
158
+ });
159
+
130
160
  test("writes beside main.js the env its Dockerfile sets, so a host without the image runs the build as is", async () => {
131
161
  const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
132
162
  const config = new AkanAppConfig(
@@ -204,18 +234,70 @@ console.info(new SampleService().name);
204
234
  return env;
205
235
  };
206
236
  const names =
207
- "JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,MAILER__AUTH__PASS,OBJECT_STORAGE__ENDPOINT,DISCORD__TOKENS:json,DISCORD__WEBHOOK,PUSH_NOTI__FIREBASE__PRIVATE_KEY:multiline,MESSAGE__API_SECRET,MESSAGE__SENDER_PASSWORD,POSTGRES_URL";
237
+ "JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,MAILER__AUTH__PASS,OBJECT_STORAGE__ENDPOINT,DISCORD__TOKENS:json,DISCORD__WEBHOOK,PUSH_NOTI__FIREBASE__PRIVATE_KEY:multiline,MESSAGE__API_SECRET,MESSAGE__SENDER_PASSWORD,POSTGRES_URL|DATABASE_URL";
208
238
  try {
209
- const read = await metaOf({ secretEnv: "read" });
210
- expect(read.AKAN_ENV_NAMES).toBe(names);
211
- expect(read).not.toHaveProperty("AKAN_ENV_FALLBACK");
212
- expect(await metaOf({ secretEnv: "inline" })).toMatchObject({
213
- AKAN_ENV_NAMES: names,
214
- AKAN_ENV_FALLBACK: "image",
215
- });
216
- const carried = await metaOf({});
217
- expect(carried).not.toHaveProperty("AKAN_ENV_NAMES");
218
- expect(carried).not.toHaveProperty("AKAN_ENV_FALLBACK");
239
+ expect((await metaOf({ secretEnv: "read" })).AKAN_ENV_NAMES).toBe(names);
240
+ expect(await metaOf({})).not.toHaveProperty("AKAN_ENV_NAMES");
241
+ } finally {
242
+ for (const key of keys) {
243
+ if (shellEnv[key] === undefined) delete process.env[key];
244
+ else process.env[key] = shellEnv[key];
245
+ }
246
+ await rm(root, { recursive: true, force: true });
247
+ }
248
+ });
249
+
250
+ test("an image build checks each profile its variants name before any phase, and that variant's Dockerfile lists no secret env name", async () => {
251
+ const { root, workspace } = await createTempApp("portal");
252
+ await writeSecretEnvFixture(root, { app: "portal" });
253
+ await writeFile(
254
+ path.join(root, "apps/portal/akan.config.ts"),
255
+ 'export default { docker: { variants: { edge: { profile: "edge" } } } };\n',
256
+ );
257
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
258
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
259
+ for (const key of keys) delete process.env[key];
260
+ await writeFile(
261
+ path.join(root, ".env"),
262
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
263
+ );
264
+ const started = async (options: ConstructorParameters<typeof ApplicationBuildRunner>[1]) => {
265
+ const app = AppExecutor.from(workspace, "portal");
266
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
267
+ app.prepareCommand = async () => {
268
+ throw new Error("stopped before the phases");
269
+ };
270
+ const runner = new ApplicationBuildRunner(app, options);
271
+ const failure = await runner.build().then(
272
+ () => "",
273
+ (error: Error) => error.message,
274
+ );
275
+ return { app, runner, failure };
276
+ };
277
+ const profileFile = path.join(root, "apps/portal/env/env.server.main.edge.ts");
278
+ try {
279
+ expect((await started({ secretEnv: "read" })).failure).toContain(
280
+ 'The server env profile "edge" bundles env/env.server.main.edge.ts',
281
+ );
282
+ expect((await started({})).failure).toBe("stopped before the phases");
283
+
284
+ await writeFile(profileFile, 'export const env = { mailer: { auth: { pass: "sentinel-edge-pass" } } };\n');
285
+ const secret = await started({ secretEnv: "read" });
286
+ expect(secret.failure).toContain("env/env.server.main.edge.ts holds secret-named values");
287
+ expect(secret.failure).not.toContain("sentinel-edge-pass");
288
+
289
+ await writeFile(profileFile, 'export const env = { hostname: "edge-host" };\n');
290
+ const { app, runner, failure } = await started({ secretEnv: "read" });
291
+ expect(failure).toBe("stopped before the phases");
292
+ await runner.buildAppMeta();
293
+ const [image, edge] = await Promise.all(
294
+ ["Dockerfile", "Dockerfile.edge"].map((name) => readFile(path.join(app.dist.cwdPath, name), "utf8")),
295
+ );
296
+ expect(image).toContain("ENV AKAN_ENV_NAMES=JWT_SECRET,");
297
+ expect(image).not.toContain("AKAN_ENV_PROFILE");
298
+ expect(edge).toContain("ENV AKAN_ENV_PROFILE=edge\n");
299
+ expect(edge).not.toContain("AKAN_ENV_NAMES");
300
+ expect(edge.replace("ENV AKAN_ENV_PROFILE=edge\n", "")).toBe(image.replace(/ENV AKAN_ENV_NAMES=.*\n/, ""));
219
301
  } finally {
220
302
  for (const key of keys) {
221
303
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -257,7 +339,7 @@ console.info(new SampleService().name);
257
339
  }
258
340
  });
259
341
 
260
- test("an env file that needs a variable of the shell to load builds with it set; without it a build stops at the place, and an --inline-secrets build warns and holds the env as written", async () => {
342
+ test("an env file that needs a variable of the shell to load builds with it set; without it a build stops at the place", async () => {
261
343
  const { root, workspace } = await createTempApp("portal");
262
344
  await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n hosts: process.env.ZQ_HOSTS!.split(","),' });
263
345
  const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN", "ZQ_HOSTS"] as const;
@@ -267,7 +349,7 @@ console.info(new SampleService().name);
267
349
  path.join(root, ".env"),
268
350
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
269
351
  );
270
- const started = async (secretEnv: "read" | "inline") => {
352
+ const started = async () => {
271
353
  const app = AppExecutor.from(workspace, "portal");
272
354
  const warnings: string[] = [];
273
355
  spyOn(app.logger, "warn").mockImplementation((message: string) => {
@@ -276,7 +358,7 @@ console.info(new SampleService().name);
276
358
  app.prepareCommand = async () => {
277
359
  throw new Error("stopped before the phases");
278
360
  };
279
- const runner = new ApplicationBuildRunner(app, { secretEnv });
361
+ const runner = new ApplicationBuildRunner(app, { secretEnv: "read" });
280
362
  const failure = await runner.build().then(
281
363
  () => "",
282
364
  (error: Error) => error.message,
@@ -292,23 +374,16 @@ console.info(new SampleService().name);
292
374
  const place =
293
375
  /env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+/;
294
376
  try {
295
- const stopped = await started("read");
377
+ const stopped = await started();
296
378
  expect(stopped.failure).toMatch(place);
297
- expect(stopped.failure).toContain("Make the file load at that line");
379
+ expect(stopped.failure).toEndWith(
380
+ "by setting the variable it reads there in this shell or giving it a fallback, and build again.",
381
+ );
382
+ expect(stopped.warnings).toEqual([]);
298
383
  expect(holdsSentinel(stopped.failure)).toBe(false);
299
384
 
300
- const inlined = await started("inline");
301
- expect(inlined.failure).toBe("stopped before the phases");
302
- expect(inlined.warnings).toHaveLength(1);
303
- expect(inlined.warnings[0]).toMatch(place);
304
- expect(inlined.warnings[0]).toStartWith("--inline-secrets: env.server.ts could not be evaluated");
305
- expect(holdsSentinel(inlined.warnings.join())).toBe(false);
306
- const written = await envOf(inlined);
307
- expect(written).not.toHaveProperty("AKAN_ENV_NAMES");
308
- expect(written).not.toHaveProperty("AKAN_ENV_FALLBACK");
309
-
310
385
  process.env.ZQ_HOSTS = "a.example.test,b.example.test";
311
- const built = await started("read");
386
+ const built = await started();
312
387
  expect(built.failure).toBe("stopped before the phases");
313
388
  expect((await envOf(built)).AKAN_ENV_NAMES).toStartWith("JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,");
314
389
  } finally {
@@ -330,7 +405,7 @@ console.info(new SampleService().name);
330
405
  path.join(root, ".env"),
331
406
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
332
407
  );
333
- const started = async (secretEnv: "read" | "inline") => {
408
+ const started = async () => {
334
409
  const app = AppExecutor.from(workspace, "portal");
335
410
  spyOn(app.logger, "warn").mockImplementation(() => undefined);
336
411
  let prepared = false;
@@ -338,23 +413,20 @@ console.info(new SampleService().name);
338
413
  prepared = true;
339
414
  throw new Error("stopped before the phases");
340
415
  };
341
- const failure = await new ApplicationBuildRunner(app, { secretEnv }).build().then(
416
+ const failure = await new ApplicationBuildRunner(app, { secretEnv: "read" }).build().then(
342
417
  () => "",
343
418
  (error: Error) => error.message,
344
419
  );
345
420
  return { failure, prepared: () => prepared };
346
421
  };
347
422
  try {
348
- const stopped = await started("read");
423
+ const stopped = await started();
349
424
  expect(stopped.prepared()).toBe(false);
350
425
  expect(stopped.failure).toStartWith(
351
426
  `The server env of portal (main) holds 4 secret values this build cannot leave out, so it stops here: ${computedSecretKeys.join(", ")} (apps/portal/env/env.server.ts and what it imports).\n`,
352
427
  );
353
428
  expect(holdsSentinel(stopped.failure)).toBe(false);
354
429
  for (const value of Object.values(computedSecrets)) expect(stopped.failure).not.toContain(value);
355
- const inlined = await started("inline");
356
- expect(inlined.prepared()).toBe(true);
357
- expect(inlined.failure).toBe("stopped before the phases");
358
430
  } finally {
359
431
  for (const key of keys) {
360
432
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -374,7 +446,7 @@ console.info(new SampleService().name);
374
446
  path.join(root, ".env"),
375
447
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
376
448
  );
377
- const runnerOf = async (secretEnv: "read" | "inline") => {
449
+ const runnerOf = async () => {
378
450
  const app = AppExecutor.from(workspace, "portal");
379
451
  const warnings: string[] = [];
380
452
  spyOn(app.logger, "warn").mockImplementation((message: string) => {
@@ -383,12 +455,12 @@ console.info(new SampleService().name);
383
455
  app.prepareCommand = async () => {
384
456
  throw new Error("stopped before the phases");
385
457
  };
386
- const runner = new ApplicationBuildRunner(app, { secretEnv });
458
+ const runner = new ApplicationBuildRunner(app, { secretEnv: "read" });
387
459
  await expect(runner.build()).rejects.toThrow("stopped before the phases");
388
460
  return { app, runner, warnings };
389
461
  };
390
462
  try {
391
- const { app, runner, warnings } = await runnerOf("read");
463
+ const { app, runner, warnings } = await runnerOf();
392
464
  await mkdir(app.dist.cwdPath, { recursive: true });
393
465
  await writeFile(path.join(app.dist.cwdPath, "server.js"), 'const env = { hostname: "app.example.test" };\n');
394
466
  await runner.assertSecretsLeftOut();
@@ -420,9 +492,6 @@ console.info(new SampleService().name);
420
492
  ].join("\n"),
421
493
  );
422
494
  expect(holdsSentinel(failure)).toBe(false);
423
- const inlined = await runnerOf("inline");
424
- await inlined.runner.assertSecretsLeftOut();
425
- expect(inlined.warnings.join("\n")).not.toContain("also in what this build wrote");
426
495
  } finally {
427
496
  for (const key of keys) {
428
497
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -2,10 +2,11 @@ import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
3
  import { AppWorkerPath } from "akanjs/server/appWorkerPath";
4
4
  import { BUILD_ENV_FILE, BUILD_ENV_MODULE } from "akanjs/server/lifecycle/buildEnv";
5
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
5
6
  import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
7
  import type { BunPlugin } from "bun";
7
8
  import { AkanBin } from "../akanConfig/akanBin";
8
- import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
9
+ import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX, dockerProfilesOf } from "../akanConfig/dockerImage";
9
10
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
10
11
  import type { App } from "../commandDecorators";
11
12
  import { LibExecutor, parseEnvFile, WorkspaceExecutor } from "../executors";
@@ -76,10 +77,9 @@ export interface ApplicationBuildRunnerOptions {
76
77
  profile?: string;
77
78
  /**
78
79
  * An image build's: `read` leaves the server env's secret strings out of the server, which reads each from its process
79
- * env, and `inline` keeps them in it as what an unset variable falls back to. Unset, as for the server a desktop app
80
- * carries, or under a `profile`, the env files are bundled as written.
80
+ * env. Unset, as for the server a desktop app carries, or under a `profile`, the env files are bundled as written.
81
81
  */
82
- secretEnv?: "read" | "inline";
82
+ secretEnv?: "read";
83
83
  /**
84
84
  * `enforce` fails on an overage, a route with no entry, or a missing or unreadable akan.budget.json; `update` and
85
85
  * `raise` rewrite the file first; `report` only warns.
@@ -132,7 +132,7 @@ export class ApplicationBuildRunner {
132
132
  #reporter?: BuildProgressReporter;
133
133
  #environment?: string;
134
134
  #profile?: string;
135
- #secretEnv?: "read" | "inline";
135
+ #secretEnv?: "read";
136
136
  #secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
137
137
  #budget: RouteJsBudgetMode;
138
138
  #modulesByRoute?: Record<string, string[]>;
@@ -194,13 +194,14 @@ export class ApplicationBuildRunner {
194
194
  this.#spinner = spinner && process.stderr.isTTY;
195
195
  if (spinner && !this.#spinner) this.#reporter ??= ApplicationBuildReporter.create();
196
196
  if (this.#verify) this.#app.useVerifyDist();
197
- const { web, assets, baseDevEnv } = await this.#app.getConfig();
197
+ const { web, assets, baseDevEnv, dockerVariants } = await this.#app.getConfig();
198
198
  const environment = this.#environment ?? baseDevEnv.env;
199
199
  WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
200
200
  this.#pinImageEnv(baseDevEnv, environment);
201
+ if (this.#secretEnv) this.#carriedProfiles = dockerProfilesOf(dockerVariants);
201
202
  //? Before any phase: a profile that would ship a secret stops the build, not the image after it.
202
- if (this.#profile)
203
- await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile: this.#profile });
203
+ for (const profile of this.#profile ? [this.#profile] : this.#carriedProfiles)
204
+ await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile });
204
205
  if (this.#secretEnv) await this.#declareSecrets(environment);
205
206
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
206
207
  if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
@@ -228,12 +229,10 @@ export class ApplicationBuildRunner {
228
229
  ? "skipped"
229
230
  : "disabled by akan.config.ts web.ssr",
230
231
  );
231
- const leftOut = ServerEnvProfile.leftOutNotice(
232
- this.#profile ?? "",
233
- this.#app.workspace.workspaceRoot,
234
- this.#libEnvsLeftOut,
235
- );
236
- if (leftOut) this.#app.logger.warn(leftOut);
232
+ for (const [profile, libEnvs] of this.#libEnvsLeftOut) {
233
+ const leftOut = ServerEnvProfile.leftOutNotice(profile, this.#app.workspace.workspaceRoot, libEnvs);
234
+ if (leftOut) this.#app.logger.debug(leftOut);
235
+ }
237
236
  if (this.#verify) {
238
237
  const routeJs = await this.#runBudgetPhase(environment);
239
238
  await this.#app.dist.writeJson(
@@ -274,24 +273,17 @@ export class ApplicationBuildRunner {
274
273
  return this.#resultOf(environment, routeJs);
275
274
  }
276
275
 
277
- //* A build that cannot load the env file cannot say what it left out, so it stops; under --inline-secrets, which
278
- //* leaves nothing out, it goes on as a build without the setting does.
279
276
  async #declareSecrets(environment: string) {
280
277
  try {
281
278
  this.#secrets = await SecretEnvDeclaration.of(this.#envDir, environment);
282
279
  } catch (error) {
283
280
  if (!(error instanceof ServerEnvEvaluationError)) throw error;
284
- if (this.#secretEnv === "read")
285
- throw new Error(
286
- `${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
287
- );
288
- this.#app.logger.warn(
289
- `--inline-secrets: ${error.message}. The secret values of the server env could not be listed, so this build holds the env files as written: the server reads no secret from a variable of its process env, and names none at boot.`,
281
+ throw new Error(
282
+ `${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again.`,
290
283
  );
291
- this.#secretEnv = undefined;
292
284
  }
293
285
  //? Before any phase, and by the env's value alone: a search of the files written misses a short or a plain one.
294
- if (this.#secretEnv === "read" && this.#secrets.unmoved.length)
286
+ if (this.#secrets.unmoved.length)
295
287
  throw new Error(
296
288
  SecretEnvFile.unmovedStop(
297
289
  this.#app.name,
@@ -306,7 +298,7 @@ export class ApplicationBuildRunner {
306
298
 
307
299
  //? Before the metadata phase: a build that still holds a secret gets no Dockerfile to build an image from.
308
300
  async assertSecretsLeftOut() {
309
- if (this.#secretEnv !== "read" || !this.#secrets.moved.length) return;
301
+ if (!this.#secretEnv || !this.#secrets.moved.length) return;
310
302
  const { workspaceRoot } = this.#app.workspace;
311
303
  const note = await new ServerBundleSecrets(workspaceRoot, this.#app.cwdPath).assertImageClean(
312
304
  this.#app.dist.cwdPath,
@@ -320,13 +312,13 @@ export class ApplicationBuildRunner {
320
312
  const { logger, name } = this.#app;
321
313
  const names = variables.map((variable) => variable.name).join(", ");
322
314
  const count = `${variables.length} secret value${variables.length === 1 ? "" : "s"}`;
323
- if (variables.length && this.#secretEnv === "inline")
324
- logger.warn(
325
- `--inline-secrets keeps ${count} of the server env in this build, where whoever can read the image reads them: ${names}. A variable the deployment sets still wins over the built-in value. akanjs 3.5.0 removes the flag: set them where the server is deployed and build without it.`,
315
+ if (this.#carriedProfiles.length)
316
+ logger.info(
317
+ `The server also carries the env ${this.#carriedProfiles.length === 1 ? "profile" : "profiles"} ${this.#carriedProfiles.join(", ")}: ${EnvProfile.key}=<name> starts it on env/env.server.${environment}.<name>.ts, which reads no secret value.`,
326
318
  );
327
- else if (variables.length)
319
+ if (variables.length)
328
320
  logger.info(
329
- `The server reads ${count} from its process env when it starts, not from this build: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
321
+ `The server reads ${count} from its process env when it starts, not from this build, and does not start while one is unset: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
330
322
  );
331
323
  }
332
324
 
@@ -451,7 +443,14 @@ export class ApplicationBuildRunner {
451
443
  ...variants.map((variant) =>
452
444
  dist.writeFile(
453
445
  `${dist.cwdPath}/${DOCKER_VARIANT_FILE_PREFIX}${variant}`,
454
- akanConfig.dockerfileFor(environment, { ...imageParts, variant }),
446
+ akanConfig.dockerfileFor(environment, {
447
+ ...imageParts,
448
+ //? A variant on a profile reads none of the names, so its Dockerfile asks a deployment for none.
449
+ ...(EnvProfile.key in akanConfig.dockerVariants[variant].env
450
+ ? { env: Object.fromEntries(Object.entries(imageParts.env).filter(([key]) => key !== SecretEnv.listKey)) }
451
+ : {}),
452
+ variant,
453
+ }),
455
454
  silent,
456
455
  ),
457
456
  ),
@@ -464,10 +463,7 @@ export class ApplicationBuildRunner {
464
463
  //? Names and kinds alone: the image carries the list of what its deployment owes, never a value.
465
464
  #secretEnvList(): Record<string, string> {
466
465
  if (!this.#secrets.variables.length) return {};
467
- return {
468
- [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables),
469
- ...(this.#secretEnv === "inline" ? { [SecretEnv.fallbackKey]: "image" } : {}),
470
- };
466
+ return { [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables) };
471
467
  }
472
468
 
473
469
  async #pruneLockfile(packageJson: PackageJson): Promise<string | null> {
@@ -497,7 +493,8 @@ export class ApplicationBuildRunner {
497
493
  }
498
494
 
499
495
  #serverEnv: BunPlugin | null = null;
500
- #libEnvsLeftOut = new Map<string, string[]>();
496
+ #carriedProfiles: string[] = [];
497
+ #libEnvsLeftOut = new Map<string, Map<string, string[]>>();
501
498
  //? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
502
499
  #serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
503
500
  this.#serverEnv ??= createServerEnvPlugin({
@@ -505,9 +502,12 @@ export class ApplicationBuildRunner {
505
502
  environment: this.#environment ?? baseEnv,
506
503
  environments: ["local", "testing", ...branches],
507
504
  profile: this.#profile,
505
+ profiles: this.#carriedProfiles,
508
506
  secrets: this.#secretEnv,
509
- onLibEnv: (file, { profileFile, stripped }) => {
510
- if (!profileFile && stripped.length) this.#libEnvsLeftOut.set(file, stripped);
507
+ onLibEnv: (file, { profile, profileFile, stripped }) => {
508
+ if (profileFile || !stripped.length) return;
509
+ const libEnvs = this.#libEnvsLeftOut.get(profile) ?? new Map<string, string[]>();
510
+ this.#libEnvsLeftOut.set(profile, libEnvs.set(file, stripped));
511
511
  },
512
512
  });
513
513
  return this.#serverEnv;
@@ -532,8 +532,13 @@ export class ApplicationBuildRunner {
532
532
  target: "bun",
533
533
  minify: AKAN_BACKEND_MINIFY,
534
534
  naming: { entry: "[name].[ext]", chunk: "chunk-[hash].[ext]" },
535
- // `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
536
- define: { "process.env.NODE_ENV": JSON.stringify("production") },
535
+ define: {
536
+ // `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
537
+ "process.env.NODE_ENV": JSON.stringify("production"),
538
+ [`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(
539
+ EnvProfile.format(this.#profile ? [this.#profile] : this.#carriedProfiles),
540
+ ),
541
+ },
537
542
  } satisfies Omit<Bun.BuildConfig, "entrypoints">;
538
543
  const serverEnvPlugin = this.#serverEnvPlugin(baseDevEnv.env, branches);
539
544
  const backendConfig = {
@@ -38,7 +38,8 @@ the agent guide's Path Rules table.
38
38
  - `akan secret-env <app> --env <env>` prints the variables, never a value. `--out <file> --format k8s --name <name>`
39
39
  writes a Kubernetes Secret for `envFrom`, `--format dotenv` a file for `bun --env-file`. Never write it
40
40
  under `dist/` or a tracked path, and delete it once applied.
41
- - At boot a variable left unset is one warning naming it. The framework does not stop for it, though whatever reads the value may; 3.5.0 will refuse to boot.
41
+ - A server with one of them unset exits at boot, naming each: set them before the image rolls out. Images built
42
+ before 3.3.0 still hold the values: rotate them.
42
43
  - A secret the env file computes or imports stops the build, whatever its length: write the string at the key, or
43
44
  `process.env.<NAME>` there, which the build leaves as that read. A secret string a plain key or the app's code
44
45
  holds as well stops it too when long and mixed, and is a warning when short. A key the name rule misses
@@ -46,7 +47,6 @@ the agent guide's Path Rules table.
46
47
  - The build loads the env file to list the secrets, with the shell's variables only when it cannot load without
47
48
  them; a file that throws as it loads stops the build by error class and line.
48
49
  - `akan start`, `akan test`, `akan build --profile …` and desktop and mobile builds read the env file as written.
49
- `akan build --inline-secrets` keeps the values in the image for one release, for a deployment not ready yet.
50
50
 
51
51
  ## Native and desktop
52
52
 
@@ -1,5 +1,9 @@
1
+ import { existsSync, readFileSync } from "node:fs";
1
2
  import os from "node:os";
2
3
  import path from "node:path";
4
+ import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
5
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
+ import { SecretEnvDeclaration } from "../transforms/secretEnvDeclaration";
3
7
 
4
8
  export type DevResourceRole = "host" | "builder" | "batch" | "gateway" | "replica" | "rsc" | "other";
5
9
 
@@ -207,6 +211,16 @@ export class DevResourceProbe {
207
211
  return [...kept.values()].filter((proc) => proc.role !== "other" || proc.pid === rootPid);
208
212
  }
209
213
 
214
+ static async deployedSecretEnv(distDir: string, envDir: string): Promise<{ [name: string]: string }> {
215
+ const file = path.join(distDir, BUILD_ENV_FILE);
216
+ const built = existsSync(file)
217
+ ? (JSON.parse(readFileSync(file, "utf8")) as { [key: string]: string | undefined })
218
+ : {};
219
+ if (!built[SecretEnv.listKey]) return {};
220
+ const { variables } = await SecretEnvDeclaration.of(envDir, built.AKAN_PUBLIC_ENV ?? "local");
221
+ return Object.fromEntries(variables.map(({ name, value }) => [name, value]));
222
+ }
223
+
210
224
  static async killTree(
211
225
  root: { kill: (signal: NodeJS.Signals) => void },
212
226
  sampleTree: () => Promise<{ pid: number }[]>,
@@ -159,6 +159,7 @@ export default page()
159
159
  #server: { kill: (signal: NodeJS.Signals) => void } | null = null;
160
160
  #build: { kill: (signal: NodeJS.Signals) => void } | null = null;
161
161
  #injected = false;
162
+ #secretEnv: { [name: string]: string } = {};
162
163
 
163
164
  constructor(options: RenderAdmissionSoakOptions) {
164
165
  this.#options = options;
@@ -223,6 +224,10 @@ export default page()
223
224
  `no built app at ${distDir} — run this with --prepare, which builds ${appName} with the soak page`,
224
225
  );
225
226
  const routes = await this.#routes();
227
+ this.#secretEnv = await DevResourceProbe.deployedSecretEnv(
228
+ distDir,
229
+ path.join(this.#options.workspaceRoot, "apps", appName, "env"),
230
+ );
226
231
  console.info(
227
232
  `[soak] app=${appName} arrival=${this.#options.arrival} caps=${caps.join(",")} mixes=${mixes.join(",")} runs=${runs} routes=${routes.docs.length}`,
228
233
  );
@@ -323,6 +328,7 @@ export default page()
323
328
  return Bun.spawn(["bun", "main.js"], {
324
329
  cwd: distDir,
325
330
  env: {
331
+ ...this.#secretEnv,
326
332
  ...process.env,
327
333
  NODE_ENV: "production",
328
334
  USE_AKANJS_PKGS: "true",
@@ -106,9 +106,14 @@ export class SsrMemoryProbe {
106
106
  if (!fs.existsSync(path.join(distDir, "main.js")))
107
107
  throw new Error(`no built app at ${distDir} — run \`akan build ${appName}\` first`);
108
108
  await Bun.write(logPath, "");
109
+ const secretEnv = await DevResourceProbe.deployedSecretEnv(
110
+ distDir,
111
+ path.join(process.cwd(), "apps", appName, "env"),
112
+ );
109
113
  const gateway = Bun.spawn(["bun", "main.js"], {
110
114
  cwd: distDir,
111
115
  env: {
116
+ ...secretEnv,
112
117
  ...process.env,
113
118
  NODE_ENV: "production",
114
119
  USE_AKANJS_PKGS: "true",
@@ -282,6 +282,12 @@ describe("NativeApp", () => {
282
282
  );
283
283
  });
284
284
 
285
+ test("an indexPath's query opens the dev build ahead of its own parameters, and its hash after them", () => {
286
+ expect(new NativeApp(fakeApp(), target({ indexPath: "/explore?tab=new#top" })).startPath("en", "ios")).toBe(
287
+ "/en/explore?tab=new&csr=true&akanMobileTarget=default&akanMobileLang=device&akanMobileIndexPath=%2Fexplore%3Ftab%3Dnew%23top#top",
288
+ );
289
+ });
290
+
285
291
  test("a platform section's indexPath wins on that platform, and the others keep the target's", () => {
286
292
  const app = new NativeApp(fakeApp(), target({ indexPath: "/mobile", desktop: { indexPath: "/", server: true } }));
287
293