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

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.
@@ -280,6 +280,14 @@ console.info(new SampleService().name);
280
280
  'The server env profile "edge" bundles env/env.server.main.edge.ts',
281
281
  );
282
282
  expect((await started({})).failure).toBe("stopped before the phases");
283
+ await writeFile(
284
+ path.join(root, "apps/portal/env/env.server.main.runtime.ts"),
285
+ 'export const env = { hostname: "runtime-host" };\n',
286
+ );
287
+ expect((await started({ secretEnv: "read", profile: "runtime" })).failure).toContain(
288
+ 'The server env profile "edge" bundles env/env.server.main.edge.ts',
289
+ );
290
+ expect((await started({ profile: "runtime" })).failure).toBe("stopped before the phases");
283
291
 
284
292
  await writeFile(profileFile, 'export const env = { mailer: { auth: { pass: "sentinel-edge-pass" } } };\n');
285
293
  const secret = await started({ secretEnv: "read" });
@@ -287,6 +295,7 @@ console.info(new SampleService().name);
287
295
  expect(secret.failure).not.toContain("sentinel-edge-pass");
288
296
 
289
297
  await writeFile(profileFile, 'export const env = { hostname: "edge-host" };\n');
298
+ expect((await started({ secretEnv: "read", profile: "runtime" })).failure).toBe("stopped before the phases");
290
299
  const { app, runner, failure } = await started({ secretEnv: "read" });
291
300
  expect(failure).toBe("stopped before the phases");
292
301
  await runner.buildAppMeta();
@@ -133,6 +133,7 @@ export class ApplicationBuildRunner {
133
133
  #environment?: string;
134
134
  #profile?: string;
135
135
  #secretEnv?: "read";
136
+ #image: boolean;
136
137
  #secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
137
138
  #budget: RouteJsBudgetMode;
138
139
  #modulesByRoute?: Record<string, string[]>;
@@ -159,6 +160,7 @@ export class ApplicationBuildRunner {
159
160
  this.#environment = environment;
160
161
  this.#profile = profile;
161
162
  this.#secretEnv = profile ? undefined : secretEnv;
163
+ this.#image = !!secretEnv;
162
164
  this.#budget = budget;
163
165
  }
164
166
 
@@ -198,9 +200,11 @@ export class ApplicationBuildRunner {
198
200
  const environment = this.#environment ?? baseDevEnv.env;
199
201
  WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
200
202
  this.#pinImageEnv(baseDevEnv, environment);
201
- if (this.#secretEnv) this.#carriedProfiles = dockerProfilesOf(dockerVariants);
203
+ //? Under `--profile` too: each variant's Dockerfile names its profile whichever env file the build starts on.
204
+ if (this.#image)
205
+ this.#carriedProfiles = dockerProfilesOf(dockerVariants).filter((profile) => profile !== this.#profile);
202
206
  //? Before any phase: a profile that would ship a secret stops the build, not the image after it.
203
- for (const profile of this.#profile ? [this.#profile] : this.#carriedProfiles)
207
+ for (const profile of this.#envProfiles)
204
208
  await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile });
205
209
  if (this.#secretEnv) await this.#declareSecrets(environment);
206
210
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
@@ -494,6 +498,9 @@ export class ApplicationBuildRunner {
494
498
 
495
499
  #serverEnv: BunPlugin | null = null;
496
500
  #carriedProfiles: string[] = [];
501
+ get #envProfiles() {
502
+ return [...(this.#profile ? [this.#profile] : []), ...this.#carriedProfiles];
503
+ }
497
504
  #libEnvsLeftOut = new Map<string, Map<string, string[]>>();
498
505
  //? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
499
506
  #serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
@@ -535,9 +542,7 @@ export class ApplicationBuildRunner {
535
542
  define: {
536
543
  // `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
537
544
  "process.env.NODE_ENV": JSON.stringify("production"),
538
- [`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(
539
- EnvProfile.format(this.#profile ? [this.#profile] : this.#carriedProfiles),
540
- ),
545
+ [`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(EnvProfile.format(this.#envProfiles)),
541
546
  },
542
547
  } satisfies Omit<Bun.BuildConfig, "entrypoints">;
543
548
  const serverEnvPlugin = this.#serverEnvPlugin(baseDevEnv.env, branches);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.71",
3
+ "version": "3.3.0-rc.72",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -52,10 +52,10 @@
52
52
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
53
53
  },
54
54
  "dependencies": {
55
- "@akanjs/language": "3.3.0-rc.71",
55
+ "@akanjs/language": "3.3.0-rc.72",
56
56
  "@inquirer/prompts": "^8.7.3",
57
57
  "@tailwindcss/node": "^4.3.3",
58
- "akanjs": "3.3.0-rc.71",
58
+ "akanjs": "3.3.0-rc.72",
59
59
  "chalk": "^6.0.1",
60
60
  "commander": "^15.0.0",
61
61
  "dayjs": "^1.11.23",
@@ -257,7 +257,7 @@ describe("createServerEnvPlugin", () => {
257
257
  });
258
258
 
259
259
  describe("profiles carried beside the environment's own file", () => {
260
- const carry = async (secrets?: "read") => {
260
+ const carry = async (secrets?: "read", profile?: string) => {
261
261
  const root = await makeTempRoot();
262
262
  const libEnv = path.join(root, "libs/shared/env/env.server.testing.ts");
263
263
  await write(
@@ -277,13 +277,13 @@ describe("createServerEnvPlugin", () => {
277
277
  "",
278
278
  ].join("\n"),
279
279
  );
280
- for (const profile of ["edge", "kiosk"])
280
+ for (const name of ["edge", "kiosk", "runtime"])
281
281
  await write(
282
- path.join(envDir, `env.server.main.${profile}.ts`),
282
+ path.join(envDir, `env.server.main.${name}.ts`),
283
283
  [
284
284
  'import { libEnv } from "./env.server.type";',
285
- `export const env = { ...libEnv, origin: "${profile}-origin" };`,
286
- `export default "${profile}-default";`,
285
+ `export const env = { ...libEnv, origin: "${name}-origin" };`,
286
+ `export default "${name}-default";`,
287
287
  "",
288
288
  ].join("\n"),
289
289
  );
@@ -306,7 +306,8 @@ describe("createServerEnvPlugin", () => {
306
306
  envDir,
307
307
  environment: "main",
308
308
  environments,
309
- profiles: ["edge", "kiosk"],
309
+ profile,
310
+ profiles: [...(profile ? [profile] : []), "edge", "kiosk"],
310
311
  secrets,
311
312
  onLibEnv: (file, report) => reports.push({ file: path.basename(file), ...report }),
312
313
  }),
@@ -359,6 +360,42 @@ describe("createServerEnvPlugin", () => {
359
360
  );
360
361
  });
361
362
 
363
+ test("a profile build carries them beside its own profile, which it starts on with none named", async () => {
364
+ const { start, reports, text } = await carry(undefined, "runtime");
365
+ expect(text).not.toContain("main-secret");
366
+ const runtime = {
367
+ app: { shared: "shared-value", origin: "runtime-origin" },
368
+ lib: { hostname: "lib-host", security: { accessTokenSeconds: 900 } },
369
+ fallback: "runtime-default",
370
+ };
371
+ for (const named of [[], ["runtime"]]) {
372
+ const proc = start(Object.fromEntries(named.map((name) => ["AKAN_ENV_PROFILE", name])));
373
+ expect(proc.stderr.toString()).toBe("");
374
+ expect(JSON.parse(proc.stdout.toString())).toEqual(runtime);
375
+ }
376
+ expect(JSON.parse(start({ AKAN_ENV_PROFILE: "edge" }).stdout.toString())).toEqual({
377
+ ...runtime,
378
+ app: { shared: "shared-value", origin: "edge-origin" },
379
+ fallback: "edge-default",
380
+ });
381
+ expect(JSON.parse(start({ AKAN_ENV_PROFILE: "kiosk" }).stdout.toString())).toEqual({
382
+ app: { shared: "shared-value", origin: "kiosk-origin" },
383
+ lib: { hostname: "lib-kiosk-host" },
384
+ fallback: "kiosk-default",
385
+ });
386
+ expect(start({ AKAN_ENV_PROFILE: "desk" }).stderr.toString()).toContain(
387
+ "AKAN_ENV_PROFILE=desk names a server env profile this build does not carry (it carries runtime, edge, kiosk).",
388
+ );
389
+ expect(reports).toEqual(
390
+ expect.arrayContaining([
391
+ { file: "env.server.testing.ts", profile: "runtime", profileFile: false, stripped: ["security.jwtSecret"] },
392
+ { file: "env.server.testing.ts", profile: "edge", profileFile: false, stripped: ["security.jwtSecret"] },
393
+ { file: "env.server.testing.ts", profile: "kiosk", profileFile: true, stripped: [] },
394
+ ]),
395
+ );
396
+ expect(reports).toHaveLength(3);
397
+ });
398
+
362
399
  test("an image build still leaves every secret value out, the app's and a lib's", async () => {
363
400
  const { start, text } = await carry("read");
364
401
  for (const secret of ["main-secret", "lib-jwt"]) expect(text).not.toContain(secret);
@@ -13,8 +13,8 @@ export interface ServerEnvPluginOptions {
13
13
  /** Bundled in place of the environment's own file: `env.server.<environment>.<profile>.ts`, read from the same folder. */
14
14
  profile?: string;
15
15
  /**
16
- * Carried beside the environment's own file, each as `env.server.<environment>.<profile>.ts`: the server runs the
17
- * one `AKAN_ENV_PROFILE` names when it starts, and the environment's own with none named.
16
+ * Carried beside the environment's own file, or beside `profile` when one is bundled in its place, each as
17
+ * `env.server.<environment>.<profile>.ts`: the server runs the one `AKAN_ENV_PROFILE` names when it starts.
18
18
  */
19
19
  profiles?: readonly string[];
20
20
  /** Under a profile, once per lib env file: whether the lib gave one of the profile's, and what was left out if not. */
@@ -34,11 +34,13 @@ const ORIGINAL_PREFIX = `${ORIGINAL_NAMESPACE}:`;
34
34
  const ORIGINAL_SUFFIX = ".original";
35
35
 
36
36
  //? Only the env the server starts on is evaluated: the environment's own file may not load without its variables.
37
- const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }) => {
37
+ const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }, base?: string) => {
38
38
  const names = Object.keys(carried);
39
- const refusal = ` names a server env profile this build does not carry (it carries ${names.join(", ")}).`;
39
+ const all = [...(base ? [base] : []), ...names];
40
+ const refusal = ` names a server env profile this build does not carry (it carries ${all.join(", ")}).`;
41
+ const named = `process.env.${EnvProfile.key}`;
40
42
  return [
41
- `const profile = process.env.${EnvProfile.key};`,
43
+ `const profile = ${base ? `${named} === ${JSON.stringify(base)} ? undefined : ${named}` : named};`,
42
44
  `const carried = { ${names.map((name) => `${JSON.stringify(name)}: () => ${carried[name]}`).join(", ")} };`,
43
45
  `if (profile && !Object.hasOwn(carried, profile)) throw new Error("${EnvProfile.key}=" + profile + ${JSON.stringify(refusal)});`,
44
46
  `const picked = profile ? carried[profile]() : require(${JSON.stringify(`${ORIGINAL_PREFIX}${file}`)});`,
@@ -65,18 +67,40 @@ export const createServerEnvPlugin = ({
65
67
  const folder = `^(?:${[...dirs].map(escapeRegExp).join("|")})[\\\\/]env\\.server\\.`;
66
68
  const filter = new RegExp(`${folder}(?:${others.map(escapeRegExp).join("|")})\\.ts$`);
67
69
  const own = new RegExp(`${folder}${escapeRegExp(environment)}\\.ts$`);
70
+ const carriedNames = profiles.filter((name) => name !== profile);
68
71
  const libEnvs = new Map<string, Promise<OnLoadResult>>();
72
+ const libSelectors = new Map<string, Promise<OnLoadResult>>();
73
+ const once = (
74
+ cache: Map<string, Promise<OnLoadResult>>,
75
+ file: string,
76
+ load: (file: string) => Promise<OnLoadResult>,
77
+ ) => {
78
+ if (!cache.has(file)) cache.set(file, load(file));
79
+ return cache.get(file) as Promise<OnLoadResult>;
80
+ };
69
81
  const libEnv = async (file: string): Promise<OnLoadResult> => {
70
82
  const { loader, contents, profileFile, stripped } = await ServerEnvProfile.libEnvSource(file, profile ?? "");
71
83
  onLibEnv?.(file, { profile: profile ?? "", profileFile, stripped });
72
84
  return { loader, contents };
73
85
  };
86
+ const inPlace = async (file: string, name: string): Promise<OnLoadResult> => ({
87
+ loader: "ts",
88
+ contents: await ServerEnvProfile.sourceInPlaceOf(
89
+ path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)),
90
+ file,
91
+ name,
92
+ ),
93
+ });
74
94
  const exportsOf = async (file: string) =>
75
95
  new Bun.Transpiler({ loader: "ts" }).scan(await Bun.file(file).text()).exports;
76
96
  const original = async (file: string): Promise<OnLoadResult> =>
77
- secrets
97
+ secrets && !profile
78
98
  ? await SecretEnvDeclaration.source(file, secrets)
79
99
  : { loader: "ts", contents: await Bun.file(file).text() };
100
+ const base = (file: string): Promise<OnLoadResult> => {
101
+ if (!profile) return original(file);
102
+ return own.test(file) ? inPlace(file, profile) : once(libEnvs, file, libEnv);
103
+ };
80
104
  const isAppEnv = (file: string) => {
81
105
  const name = path.basename(file, ".ts").slice("env.server.".length);
82
106
  return dirs.has(path.dirname(file)) || name === "type" || name === "example";
@@ -87,37 +111,30 @@ export const createServerEnvPlugin = ({
87
111
  file,
88
112
  await exportsOf(file),
89
113
  Object.fromEntries(
90
- profiles.map((name) => [
114
+ carriedNames.map((name) => [
91
115
  name,
92
116
  `require(${JSON.stringify(path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)))})`,
93
117
  ]),
94
118
  ),
119
+ profile,
95
120
  ),
96
121
  });
97
122
  const libSelector = async (file: string): Promise<OnLoadResult> => {
98
123
  const carried: { [name: string]: string } = {};
99
- for (const name of profiles) {
124
+ for (const name of carriedNames) {
100
125
  const { profileFile, stripped, value } = await ServerEnvProfile.libEnvSource(file, name);
101
126
  onLibEnv?.(file, { profile: name, profileFile, stripped });
102
127
  carried[name] = profileFile
103
128
  ? `require(${JSON.stringify(ServerEnvProfile.profileFileOf(file, name))})`
104
129
  : `({ env: ${JSON.stringify(value)} })`;
105
130
  }
106
- return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried) };
131
+ return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried, profile) };
107
132
  };
108
133
  return {
109
134
  name: "akan-server-env",
110
135
  setup(build) {
111
136
  //* The environment's own file never enters a profile's bundle: its contents are the profile file's.
112
- if (profile)
113
- build.onLoad({ filter: own }, async (args) => ({
114
- loader: "ts",
115
- contents: await ServerEnvProfile.sourceInPlaceOf(
116
- path.join(path.dirname(args.path), ServerEnvProfile.fileName(environment, profile)),
117
- args.path,
118
- profile,
119
- ),
120
- }));
137
+ if (profile && !carriedNames.length) build.onLoad({ filter: own }, (args) => inPlace(args.path, profile));
121
138
  if (others.length)
122
139
  build.onLoad({ filter }, async (args) => {
123
140
  const name = path.basename(args.path, ".ts").slice("env.server.".length);
@@ -132,7 +149,7 @@ export const createServerEnvPlugin = ({
132
149
  ].join("\n"),
133
150
  };
134
151
  });
135
- if (profiles.length && !profile) {
152
+ if (carriedNames.length) {
136
153
  build.onResolve({ filter: new RegExp(`^${ORIGINAL_PREFIX}`) }, (args) => ({
137
154
  path: `${args.path.slice(ORIGINAL_PREFIX.length)}${ORIGINAL_SUFFIX}`,
138
155
  namespace: ORIGINAL_NAMESPACE,
@@ -142,13 +159,11 @@ export const createServerEnvPlugin = ({
142
159
  path: Bun.resolveSync(args.path, path.dirname(args.importer)),
143
160
  }));
144
161
  build.onLoad({ filter: /.*/, namespace: ORIGINAL_NAMESPACE }, (args) =>
145
- original(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
162
+ base(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
146
163
  );
147
164
  build.onLoad({ filter: own }, (args) => ownSelector(args.path));
148
165
  build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) => {
149
- if (isAppEnv(args.path)) return original(args.path);
150
- if (!libEnvs.has(args.path)) libEnvs.set(args.path, libSelector(args.path));
151
- return libEnvs.get(args.path) as Promise<OnLoadResult>;
166
+ return isAppEnv(args.path) ? original(args.path) : once(libSelectors, args.path, libSelector);
152
167
  });
153
168
  }
154
169
  //? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
@@ -158,14 +173,10 @@ export const createServerEnvPlugin = ({
158
173
  SecretEnvDeclaration.source(args.path, secrets),
159
174
  );
160
175
  //? Last: the app's own env files above are taken by the handlers before it, which match them first.
161
- if (profile)
162
- build.onLoad({ filter: ServerEnvProfile.envFilePattern }, async (args) => {
163
- const name = path.basename(args.path, ".ts").slice("env.server.".length);
164
- if (dirs.has(path.dirname(args.path)) || name === "type" || name === "example")
165
- return { loader: "ts", contents: await Bun.file(args.path).text() };
166
- if (!libEnvs.has(args.path)) libEnvs.set(args.path, libEnv(args.path));
167
- return (await libEnvs.get(args.path)) as OnLoadResult;
168
- });
176
+ if (profile && !carriedNames.length)
177
+ build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) =>
178
+ isAppEnv(args.path) ? original(args.path) : once(libEnvs, args.path, libEnv),
179
+ );
169
180
  },
170
181
  };
171
182
  };