@akanjs/devkit 3.2.0-rc.12 → 3.2.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/executors.ts CHANGED
@@ -1,1749 +1,8 @@
1
- import {
2
- type ChildProcess,
3
- type ExecOptions,
4
- exec,
5
- type ForkOptions,
6
- fork,
7
- type SpawnOptions,
8
- spawn,
9
- } from "node:child_process";
10
- import { existsSync, readFileSync } from "node:fs";
11
- import {
12
- copyFile,
13
- cp as cpEntry,
14
- lstat,
15
- mkdir,
16
- readdir as readDirEntries,
17
- realpath,
18
- rm,
19
- stat,
20
- symlink,
21
- } from "node:fs/promises";
22
- import path from "node:path";
23
- import { pathToFileURL } from "node:url";
24
- import type { AkanPlugin, AkanSyncContext } from "akanjs";
25
- import {
26
- capitalize,
27
- getPageSourceFileViolation,
28
- isRouteSourceFile,
29
- Logger,
30
- parseRouteModuleKey,
31
- toError,
32
- validatePageSourceFile,
33
- validateSubRoutePageKey,
34
- } from "akanjs/common";
35
- import { $ } from "bun";
36
- import chalk from "chalk";
37
- import {
38
- renderScopeAgentBlock,
39
- renderScopeAgentsMd,
40
- renderScopeClaudeMd,
41
- scanScopeRecipes,
42
- upsertAgentBlock,
43
- } from "./agentsIndex";
44
- import { AkanAppConfig, AkanLibConfig, AkanWorkspaceConfig, decreaseBuildNum, increaseBuildNum } from "./akanConfig";
45
- import { getRootBoundarySegments, isRootBoundarySegments } from "./artifact/implicitRootLayout";
46
- import { CodegenLock } from "./codegenLock";
47
- import { EnvSeed } from "./envSeed";
48
- import { FileSys, getDirname } from "./fileSys";
49
- import { JsonFormatter } from "./jsonFormatter";
50
- import { Linter } from "./linter";
51
- import { ManifestDependencies } from "./manifestDependencies";
52
- import { resolveRepoName } from "./repoIdentity";
53
- import type { RouteSourceInfo } from "./routeSourceValidator";
54
- import { AppInfo, isAkanFrameworkDependency, LibInfo, PkgInfo, WorkspaceInfo } from "./scanInfo";
55
- import { Spinner } from "./spinner";
56
- // Type-only: `getTypeChecker` loads it on demand to keep `typescript` out of the resident module graph.
57
- import type { TypeChecker } from "./typeChecker";
58
- import { ProjectTypecheck } from "./typecheck/projectTypecheck";
59
- import type { BaseDevEnv, FileContent, PackageJson, TsConfigJson } from "./types";
60
- import { barrelFacetDirs } from "./workspaceLayout";
61
-
62
- export interface PageRoot {
63
- /** App-relative location of the route files, i.e. the symlink for a synced lib. */
64
- dir: string;
65
- /** Where the files actually live, which is what a file watcher reports. */
66
- realDir: string;
67
- /** Prefix that turns a `dir`-relative path into an app page key (empty for the app's own `page`). */
68
- keyPrefix: string;
69
- }
70
-
71
- export interface AppRouteSource {
72
- key: string;
73
- absPath: string;
74
- info: RouteSourceInfo;
75
- }
76
-
77
- export interface WrittenFileContent extends FileContent {
78
- written: boolean;
79
- }
80
-
81
- const staticTemplateFileExtensions = new Set(
82
- ".avif .bmp .cjs .css .eot .gif .html .ico .jpeg .jpg .js .json .map .md .mjs .mp3 .mp4 .ogg .otf .pdf .png .svg"
83
- .split(" ")
84
- .concat(".ttf .txt .wasm .wav .webm .webp .woff .woff2 .xml".split(" ")),
85
- );
86
-
87
- //? A backslash is a path separator on Windows but an escape in a POSIX shell, so only there does it force quoting.
88
- const plainCommandArgPattern = process.platform === "win32" ? /^[\w@%+=:,./\\-]+$/ : /^[\w@%+=:,./-]+$/;
89
- const formatCommandArg = (value: string) => (plainCommandArgPattern.test(value) ? value : JSON.stringify(value));
90
-
91
- const formatCommandForDisplay = (command: string, args: string[] = []) =>
92
- [command, ...args].map(formatCommandArg).join(" ");
93
-
94
- export interface CommandExecutionErrorOptions {
95
- command: string;
96
- args?: string[];
97
- cwd: string;
98
- code: number | null;
99
- signal: string | null;
100
- stdout?: string;
101
- stderr?: string;
102
- cause?: unknown;
103
- }
104
-
105
- export class CommandExecutionError extends Error {
106
- command: string;
107
- args: string[];
108
- cwd: string;
109
- code: number | null;
110
- signal: string | null;
111
- stdout: string;
112
- stderr: string;
113
-
114
- constructor({
115
- command,
116
- args = [],
117
- cwd,
118
- code,
119
- signal,
120
- stdout = "",
121
- stderr = "",
122
- cause,
123
- }: CommandExecutionErrorOptions) {
124
- const displayCommand = formatCommandForDisplay(command, args);
125
- const status = signal ? `signal: ${signal}` : `exit code: ${code ?? "unknown"}`;
126
- const output = (stderr || stdout).trim();
127
- super([`Command failed: ${displayCommand}`, `cwd: ${cwd}`, status, output ? `\n${output}` : ""].join("\n"), {
128
- cause,
129
- });
130
- this.name = "CommandExecutionError";
131
- this.command = command;
132
- this.args = args;
133
- this.cwd = cwd;
134
- this.code = code;
135
- this.signal = signal;
136
- this.stdout = stdout;
137
- this.stderr = stderr;
138
- }
139
- }
140
-
141
- export const execEmoji = {
142
- workspace: "🏠",
143
- app: "🚀",
144
- lib: "🔧",
145
- pkg: "📦",
146
- dist: "💿",
147
- module: "⚙️",
148
- default: "✈️",
149
- };
150
-
151
- //? As Bun's own .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value even mid-word.
152
- const parseEnvValue = (value: string) => {
153
- const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
154
- if (!quote) return value.replace(/#.*/, "").trim();
155
- if (quote !== '"') return inner;
156
- return inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
157
- };
158
-
159
- export const parseEnvFile = (envPath: string): Record<string, string> => {
160
- const env: Record<string, string> = {};
161
- const content = (() => {
162
- try {
163
- return readFileSync(envPath, "utf8");
164
- } catch {
165
- return "";
166
- }
167
- })();
168
- for (const line of content.split(/\r?\n/)) {
169
- const trimmed = line.trim();
170
- if (!trimmed || trimmed.startsWith("#")) continue;
171
- const normalized = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trim() : trimmed;
172
- const separatorIndex = normalized.indexOf("=");
173
- if (separatorIndex <= 0) continue;
174
- const key = normalized.slice(0, separatorIndex).trim();
175
- env[key] = parseEnvValue(normalized.slice(separatorIndex + 1).trim());
176
- }
177
- return env;
178
- };
179
-
180
- const withCapitalizedDict = (dict: { [key: string]: string } = {}) => ({
181
- ...dict,
182
- ...Object.fromEntries(Object.entries(dict).map(([key, value]) => [capitalize(key), capitalize(value)])),
183
- });
184
-
185
- export class Executor {
186
- static verbose = false;
187
- static setVerbose(verbose: boolean) {
188
- Executor.verbose = verbose;
189
- }
190
-
191
- name: string;
192
- logger: Logger;
193
- logs: string[];
194
- cwdPath: string;
195
- emoji = execEmoji.default;
196
- typeChecker: TypeChecker | null = null;
197
- linter: Linter | null = null;
198
- constructor(name: string, cwdPath: string) {
199
- this.name = name;
200
- this.logger = new Logger(name);
201
- this.logs = [] as string[];
202
- this.cwdPath = cwdPath;
203
- }
204
- #stdout(data: Buffer) {
205
- if (Executor.verbose) Logger.raw(chalk.dim(data.toString()));
206
- }
207
- #stderr(data: Buffer) {
208
- Logger.raw(chalk.red(data.toString()));
209
- }
210
- #settle(
211
- proc: ChildProcess,
212
- target: { command: string; args?: string[]; cwd: string },
213
- { onClose = false, keepLogs = false, redStderr = false } = {},
214
- ): Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string }> {
215
- let stdout = "";
216
- let stderr = "";
217
- proc.stdout?.on("data", (data: Buffer) => {
218
- stdout += data.toString();
219
- if (keepLogs) this.logs.push(data.toString());
220
- this.#stdout(data);
221
- });
222
- proc.stderr?.on("data", (data: Buffer) => {
223
- stderr += data.toString();
224
- if (keepLogs) this.logs.push(data.toString());
225
- if (redStderr) this.#stderr(data);
226
- else this.#stdout(data); // 정상로그도 stderr로 나옴
227
- });
228
- return new Promise((resolve, reject) => {
229
- proc.on("error", (cause) =>
230
- reject(new CommandExecutionError({ ...target, code: null, signal: null, stdout, stderr, cause })),
231
- );
232
- proc.on(onClose ? "close" : "exit", (code: number | null, signal: NodeJS.Signals | null) => {
233
- if ((onClose ? code !== 0 : code) || signal)
234
- reject(new CommandExecutionError({ ...target, code, signal, stdout, stderr }));
235
- else resolve({ code, signal, stdout });
236
- });
237
- });
238
- }
239
- exec(command: string, options: ExecOptions = {}): Promise<unknown> {
240
- const target = { command, cwd: options.cwd?.toString() ?? this.cwdPath };
241
- const proc = exec(command, { cwd: this.cwdPath, ...options });
242
- return this.#settle(proc, target).then(({ code, signal }) => ({ code, signal }));
243
- }
244
-
245
- spawn(command: string, args: string[] = [], options: SpawnOptions = {}): Promise<string> {
246
- const target = { command, args, cwd: options.cwd?.toString() ?? this.cwdPath };
247
- const proc = spawn(command, args, { cwd: this.cwdPath, ...options });
248
- return this.#settle(proc, target, { onClose: true, keepLogs: true }).then(({ stdout }) => stdout);
249
- }
250
- spawnSync(command: string, args: string[] = [], options: SpawnOptions = {}): ChildProcess {
251
- return spawn(command, args, { cwd: this.cwdPath, ...options });
252
- }
253
- fork(modulePath: string, args: string[] = [], options: ForkOptions = {}): Promise<unknown> {
254
- const target = { command: modulePath, args, cwd: options.cwd?.toString() ?? this.cwdPath };
255
- const proc = fork(modulePath, args, { cwd: this.cwdPath, ...options });
256
- return this.#settle(proc, target, { redStderr: true }).then(({ code, signal }) => ({ code, signal }));
257
- }
258
- getPath(filePath: string) {
259
- if (path.isAbsolute(filePath)) return filePath;
260
- if (filePath.startsWith(".")) return path.join(this.cwdPath, filePath);
261
- const baseParts = this.cwdPath.split(/[\\/]/).filter(Boolean);
262
- const targetParts = filePath.split(/[\\/]/).filter(Boolean);
263
-
264
- let overlapLength = 0;
265
- for (let i = 1; i <= Math.min(baseParts.length, targetParts.length); i++) {
266
- let isOverlap = true;
267
- for (let j = 0; j < i; j++)
268
- if (baseParts[baseParts.length - i + j] !== targetParts[j]) {
269
- isOverlap = false;
270
- break;
271
- }
272
- if (isOverlap) overlapLength = i;
273
- }
274
- return path.join(this.cwdPath, ...targetParts.slice(overlapLength));
275
- }
276
- async mkdir(dirPath: string) {
277
- const writePath = this.getPath(dirPath);
278
- if (!(await FileSys.dirExists(writePath))) await mkdir(writePath, { recursive: true });
279
- this.logger.verbose(`Make directory ${writePath}`);
280
- return this;
281
- }
282
- async readdir(dirPath: string): Promise<string[]> {
283
- const readPath = this.getPath(dirPath);
284
- try {
285
- const glob = new Bun.Glob("*");
286
- return Array.from(glob.scanSync({ cwd: readPath, onlyFiles: false })).sort();
287
- } catch {
288
- return [];
289
- }
290
- }
291
- async getAllFiles(pattern = "**/*", { cwd }: { cwd?: string } = {}): Promise<string[]> {
292
- const glob = new Bun.Glob(pattern);
293
- return Array.from(glob.scanSync({ cwd: cwd ?? this.cwdPath, onlyFiles: true })).sort();
294
- }
295
- async getFilesAndDirs(dirPath: string): Promise<{ files: string[]; dirs: string[] }> {
296
- const fullDirPath = this.getPath(dirPath);
297
- const glob = new Bun.Glob("*");
298
- const files = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: true })).sort();
299
- const allEntries = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: false })).sort();
300
- const dirs = allEntries.filter((entry) => !files.includes(entry));
301
- return { files, dirs };
302
- }
303
- async exists(filePath: string) {
304
- return await FileSys.exists(this.getPath(filePath));
305
- }
306
- async remove(filePath: string) {
307
- const readPath = this.getPath(filePath);
308
- if (await FileSys.fileExists(readPath)) await FileSys.delete(readPath);
309
- this.logger.verbose(`Remove file ${readPath}`);
310
- return this;
311
- }
312
- async removeDir(dirPath: string) {
313
- //* XXX: `path.join(…, ".")` drops a trailing slash: `rm -rf link/` wipes the target, `rm -rf link` only unlinks.
314
- const readPath = path.join(this.getPath(dirPath), ".");
315
- if (await FileSys.entryExists(readPath)) await rm(readPath, { recursive: true, force: true });
316
- this.logger.verbose(`Remove directory ${readPath}`);
317
- return this;
318
- }
319
- async writeFile(
320
- filePath: string,
321
- content: string | object,
322
- { overwrite = true, silent = false }: { overwrite?: boolean; silent?: boolean } = {},
323
- ): Promise<WrittenFileContent> {
324
- const writePath = this.getPath(filePath);
325
- const dir = path.dirname(writePath);
326
- if (!(await FileSys.dirExists(dir))) await mkdir(dir, { recursive: true });
327
- let contentStr = typeof content === "string" ? content : JsonFormatter.stringify(content, writePath);
328
- let written = true;
329
-
330
- if (await FileSys.fileExists(writePath)) {
331
- const currentContent = await FileSys.readText(writePath);
332
- if (currentContent === contentStr || !overwrite) {
333
- this.logger.verbose(`File ${writePath} is unchanged`);
334
- contentStr = currentContent;
335
- written = false;
336
- } else {
337
- await FileSys.writeText(writePath, contentStr);
338
- if (Logger.isVerbose()) this.logger.rawLog(chalk.yellow(`File Update: ${filePath}`));
339
- }
340
- } else {
341
- await FileSys.writeText(writePath, contentStr);
342
- if (!silent) this.logger.rawLog(chalk.green(`File Create: ${filePath}`));
343
- }
344
- return { filePath: writePath, content: contentStr, written };
345
- }
346
- async writeJson(filePath: string, content: object) {
347
- await this.writeFile(filePath, content);
348
- }
349
- async getLocalFile(targetPath: string) {
350
- const filePath = path.isAbsolute(targetPath) ? targetPath : targetPath.replace(this.cwdPath, "");
351
- const content = await this.readFile(filePath);
352
- return { filePath, content };
353
- }
354
- async readFile(filePath: string) {
355
- return await FileSys.readText(this.getPath(filePath));
356
- }
357
- async readJson(filePath: string) {
358
- return await FileSys.readJson<object>(this.getPath(filePath));
359
- }
360
- async cp(srcPath: string, destPath: string, { dereference = false }: { dereference?: boolean } = {}) {
361
- const src = this.getPath(srcPath);
362
- const dest = this.getPath(destPath);
363
- if (!(await FileSys.exists(src))) return;
364
- const isDirectory = (await stat(src)).isDirectory();
365
- if (!(await FileSys.exists(dest)) && isDirectory) await mkdir(dest, { recursive: true });
366
- //* `cp -r` keeps symlinks on GNU but follows them on macOS; Windows has no `cp -r <dir>/.` and rarely the
367
- //* privilege a symlink needs, so it always copies real files.
368
- if (dereference || process.platform === "win32")
369
- await cpEntry(src, dest, { recursive: isDirectory, dereference: true, force: true });
370
- else await $`cp -r ${src}${isDirectory ? "/." : ""} ${dest}`;
371
- }
372
- log(msg: string) {
373
- this.logger.info(msg);
374
- return this;
375
- }
376
- verbose(msg: string) {
377
- this.logger.verbose(msg);
378
- return this;
379
- }
380
- debug(msg: string) {
381
- this.logger.debug(msg);
382
- return this;
383
- }
384
- spinning(msg: string, { prefix = `${this.emoji}${this.name}`, indent = 0, enableSpin = !Executor.verbose } = {}) {
385
- return new Spinner(msg, { prefix, indent, enableSpin }).start();
386
- }
387
-
388
- #tsconfig: TsConfigJson | null = null;
389
- async getTsConfig(pathname = "tsconfig.json", { refresh }: { refresh?: boolean } = {}): Promise<TsConfigJson> {
390
- if (this.#tsconfig && !refresh) return this.#tsconfig;
391
- let tsconfig = (await this.readJson(pathname)) as TsConfigJson;
392
- if (tsconfig.extends) {
393
- const base = await this.getTsConfig(tsconfig.extends, { refresh });
394
- tsconfig = { ...base, ...tsconfig, compilerOptions: { ...base.compilerOptions, ...tsconfig.compilerOptions } };
395
- }
396
- this.#tsconfig = tsconfig;
397
- return tsconfig;
398
- }
399
- async setTsConfig(tsconfig: TsConfigJson) {
400
- await this.writeJson("tsconfig.json", tsconfig);
401
- this.#tsconfig = tsconfig;
402
- }
403
-
404
- #packageJson: PackageJson | null = null;
405
- async getPackageJson({ refresh }: { refresh?: boolean } = {}): Promise<PackageJson> {
406
- if (this.#packageJson && !refresh) return this.#packageJson;
407
- const packageJson = (await this.readJson("package.json")) as PackageJson;
408
- this.#packageJson = packageJson;
409
- return packageJson;
410
- }
411
- async setPackageJson(packageJson: PackageJson) {
412
- await this.writeJson("package.json", packageJson);
413
- this.#packageJson = packageJson;
414
- }
415
-
416
- #gitignorePatterns: string[] = [];
417
- async getGitignorePatterns(): Promise<string[]> {
418
- if (this.#gitignorePatterns.length) return this.#gitignorePatterns;
419
- const gitignore = await this.readFile(".gitignore");
420
- this.#gitignorePatterns = gitignore
421
- .split("\n")
422
- .map((line) => line.trim())
423
- .filter((line) => !!line && !line.startsWith("#"));
424
- return this.#gitignorePatterns;
425
- }
426
-
427
- async #applyTemplateFile(
428
- {
429
- templatePath,
430
- targetPath,
431
- scanInfo,
432
- overwrite = true,
433
- dryRun = false,
434
- }: {
435
- templatePath: string;
436
- targetPath: string;
437
- scanInfo?: AppInfo | LibInfo | null;
438
- overwrite?: boolean;
439
- dryRun?: boolean;
440
- },
441
- dict: { [key: string]: string } = {},
442
- options: { [key: string]: unknown } = {},
443
- ): Promise<WrittenFileContent | null> {
444
- const convertPath = (target: string) =>
445
- Object.entries(dict).reduce(
446
- (converted, [key, value]) => converted.replace(new RegExp(`__${key}__`, "g"), value),
447
- target,
448
- );
449
- if (targetPath.endsWith(".ts") || targetPath.endsWith(".tsx")) {
450
- const getContent = (await import(templatePath)) as {
451
- default: (
452
- scanInfo: AppInfo | LibInfo | null,
453
- dict: { [key: string]: string },
454
- options?: { [key: string]: unknown },
455
- ) => Promise<string | null | { filename: string; content: string }>;
456
- };
457
- const result = await getContent.default(scanInfo ?? null, dict, options);
458
- if (result === null) return null;
459
- const filename = typeof result === "object" ? result.filename : path.basename(targetPath).replace(".js", ".ts");
460
- const content = typeof result === "object" ? result.content : result;
461
- const convertedTargetPath = convertPath(`${path.dirname(targetPath)}/${filename}`);
462
- if (dryRun) return { filePath: this.getPath(convertedTargetPath), content, written: false };
463
- this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
464
- return this.writeFile(convertedTargetPath, content, { overwrite });
465
- } else if (targetPath.endsWith(".template")) {
466
- const content = await FileSys.readText(templatePath);
467
- const convertedTargetPath = convertPath(targetPath.slice(0, -9));
468
- const convertedContent = Object.entries(dict).reduce(
469
- (data, [key, value]) => data.replace(new RegExp(`<%= ${key} %>`, "g"), value),
470
- content,
471
- );
472
- if (dryRun) return { filePath: this.getPath(convertedTargetPath), content: convertedContent, written: false };
473
- this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
474
- return this.writeFile(convertedTargetPath, convertedContent, { overwrite });
475
- } else if (staticTemplateFileExtensions.has(path.extname(targetPath).toLowerCase())) {
476
- const convertedTargetPath = convertPath(targetPath);
477
- const writePath = this.getPath(convertedTargetPath);
478
- if (dryRun) return { filePath: writePath, content: "", written: false };
479
- if (!overwrite && (await FileSys.fileExists(writePath)))
480
- return { filePath: writePath, content: "", written: false };
481
- const dirname = path.dirname(writePath);
482
- if (!(await FileSys.dirExists(dirname))) await mkdir(dirname, { recursive: true });
483
- await copyFile(templatePath, writePath);
484
- this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
485
- return { filePath: writePath, content: "", written: true };
486
- } else return null;
487
- }
488
- async _applyTemplate({
489
- basePath,
490
- template,
491
- scanInfo,
492
- dict = {},
493
- options = {},
494
- overwrite = true,
495
- dryRun = false,
496
- }: {
497
- basePath: string;
498
- template: string;
499
- scanInfo?: AppInfo | LibInfo | null;
500
- dict?: { [key: string]: string };
501
- options?: { [key: string]: unknown };
502
- overwrite?: boolean;
503
- dryRun?: boolean;
504
- }): Promise<WrittenFileContent[]> {
505
- const templateRoot = await this.#resolveTemplateRoot();
506
- const templatePath = `${templateRoot}${template ? `/${template}` : ""}`;
507
- if ((await stat(templatePath)).isFile()) {
508
- const fileContent = await this.#applyTemplateFile(
509
- {
510
- templatePath,
511
- targetPath: path.join(basePath, path.basename(templatePath)),
512
- scanInfo,
513
- overwrite,
514
- dryRun,
515
- },
516
- dict,
517
- options,
518
- );
519
- return fileContent ? [fileContent] : ([] as WrittenFileContent[]);
520
- } else {
521
- const subdirs = await readDirEntries(templatePath);
522
- const fileContents = (
523
- await Promise.all(
524
- subdirs.map(async (subdir) => {
525
- const subpath = path.join(templatePath, subdir);
526
- if ((await stat(subpath)).isFile()) {
527
- const fileContent = await this.#applyTemplateFile(
528
- {
529
- templatePath: subpath,
530
- targetPath: path.join(basePath, subdir),
531
- scanInfo,
532
- overwrite,
533
- dryRun,
534
- },
535
- dict,
536
- options,
537
- );
538
- return fileContent ? [fileContent] : ([] as WrittenFileContent[]);
539
- } else
540
- return await this._applyTemplate({
541
- basePath: path.join(basePath, subdir),
542
- template: path.join(template, subdir),
543
- scanInfo,
544
- dict,
545
- overwrite,
546
- dryRun,
547
- options,
548
- });
549
- }),
550
- )
551
- ).flat();
552
- return fileContents;
553
- }
554
- }
555
- async #resolveTemplateRoot() {
556
- const candidates = [
557
- path.resolve(getDirname(import.meta.url), "templates"),
558
- path.resolve(getDirname(import.meta.url), "../cli/templates"),
559
- ];
560
- for (const candidate of candidates) {
561
- if (await FileSys.dirExists(candidate)) return candidate;
562
- }
563
- return candidates[0];
564
- }
565
- async applyTemplate(options: {
566
- basePath: string;
567
- template: string;
568
- scanInfo?: AppInfo | LibInfo | null;
569
- dict?: { [key: string]: string };
570
- options?: { [key: string]: unknown };
571
- overwrite?: boolean;
572
- dryRun?: boolean;
573
- }): Promise<FileContent[]> {
574
- const fileContents = await this._applyTemplate({ ...options, dict: withCapitalizedDict(options.dict) });
575
- await this.#formatAppliedTemplate(fileContents.filter((fileContent) => fileContent.written));
576
- return fileContents;
577
- }
578
-
579
- // Best-effort: `create-akan-workspace` scaffolds before `bun install`, with no local Biome binary yet, so a
580
- // template emits Biome's form itself (`templates/biomeForm.ts`).
581
- async #formatAppliedTemplate(fileContents: FileContent[]) {
582
- const filePaths = fileContents
583
- .map((fileContent) => fileContent.filePath)
584
- .filter((filePath) => filePath.endsWith(".ts") || filePath.endsWith(".tsx"));
585
- if (filePaths.length === 0) return;
586
- try {
587
- const { fixed } = await this.getLinter().fixFiles(filePaths);
588
- if (fixed.length > 0) this.logger.verbose(`Formatted ${fixed.length} scaffolded file(s)`);
589
- } catch (err) {
590
- this.logger.verbose(`Skipped formatting scaffolded files: ${toError(err).message}`);
591
- }
592
- }
593
- // Async so `typescript` (~65MB resident) loads only in the commands that typecheck.
594
- async getTypeChecker() {
595
- const { TypeChecker } = await import("./typeChecker");
596
- this.typeChecker ??= new TypeChecker(this);
597
- return this.typeChecker;
598
- }
599
- async typeCheck(filePath: string) {
600
- const path = this.getPath(filePath);
601
- const typeChecker = await this.getTypeChecker();
602
- const { fileDiagnostics, fileErrors, fileWarnings } = typeChecker.check(path);
603
- const message = typeChecker.formatDiagnostics(fileDiagnostics);
604
- return { fileDiagnostics, fileErrors, fileWarnings, message };
605
- }
606
- async typeCheckAsync(filePath: string) {
607
- const path = this.getPath(filePath);
608
- const entry = await ProjectTypecheck.workerEntry(process.cwd());
609
- const proc = Bun.spawn([process.execPath, entry], {
610
- cwd: this.cwdPath,
611
- env: {
612
- ...process.env,
613
- AKAN_TYPECHECK_CWD: this.cwdPath,
614
- AKAN_TYPECHECK_FILE: path,
615
- },
616
- stdout: "pipe",
617
- stderr: "pipe",
618
- });
619
- const [stdout, stderr, exitCode] = await Promise.all([
620
- new Response(proc.stdout).text(),
621
- new Response(proc.stderr).text(),
622
- proc.exited,
623
- ]);
624
- if (exitCode !== 0) throw new Error((stderr || stdout).trim() || `Typecheck failed with exit code ${exitCode}`);
625
-
626
- const result = JSON.parse(stdout) as {
627
- fileDiagnosticsCount: number;
628
- fileErrorsCount: number;
629
- fileWarningsCount: number;
630
- message: string;
631
- };
632
- return {
633
- fileDiagnostics: Array.from({ length: result.fileDiagnosticsCount }),
634
- fileErrors: Array.from({ length: result.fileErrorsCount }),
635
- fileWarnings: Array.from({ length: result.fileWarningsCount }),
636
- message: result.message,
637
- };
638
- }
639
- getLinter() {
640
- this.linter ??= new Linter(this.cwdPath);
641
- return this.linter;
642
- }
643
- async lint(
644
- filePath: string,
645
- { fix = false, dryRun = false }: { fix?: boolean; dryRun?: boolean } = {},
646
- ): Promise<{
647
- results: unknown[];
648
- message: string;
649
- errors: unknown[];
650
- warnings: unknown[];
651
- }> {
652
- const path = this.getPath(filePath);
653
- const linter = this.getLinter();
654
- const { results, errors, warnings } = await linter.lint(path, {
655
- fix,
656
- dryRun,
657
- });
658
- const message = linter.formatLintResults(results);
659
- return { results, message, errors, warnings };
660
- }
661
- }
662
-
663
- interface ExecutorOptions {
664
- workspaceRoot: string;
665
- repoName: string;
666
- }
667
- export class WorkspaceExecutor extends Executor {
668
- workspaceRoot: string;
669
- repoName: string;
670
- override emoji = execEmoji.workspace;
671
- constructor({ workspaceRoot, repoName }: ExecutorOptions) {
672
- super("workspace", workspaceRoot);
673
- this.workspaceRoot = workspaceRoot;
674
- this.repoName = repoName;
675
- }
676
-
677
- static fromRoot({
678
- workspaceRoot = process.cwd(),
679
- repoName = resolveRepoName(workspaceRoot),
680
- }: {
681
- workspaceRoot?: string;
682
- repoName?: string;
683
- } = {}) {
684
- return new WorkspaceExecutor({ workspaceRoot, repoName });
685
- }
686
- /** The public env a native build was told to reproduce (`--public-env`): it outranks the shell, which outranks `.env`. */
687
- static publicEnvPin: Record<string, string> | null = null;
688
- static readonly localServeDomain = "localhost";
689
- static getBaseDevEnv(envPath?: string) {
690
- // Bun auto-loads .env, so we use process.env directly
691
- const sourceEnv = {
692
- ...(envPath ? parseEnvFile(envPath) : {}),
693
- //? An empty export reads as unset, unlike in dotenv, so it can't blank a key the .env sets.
694
- ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value)),
695
- ...WorkspaceExecutor.publicEnvPin,
696
- };
697
-
698
- const appName = sourceEnv.AKAN_PUBLIC_APP_NAME;
699
- const workspaceRoot = sourceEnv.AKAN_WORKSPACE_ROOT;
700
- const workspaceId = sourceEnv.AKAN_WORKSPACE_ID;
701
-
702
- const repoName =
703
- sourceEnv.AKAN_PUBLIC_REPO_NAME ||
704
- resolveRepoName(envPath ? path.dirname(envPath) : (workspaceRoot ?? process.cwd()));
705
- const serveDomain = sourceEnv.AKAN_PUBLIC_SERVE_DOMAIN || WorkspaceExecutor.localServeDomain;
706
- const defaulted = (["AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const).filter((key) => !sourceEnv[key]);
707
-
708
- const portOffset = parseInt(sourceEnv.PORT_OFFSET ?? "0");
709
-
710
- const env = (sourceEnv.AKAN_PUBLIC_ENV ?? "debug") as
711
- | "testing"
712
- | "debug"
713
- | "develop"
714
- | "main"
715
- | "local"
716
- | undefined;
717
- if (!env) throw new Error("AKAN_PUBLIC_ENV is not set");
718
- return {
719
- ...(appName ? { appName } : {}),
720
- workspaceRoot,
721
- repoName,
722
- serveDomain,
723
- env,
724
- portOffset,
725
- workspaceId,
726
- defaulted,
727
- };
728
- }
729
- //? A clone has no `.env` (gitignored for its secrets): it runs local, as a new workspace and env.server.ts do, not debug.
730
- static defaultCloneToLocalEnv(workspaceRoot: string) {
731
- if (!existsSync(path.join(workspaceRoot, ".env"))) process.env.AKAN_PUBLIC_ENV ??= "local";
732
- }
733
- //? A build or tunnel for a real environment carries these into an image, a bundle or a host name it dials.
734
- static assertDeployableEnv(baseDevEnv: BaseDevEnv, environment: string, purpose: string) {
735
- const defaulted = environment === "local" ? [] : (baseDevEnv.defaulted ?? []);
736
- if (!defaulted.length) return;
737
- const values = { AKAN_PUBLIC_REPO_NAME: baseDevEnv.repoName, AKAN_PUBLIC_SERVE_DOMAIN: baseDevEnv.serveDomain };
738
- const standIns = defaulted.map((key) => `${key} (would be "${values[key]}")`).join(" and ");
739
- throw new Error(
740
- `${purpose} for the "${environment}" environment needs ${standIns} set, not a local default. ` +
741
- `Set ${defaulted.length > 1 ? "them" : "it"} in the workspace .env or the shell, or use AKAN_PUBLIC_ENV=local.`,
742
- );
743
- }
744
- getWorkspaceId<AllowEmpty extends boolean = false>({
745
- allowEmpty,
746
- }: {
747
- allowEmpty?: AllowEmpty;
748
- } = {}): AllowEmpty extends true ? string | undefined : string {
749
- const { workspaceId } = WorkspaceExecutor.getBaseDevEnv();
750
- if (!workspaceId && !allowEmpty) throw new Error("Workspace ID is not found");
751
- return workspaceId as AllowEmpty extends true ? string | undefined : string;
752
- }
753
- async scan(): Promise<WorkspaceInfo> {
754
- return await WorkspaceInfo.fromExecutor(this);
755
- }
756
- #akanConfig: AkanWorkspaceConfig | null = null;
757
- async getConfig({ refresh }: { refresh?: boolean } = {}) {
758
- if (this.#akanConfig && !refresh) return this.#akanConfig;
759
- this.#akanConfig = await AkanWorkspaceConfig.from(this, { bustImportCache: refresh });
760
- return this.#akanConfig;
761
- }
762
- async getApps() {
763
- return await this.#getDirHasFile(`${this.workspaceRoot}/apps`, "akan.config.ts");
764
- }
765
- async getLibs() {
766
- return await this.#getDirHasFile(`${this.workspaceRoot}/libs`, "akan.config.ts");
767
- }
768
- async getSyss() {
769
- const [appNames, libNames] = await Promise.all([this.getApps(), this.getLibs()]);
770
- return [appNames, libNames] as [string[], string[]];
771
- }
772
- async getPkgs() {
773
- return await this.#getDirHasFile(`${this.workspaceRoot}/pkgs`, "package.json");
774
- }
775
- async getExecs() {
776
- const [appNames, libNames, pkgNames] = await Promise.all([this.getApps(), this.getLibs(), this.getPkgs()]);
777
- return [appNames, libNames, pkgNames] as [string[], string[], string[]];
778
- }
779
- async setPkgTsPaths(name: string) {
780
- const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
781
- rootTsConfig.compilerOptions.paths ??= {};
782
- rootTsConfig.compilerOptions.paths[name] = [`./pkgs/${name}/index.ts`];
783
- rootTsConfig.compilerOptions.paths[`${name}/*`] = [`./pkgs/${name}/*`];
784
- if (rootTsConfig.references) {
785
- if (!rootTsConfig.references.some((ref) => ref.path === `./pkgs/${name}/tsconfig.json`))
786
- rootTsConfig.references.push({ path: `./pkgs/${name}/tsconfig.json` });
787
- }
788
- await this.writeJson("tsconfig.json", rootTsConfig);
789
- return this;
790
- }
791
- async unsetPkgTsPaths(name: string) {
792
- const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
793
- const filteredKeys = Object.keys(rootTsConfig.compilerOptions.paths ?? {}).filter(
794
- (key) => key !== name && key !== `${name}/*`,
795
- );
796
- rootTsConfig.compilerOptions.paths = Object.fromEntries(
797
- filteredKeys.map((key) => [key, rootTsConfig.compilerOptions.paths?.[key] ?? []]),
798
- );
799
- if (rootTsConfig.references) {
800
- rootTsConfig.references = rootTsConfig.references.filter(
801
- (ref) => ref.path !== `./pkgs/${name}/tsconfig.json`,
802
- ) as TsConfigJson["references"];
803
- }
804
- await this.writeJson("tsconfig.json", rootTsConfig);
805
- return this;
806
- }
807
- async getDirInModule(basePath: string, name: string) {
808
- const AVOID_DIRS = ["__lib", "__scalar", `_`, `_${name}`];
809
- const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
810
- const dirs = await this.readdir(dirname);
811
- await Promise.all(
812
- dirs.map(async (dir) => {
813
- if (dir.includes("_") || AVOID_DIRS.includes(dir)) return;
814
- const dirPath = path.join(dirname, dir);
815
- if ((await stat(dirPath)).isDirectory()) {
816
- results.push(`${prefix}${dir}`);
817
- if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
818
- }
819
- }),
820
- );
821
- return results;
822
- };
823
- return await getDirs(basePath);
824
- }
825
- async commit(
826
- message: string,
827
- {
828
- init = false,
829
- add = true,
830
- identity,
831
- }: { init?: boolean; add?: boolean; identity?: { name: string; email: string } } = {},
832
- ) {
833
- if (init) await this.spawn("git", ["init", "--quiet"]);
834
- if (add) await this.spawn("git", ["add", "."]);
835
- const author = identity ? ["-c", `user.name=${identity.name}`, "-c", `user.email=${identity.email}`] : [];
836
- // Argument vector, not a shell string: a message carrying a double quote breaks the interpolated form.
837
- await this.spawn("git", [...author, "commit", "--quiet", "-m", message]);
838
- }
839
- /** `git commit` exits non-zero on an empty index, so a re-runnable caller has to ask first. */
840
- async hasChanges() {
841
- return !!(await this.spawn("git", ["status", "--porcelain"])).trim();
842
- }
843
- /** Sorted workspace-relative paths; `untracked` adds uncommitted files, still honoring `.gitignore`. */
844
- async listGitFiles(paths: string[], { untracked = false }: { untracked?: boolean } = {}) {
845
- if (!paths.length) return [];
846
- const mode = untracked ? ["--cached", "--others", "--exclude-standard"] : ["--cached"];
847
- const stdout = await this.spawn("git", ["ls-files", "-z", ...mode, "--", ...paths]);
848
- return stdout
849
- .split("\0")
850
- .filter((file) => !!file)
851
- .sort();
852
- }
853
- async #getDirHasFile(basePath: string, targetFilename: string) {
854
- if (!(await FileSys.dirExists(basePath))) return [];
855
- //? `local/` is gitignored scratch: a test's temporary workspace there has a package.json of its own.
856
- const AVOID_DIRS = ["node_modules", "dist", "public", "webkit", "local"];
857
- const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
858
- const dirs = await this.readdir(dirname);
859
- await Promise.all(
860
- dirs.map(async (dir) => {
861
- if (AVOID_DIRS.includes(dir)) return;
862
- const dirPath = path.join(dirname, dir);
863
- //* Not `stat`: a dangling symlink would throw, and this walk backs `getApps`, i.e. every command.
864
- if (await FileSys.dirExists(dirPath)) {
865
- const hasTargetFile = await FileSys.fileExists(path.join(dirPath, targetFilename));
866
- if (hasTargetFile) results.push(`${prefix}${dir}`);
867
- if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
868
- }
869
- }),
870
- );
871
- return results;
872
- };
873
- return (await getDirs(basePath)).sort((a, b) => a.localeCompare(b));
874
- }
875
-
876
- async #fromEverySys<T>(read: (sys: SysExecutor) => Promise<T[]>): Promise<T[]> {
877
- const [appNames, libNames] = await this.getSyss();
878
- const fromApps = await Promise.all(appNames.map((appName) => read(AppExecutor.from(this, appName))));
879
- const fromLibs = await Promise.all(libNames.map((libName) => read(LibExecutor.from(this, libName))));
880
- return [...fromApps.flat(), ...fromLibs.flat()];
881
- }
882
- async getScalarConstantFiles() {
883
- return await this.#fromEverySys((sys) => sys.getScalarConstantFiles());
884
- }
885
- async getConstantFiles() {
886
- return await this.#fromEverySys((sys) => sys.getConstantFiles());
887
- }
888
- async getDictionaryFiles() {
889
- return await this.#fromEverySys((sys) => sys.getDictionaryFiles());
890
- }
891
- async getViewFiles() {
892
- return await this.#fromEverySys((sys) => sys.getViewsSourceCode());
893
- }
894
- }
895
-
896
- interface NamedExecutorOptions {
897
- workspace?: WorkspaceExecutor;
898
- name: string;
899
- }
900
- interface SysExecutorOptions extends NamedExecutorOptions {
901
- type: "app" | "lib";
902
- }
903
-
904
- export class SysExecutor extends Executor {
905
- workspace: WorkspaceExecutor;
906
- override name: string;
907
- type: "app" | "lib";
908
- override emoji: string;
909
- constructor({ workspace = WorkspaceExecutor.fromRoot(), name, type }: SysExecutorOptions) {
910
- super(name, `${workspace.workspaceRoot}/${type}s/${name}`);
911
- this.workspace = workspace;
912
- this.name = name;
913
- this.type = type;
914
- this.emoji = execEmoji[type];
915
- }
916
- #akanConfig: AkanAppConfig | AkanLibConfig | null = null;
917
- async getConfig({ refresh }: { refresh?: boolean } = {}) {
918
- if (this.#akanConfig && !refresh) return this.#akanConfig;
919
- this.#akanConfig =
920
- this.type === "app"
921
- ? await AkanAppConfig.from(this as unknown as AppExecutor)
922
- : await AkanLibConfig.from(this as unknown as LibExecutor);
923
- return this.#akanConfig;
924
- }
925
- async getModules() {
926
- const path = this.type === "app" ? `apps/${this.name}/lib` : `libs/${this.name}/lib`;
927
- return await this.workspace.getDirInModule(path, this.name);
928
- }
929
- async getPageConventionViolations(): Promise<{ relativePath: string; reason: string }[]> {
930
- if (!(await this.exists("page"))) return [];
931
- const violations: { relativePath: string; reason: string }[] = [];
932
- for (const entry of await this.getAllFiles("**/*", { cwd: this.getPath("page") })) {
933
- const relativePath = entry.split(path.sep).join("/");
934
- const reason = getPageSourceFileViolation(relativePath);
935
- if (reason) violations.push({ relativePath: `page/${relativePath}`, reason });
936
- }
937
- return violations;
938
- }
939
-
940
- #scanInfo: AppInfo | LibInfo | null = null;
941
- hasScanInfo() {
942
- return this.#scanInfo !== null;
943
- }
944
- getScanInfo<AllowEmpty extends boolean = false>({
945
- allowEmpty,
946
- }: {
947
- allowEmpty?: AllowEmpty;
948
- } = {}): AllowEmpty extends true ? AppInfo | LibInfo | null : AppInfo | LibInfo {
949
- if (!this.hasScanInfo() && !allowEmpty) throw new Error("Scan info is not available");
950
- return this.#scanInfo as AllowEmpty extends true ? AppInfo | LibInfo | null : AppInfo | LibInfo;
951
- }
952
- async #seedEnvFiles(): Promise<FileContent[]> {
953
- const envDir = path.join(this.cwdPath, "env");
954
- const missing = await new EnvSeed(envDir).missing();
955
- if (!missing.length) return [];
956
- const written = await Promise.all(
957
- missing.map(({ fileName, content }) =>
958
- this.writeFile(path.join(envDir, fileName), content, { overwrite: false, silent: true }),
959
- ),
960
- );
961
- this.logger.info(
962
- `${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\`.`,
963
- );
964
- return written;
965
- }
966
- #getScanTemplateTasks(scanInfo: AppInfo | LibInfo): (Promise<FileContent[]> | null)[] {
967
- return [
968
- this.#seedEnvFiles(),
969
- this._applyTemplate({ basePath: "env", template: "env", scanInfo }),
970
- this._applyTemplate({ basePath: "lib", template: "lib", scanInfo }),
971
- this._applyTemplate({ basePath: ".", template: "server.ts", scanInfo }),
972
- this._applyTemplate({ basePath: ".", template: "client.ts", scanInfo }),
973
- this.type === "lib" ? this._applyTemplate({ basePath: ".", template: "index.ts", scanInfo }) : null,
974
- ...barrelFacetDirs.map((facet) =>
975
- this._applyTemplate({
976
- basePath: facet,
977
- template: "facetIndex/index.ts",
978
- scanInfo,
979
- options: { exec: this, facet },
980
- }),
981
- ),
982
- ...[
983
- ...scanInfo.getDatabaseModules().map((model) => [model, `lib/${model}`]),
984
- ...scanInfo.getServiceModules().map((model) => [model, `lib/_${model}`]),
985
- ...scanInfo.getScalarModules().map((model) => [model, `lib/__scalar/${model}`]),
986
- ].map(([model, basePath]) =>
987
- this._applyTemplate({ basePath, template: "moduleRoot", scanInfo, dict: { model, Model: capitalize(model) } }),
988
- ),
989
- ];
990
- }
991
- async scan({
992
- refresh = false,
993
- write = true,
994
- writeLib = write,
995
- }: {
996
- refresh?: boolean;
997
- write?: boolean;
998
- writeLib?: boolean;
999
- } = {}): Promise<AppInfo | LibInfo> {
1000
- if (this.#scanInfo && !refresh) return this.#scanInfo;
1001
- const scanInfo =
1002
- this.type === "app"
1003
- ? await AppInfo.fromExecutor(this as unknown as AppExecutor, {
1004
- refresh,
1005
- })
1006
- : await LibInfo.fromExecutor(this as unknown as LibExecutor, {
1007
- refresh,
1008
- });
1009
- //* Locked: `writeLib` rewrites dependency-lib barrels that other dev servers regenerate and watch too.
1010
- if (write)
1011
- await CodegenLock.run(this.workspace.workspaceRoot, `scan:${this.name}`, async () => {
1012
- await Promise.all(this.#getScanTemplateTasks(scanInfo));
1013
- await this.writeJson(`akan.${this.type}.json`, scanInfo.getScanResult());
1014
- await this.#updateDependencies(scanInfo);
1015
- if (writeLib) {
1016
- const libInfos = [...scanInfo.getLibInfos().values()];
1017
- await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
1018
- }
1019
- await this.syncAgentsIndex(scanInfo);
1020
- });
1021
- this.#scanInfo = scanInfo;
1022
- return scanInfo;
1023
- }
1024
- /** Rewrites only the marker block of the scoped AGENTS.md; content outside the markers belongs to the user. */
1025
- async syncAgentsIndex(scanInfo?: AppInfo | LibInfo) {
1026
- const info = scanInfo ?? (await this.scan({ write: false }));
1027
- const scope = { type: this.type, name: this.name };
1028
- const recipes = await scanScopeRecipes(this.workspace.workspaceRoot, scope, info.getScanResult().libDeps);
1029
- const block = renderScopeAgentBlock(scope, recipes);
1030
- const existing = (await this.exists("AGENTS.md")) ? await this.readFile("AGENTS.md") : null;
1031
- await this.writeFile(
1032
- "AGENTS.md",
1033
- existing?.trim() ? upsertAgentBlock(existing, block) : renderScopeAgentsMd(scope, block),
1034
- );
1035
- // CLAUDE.md 는 얇은 포인터라 최초 1회만 깔아준다 — 사용자가 지우거나 고친 것을 되살리지 않는다.
1036
- if (!(await this.exists("CLAUDE.md"))) await this.writeFile("CLAUDE.md", renderScopeClaudeMd(scope));
1037
- }
1038
- //* The root is the cached copy the dependency scan read, so a name it declares is judged by the same snapshot.
1039
- async #updateDependencies(scanInfo: AppInfo | LibInfo) {
1040
- const [rootPackageJson, packageJson] = await Promise.all([
1041
- this.workspace.getPackageJson(),
1042
- this.getPackageJson({ refresh: true }),
1043
- ]);
1044
- const { dependencies: runtime, devDependencies: typeOnly, akanConfig } = scanInfo.getScanResult();
1045
- const kept = new Set([
1046
- ...ManifestDependencies.keptBy(packageJson),
1047
- ...akanConfig.externalLibs,
1048
- ...akanConfig.trustedDependencies,
1049
- ]);
1050
- //? The scan leaves the framework out of its imports on purpose, so it is never a prune candidate.
1051
- const isKept = (dep: string) => kept.has(dep) || isAkanFrameworkDependency(dep);
1052
- const { dependencies, devDependencies, removed, unverifiable } = new ManifestDependencies(
1053
- rootPackageJson,
1054
- { runtime, typeOnly },
1055
- isKept,
1056
- ).realign(packageJson);
1057
- const manifestPath = `${this.type}s/${this.name}/package.json`;
1058
- if (removed.length)
1059
- this.logger.info(
1060
- `Removed from ${manifestPath}, declared by the root and imported nowhere: ${removed.join(", ")} (list one in akan.keepDependencies to keep it)`,
1061
- );
1062
- if (unverifiable.length)
1063
- this.logger.warn(
1064
- `${manifestPath} lists ${unverifiable.join(", ")}, which the root package.json does not declare, so sync cannot tell whether it is used; kept as is`,
1065
- );
1066
- await this.setPackageJson({ ...packageJson, dependencies, devDependencies });
1067
- }
1068
- override async getLocalFile(targetPath: string) {
1069
- const filePath = path.isAbsolute(targetPath) ? targetPath : `${this.type}s/${this.name}/${targetPath}`;
1070
- const content = await this.workspace.readFile(filePath);
1071
- return { filePath, content };
1072
- }
1073
-
1074
- async getDatabaseModules() {
1075
- return (await this.readdir("lib"))
1076
- .filter((name) => !name.startsWith("_") && !name.endsWith(".ts"))
1077
- .filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${name}.constant.ts`));
1078
- }
1079
-
1080
- async getServiceModules() {
1081
- return (await this.readdir("lib"))
1082
- .filter((name) => name.startsWith("_") && !name.startsWith("__"))
1083
- .filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${name.slice(1)}.service.ts`));
1084
- }
1085
-
1086
- async getScalarModules() {
1087
- return (await this.readdir("lib/__scalar"))
1088
- .filter((name) => !name.startsWith("_"))
1089
- .filter((name) => existsSync(`${this.cwdPath}/lib/__scalar/${name}/${name}.constant.ts`));
1090
- }
1091
-
1092
- async #getComponentModules(role: "View" | "Unit" | "Template") {
1093
- return (await this.readdir("lib"))
1094
- .filter((name) => !name.startsWith("_") && !name.endsWith(".ts"))
1095
- .filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${capitalize(name)}.${role}.tsx`));
1096
- }
1097
- async #getComponentSources(role: "View" | "Unit" | "Template") {
1098
- const modules = await this.#getComponentModules(role);
1099
- return Promise.all(modules.map((name) => this.getLocalFile(`lib/${name}/${capitalize(name)}.${role}.tsx`)));
1100
- }
1101
- async getViewComponents() {
1102
- return await this.#getComponentModules("View");
1103
- }
1104
- async getUnitComponents() {
1105
- return await this.#getComponentModules("Unit");
1106
- }
1107
- async getTemplateComponents() {
1108
- return await this.#getComponentModules("Template");
1109
- }
1110
- async getViewsSourceCode() {
1111
- return await this.#getComponentSources("View");
1112
- }
1113
- async getUnitsSourceCode() {
1114
- return await this.#getComponentSources("Unit");
1115
- }
1116
- async getTemplatesSourceCode() {
1117
- return await this.#getComponentSources("Template");
1118
- }
1119
-
1120
- async getScalarConstantFiles() {
1121
- const scalarModules = await this.getScalarModules();
1122
- return Promise.all(
1123
- scalarModules.map((scalarModule) =>
1124
- this.getLocalFile(`lib/__scalar/${scalarModule}/${scalarModule}.constant.ts`),
1125
- ),
1126
- );
1127
- }
1128
-
1129
- async getScalarDictionaryFiles() {
1130
- const scalarModules = await this.getScalarModules();
1131
- return Promise.all(
1132
- scalarModules.map((scalarModule) =>
1133
- this.getLocalFile(`lib/__scalar/${scalarModule}/${scalarModule}.dictionary.ts`),
1134
- ),
1135
- );
1136
- }
1137
-
1138
- async getConstantFiles() {
1139
- const modules = await this.getModules();
1140
- return Promise.all(modules.map((module) => this.getLocalFile(`lib/${module}/${module}.constant.ts`)));
1141
- }
1142
- async getConstantFilesWithLibs() {
1143
- const scanInfo =
1144
- this.type === "app"
1145
- ? await AppInfo.fromExecutor(this as unknown as AppExecutor)
1146
- : await LibInfo.fromExecutor(this as unknown as LibExecutor);
1147
- const sysContantFiles = await this.getConstantFiles();
1148
- const sysScalarConstantFiles = await this.getScalarConstantFiles();
1149
- const libDeps = scanInfo.getLibs();
1150
- const libConstantFiles = await Promise.all(
1151
- libDeps.map(async (lib) => [
1152
- ...(await LibExecutor.from(this, lib).getConstantFiles()),
1153
- ...(await LibExecutor.from(this, lib).getScalarConstantFiles()),
1154
- ]),
1155
- );
1156
- return [...sysContantFiles, ...sysScalarConstantFiles, ...libConstantFiles.flat()];
1157
- }
1158
- async getDictionaryFiles() {
1159
- const modules = await this.getModules();
1160
- return Promise.all(modules.map((module) => this.getLocalFile(`lib/${module}/${module}.dictionary.ts`)));
1161
- }
1162
- override async applyTemplate(options: {
1163
- basePath: string;
1164
- template: string;
1165
- dict?: { [key: string]: string };
1166
- overwrite?: boolean;
1167
- }): Promise<FileContent[]> {
1168
- const scanInfo = await this.scan();
1169
- const fileContents = await super.applyTemplate({ ...options, scanInfo });
1170
- await this.scan();
1171
- return fileContents;
1172
- }
1173
- }
1174
-
1175
- export class AppExecutor extends SysExecutor {
1176
- // Lazy: the validator pulls in `typescript` (~65MB resident).
1177
- static #routeSourceValidator: typeof import("./routeSourceValidator").RouteSourceValidator | null = null;
1178
- static async #getRouteSourceValidator() {
1179
- AppExecutor.#routeSourceValidator ??= (await import("./routeSourceValidator")).RouteSourceValidator;
1180
- return AppExecutor.#routeSourceValidator;
1181
- }
1182
- dist: Executor;
1183
- override emoji = execEmoji.app;
1184
- constructor({ workspace, name }: NamedExecutorOptions) {
1185
- super({ workspace, name, type: "app" });
1186
- this.dist = new Executor(`dist/${name}`, `${this.workspace.workspaceRoot}/dist/apps/${name}`);
1187
- }
1188
- static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
1189
- return new AppExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
1190
- }
1191
- //* Not dev output: the downloaded `bin` sources.
1192
- static readonly #keptOnStart = [path.join(".akan", "cache", "bin")];
1193
- //* Native builds moved to dist/native/<app>; the old folder may hold a signed release nobody uploaded yet.
1194
- static readonly #legacyNative = path.join(".akan", "native");
1195
- async #removeDevOutput(dir = ".akan") {
1196
- const entries = await readDirEntries(this.getPath(dir)).catch(() => [] as string[]);
1197
- await Promise.all(
1198
- entries.map(async (name) => {
1199
- const entry = path.join(dir, name);
1200
- if (entry === AppExecutor.#legacyNative) {
1201
- this.logger.warn(
1202
- `apps/${this.name}/.akan/native holds native builds from before they moved to dist/native/${this.name}: upload any release waiting in its updates folders, then delete it.`,
1203
- );
1204
- return;
1205
- }
1206
- if (AppExecutor.#keptOnStart.includes(entry)) return;
1207
- if (AppExecutor.#keptOnStart.some((kept) => kept.startsWith(`${entry}${path.sep}`)))
1208
- return await this.#removeDevOutput(entry);
1209
- await this.removeDir(entry);
1210
- }),
1211
- );
1212
- }
1213
- getEnv() {
1214
- return WorkspaceExecutor.getBaseDevEnv().env;
1215
- }
1216
- /** `AKAN_DEV_PORT` pins it; the derived port moves whenever an app directory appears or disappears. */
1217
- async getDevPort() {
1218
- const pinned = Number(process.env.AKAN_DEV_PORT);
1219
- if (Number.isInteger(pinned) && pinned > 0 && pinned <= 65_535) return pinned;
1220
- const basePort = 8282;
1221
- const appNames = (await this.workspace.getApps()).sort((a, b) => a.localeCompare(b));
1222
- const appIndex = Math.max(appNames.indexOf(this.name), 0);
1223
- const portOffset = WorkspaceExecutor.getBaseDevEnv().portOffset;
1224
- return basePort + appIndex + portOffset;
1225
- }
1226
- getCommandEnv(env: Record<string, string> = {}): Record<string, string> {
1227
- const { portOffset, repoName, serveDomain } = WorkspaceExecutor.getBaseDevEnv();
1228
- const PORT = (8282 + portOffset).toString();
1229
- return {
1230
- ...process.env,
1231
- AKAN_PUBLIC_REPO_NAME: repoName,
1232
- AKAN_PUBLIC_SERVE_DOMAIN: serveDomain,
1233
- AKAN_PUBLIC_APP_NAME: this.name,
1234
- AKAN_WORKSPACE_ROOT: this.workspace.workspaceRoot,
1235
- NODE_NO_WARNINGS: "1",
1236
- PORT,
1237
- AKAN_PUBLIC_CLIENT_PORT: PORT,
1238
- ...(portOffset ? { AKAN_PUBLIC_SERVER_PORT: PORT } : {}),
1239
- ...env,
1240
- };
1241
- }
1242
- async getDatabaseModeEnv() {
1243
- const akanConfig = await this.getConfig();
1244
- return {
1245
- AKAN_DATABASE_MODE: akanConfig.resolveDatabaseMode(),
1246
- AKAN_DATABASE_MODES: akanConfig.database.modes.join(","),
1247
- };
1248
- }
1249
- async prepareCommand(type: "build" | "start") {
1250
- const akanConfig = await this.getConfig();
1251
- const routeEnv = {
1252
- AKAN_PUBLIC_BASE_PATHS: [...akanConfig.basePaths].join(","),
1253
- AKAN_PUBLIC_API_PREFIX: akanConfig.api.prefix,
1254
- AKAN_PUBLIC_WS_PREFIX: akanConfig.api.websocketPrefix,
1255
- ...(await this.getDatabaseModeEnv()),
1256
- };
1257
- Object.assign(process.env, routeEnv);
1258
- if (type === "build") {
1259
- //* `scanSync` read the route set unfiltered; drop the cache so build phases re-read it without dev-only routes.
1260
- this.#excludeDevOnlyPages = true;
1261
- this.#pageKeys = null;
1262
- await this.dist.removeDir(this.dist.cwdPath);
1263
- await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
1264
- //* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
1265
- //* Only the web router reads `public/`, so an api-only build leaves it out.
1266
- await Promise.all([
1267
- this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
1268
- ...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
1269
- ]);
1270
- } else {
1271
- await this.#removeDevOutput();
1272
- //? `akan start` keeps the full dev surface: the incremental builder is also the file watcher.
1273
- if (!akanConfig.web.ssr || !akanConfig.web.csr)
1274
- this.logger.verbose(
1275
- `akan.config.ts disables web.${!akanConfig.web.ssr ? "ssr" : "csr"}; \`akan start\` still serves it, \`akan build\` will not`,
1276
- );
1277
- }
1278
- //? Bun auto-loads `.env`, so NODE_ENV=production can arrive unexported and send the dev server to the production
1279
- //? route cache. Set on `process.env` because the builder runs here and bakes NODE_ENV into its bundles.
1280
- if (type === "start") process.env.NODE_ENV = "development";
1281
- const devPort = type === "start" ? (await this.getDevPort()).toString() : undefined;
1282
- const env = this.getCommandEnv({
1283
- AKAN_COMMAND_TYPE: type,
1284
- ...routeEnv,
1285
- ...(devPort ? { PORT: devPort, AKAN_PUBLIC_CLIENT_PORT: devPort, AKAN_PUBLIC_SERVER_PORT: devPort } : {}),
1286
- });
1287
- // `build` runs its phases in this process, so the env is published here (only AKAN_PUBLIC_* reaches bundles).
1288
- // Ports and the operation mode are dropped: `define` would bake them in and outrank the container's own values.
1289
- if (type === "build") {
1290
- const buildEnv = { ...env };
1291
- for (const key of ["AKAN_PUBLIC_CLIENT_PORT", "AKAN_PUBLIC_SERVER_PORT", "AKAN_PUBLIC_OPERATION_MODE"]) {
1292
- delete buildEnv[key];
1293
- delete process.env[key];
1294
- }
1295
- Object.assign(process.env, buildEnv);
1296
- }
1297
- return { env };
1298
- }
1299
- #publicEnv: Record<string, string> | null = null;
1300
- getPublicEnv(...patterns: string[]) {
1301
- if (this.#publicEnv) return this.#publicEnv;
1302
- const searchPatterns = [...patterns, "AKAN_PUBLIC_*"];
1303
- const regexes = searchPatterns.map(
1304
- (pattern) =>
1305
- new RegExp(
1306
- `^${pattern
1307
- .split("*")
1308
- .map((part) => part.replace(/[.+^${}()|[\]\\?]/g, "\\$&"))
1309
- .join(".*")}$`,
1310
- ),
1311
- );
1312
- const publicEnv: Record<string, string> = {};
1313
- for (const [k, v] of Object.entries(process.env)) {
1314
- if (typeof v !== "string") continue;
1315
- if (regexes.some((r) => r.test(k))) publicEnv[k] = v;
1316
- }
1317
- this.#publicEnv = publicEnv;
1318
- return publicEnv;
1319
- }
1320
-
1321
- #akanConfig: AkanAppConfig | null = null;
1322
- override async getConfig({ refresh }: { refresh?: boolean } = {}) {
1323
- if (this.#akanConfig && !refresh) return this.#akanConfig;
1324
- this.#akanConfig = await AkanAppConfig.from(this, { bustImportCache: refresh });
1325
- return this.#akanConfig;
1326
- }
1327
-
1328
- #pageKeys: string[] | null = null;
1329
- #routeSources: AppRouteSource[] = [];
1330
- #excludeDevOnlyPages = false;
1331
- async getPageKeys({ refresh }: { refresh?: boolean } = {}): Promise<string[]> {
1332
- if (this.#pageKeys && !refresh) return this.#pageKeys;
1333
- const akanConfig = await this.getConfig();
1334
- const glob = new Bun.Glob("**/*");
1335
- const pageKeys: string[] = [];
1336
- const owners = new Map<string, { absPath: string; fromLib: boolean }>();
1337
- const devOnlyKeys = new Set<string>();
1338
- const devOnlyDirs: string[] = [];
1339
- const pageRoots = await this.getPageRoots();
1340
- const routeSources: AppRouteSource[] = [];
1341
- const libKeyPrefixes = pageRoots.map((root) => root.keyPrefix).filter(Boolean);
1342
- for (const root of pageRoots) {
1343
- if (!(await FileSys.dirExists(root.dir))) continue;
1344
- for await (const rel of glob.scan({
1345
- cwd: root.dir,
1346
- absolute: false,
1347
- onlyFiles: true,
1348
- })) {
1349
- const segments = rel.split(path.sep);
1350
- if (segments.some((s) => s === "node_modules")) continue;
1351
- const posix = `${root.keyPrefix}${segments.join("/")}`;
1352
- //* A lib folder that is a copy rather than a link (the Windows fallback) is walked into from `page` too.
1353
- if (!root.keyPrefix && libKeyPrefixes.some((prefix) => posix.startsWith(prefix))) continue;
1354
- const absPath = path.join(root.dir, ...segments);
1355
- validatePageSourceFile(posix, { filePath: absPath });
1356
- if (!isRouteSourceFile(posix)) continue;
1357
- const key = `./${posix}`;
1358
- validateSubRoutePageKey(key, akanConfig.basePaths, {
1359
- appName: this.name,
1360
- filePath: absPath,
1361
- });
1362
- const parsed = parseRouteModuleKey(key);
1363
- if (parsed.isInternalRootLayout) {
1364
- throw new Error(`[route-convention] __root_layout is reserved for Akan.js generated root layout: ${absPath}`);
1365
- }
1366
- const fromLib = !!root.keyPrefix;
1367
- const routeId = `${parsed.kind}:${parsed.pattern}`;
1368
- const owner = owners.get(routeId);
1369
- //* App-owned routes may collide (two groups, one pattern); a synced lib cannot see the other side.
1370
- if (owner && (owner.fromLib || fromLib)) {
1371
- throw new Error(
1372
- `[route-convention] duplicate ${parsed.kind} route "${parsed.pattern}" in app "${this.name}":\n- ${owner.absPath}\n- ${absPath}`,
1373
- );
1374
- }
1375
- if (!owner) owners.set(routeId, { absPath, fromLib });
1376
- const layoutSegments = getRootBoundarySegments(key);
1377
- const isRootLayout = layoutSegments !== null && isRootBoundarySegments(layoutSegments, akanConfig.basePaths);
1378
- const routeSource = await Bun.file(absPath).text();
1379
- const validator = await AppExecutor.#getRouteSourceValidator();
1380
- if (parsed.kind === "overrides") validator.validateOverridesSourceExports(routeSource, absPath);
1381
- else {
1382
- const info = validator.validateRouteSourceExports(routeSource, absPath, parsed.kind, {
1383
- rootLayout: isRootLayout,
1384
- pattern: parsed.pattern,
1385
- });
1386
- routeSources.push({ key, absPath, info });
1387
- if (info.devOnly) {
1388
- devOnlyKeys.add(key);
1389
- //* A dev-only layout takes its whole subtree, or its pages would ship without their chrome.
1390
- if (parsed.kind === "layout") devOnlyDirs.push(key.replace(/[^/]+$/, ""));
1391
- }
1392
- }
1393
- pageKeys.push(key);
1394
- }
1395
- }
1396
- pageKeys.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1397
- this.#routeSources = routeSources.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
1398
- this.#pageKeys = this.#excludeDevOnlyPages ? this.#dropDevOnlyPages(pageKeys, devOnlyKeys, devOnlyDirs) : pageKeys;
1399
- return this.#pageKeys;
1400
- }
1401
- /** Each page and layout file `getPageKeys` read, with what its chain declares; overrides files are not listed. */
1402
- async getRouteSources({ refresh }: { refresh?: boolean } = {}): Promise<AppRouteSource[]> {
1403
- await this.getPageKeys({ refresh });
1404
- return this.#routeSources;
1405
- }
1406
- #dropDevOnlyPages(pageKeys: string[], devOnlyKeys: Set<string>, devOnlyDirs: string[]): string[] {
1407
- if (!devOnlyKeys.size) return pageKeys;
1408
- const isDevOnly = (key: string) => devOnlyKeys.has(key) || devOnlyDirs.some((dir) => key.startsWith(dir));
1409
- const dropped = pageKeys.filter(isDevOnly);
1410
- this.verbose(`[route] excluded ${dropped.length} dev-only route file(s) from the build: ${dropped.join(", ")}`);
1411
- return pageKeys.filter((key) => !isDevOnly(key));
1412
- }
1413
- /** Lib roots are the `syncPages` symlinks, listed because neither Bun's glob nor TS `include` crosses one. */
1414
- async getPageRoots(): Promise<PageRoot[]> {
1415
- const akanConfig = await this.getConfig();
1416
- const pageDir = `${this.cwdPath}/page`;
1417
- const roots: PageRoot[] = [{ dir: pageDir, realDir: pageDir, keyPrefix: "" }];
1418
- for (const parent of AppExecutor.#pageLibParents(akanConfig.basePaths)) {
1419
- const libsDir = `${pageDir}/${parent}${AppExecutor.#pageLibsDir}`;
1420
- const entries = await readDirEntries(libsDir).catch(() => [] as string[]);
1421
- for (const entry of entries.sort()) {
1422
- const dir = `${libsDir}/${entry}`;
1423
- if (!(await FileSys.dirExists(dir))) continue;
1424
- roots.push({ dir, realDir: await realpath(dir), keyPrefix: `${parent}${AppExecutor.#pageLibsDir}/${entry}/` });
1425
- }
1426
- }
1427
- return roots;
1428
- }
1429
- setPageKeys(pageKeys: string[]) {
1430
- this.#pageKeys = pageKeys;
1431
- }
1432
-
1433
- static readonly #pageLibsDir = "(libs)";
1434
- static #pageLibParents(basePaths: Iterable<string>): string[] {
1435
- const parents = [...basePaths].map((basePath) => `${basePath}/`);
1436
- return parents.length ? parents : [""];
1437
- }
1438
- /** Whether the linked page set changed, which makes the app's route keys stale. */
1439
- async syncPages(libDeps: string[]): Promise<boolean> {
1440
- const akanConfig = await this.getConfig();
1441
- const parents = AppExecutor.#pageLibParents(akanConfig.basePaths);
1442
- const libs = await this.#resolvePageLibs(akanConfig.syncPageLibs, libDeps);
1443
- //* Not `getPageRoots`: it drops links whose target is gone, exactly the ones a sync must clean up.
1444
- const linked = (
1445
- await Promise.all(
1446
- parents.map(async (parent) => {
1447
- const libsDir = `${this.cwdPath}/page/${parent}${AppExecutor.#pageLibsDir}`;
1448
- const entries = await readDirEntries(libsDir).catch(() => [] as string[]);
1449
- return entries.map((entry) => `${parent}${AppExecutor.#pageLibsDir}/${entry}/`);
1450
- }),
1451
- )
1452
- ).flat();
1453
- const wanted = parents.flatMap((parent) => libs.map((lib) => `${parent}${AppExecutor.#pageLibsDir}/(${lib})/`));
1454
- //* A copy — the Windows fallback when a junction is refused — does not follow its lib, so only links are current.
1455
- const isLink = async (key: string) =>
1456
- (await lstat(`${this.cwdPath}/page/${key.slice(0, -1)}`).catch(() => null))?.isSymbolicLink() ?? false;
1457
- if (linked.sort().join(",") === wanted.sort().join(",") && (await Promise.all(linked.map(isLink))).every(Boolean))
1458
- return false;
1459
- await Promise.all(
1460
- parents.map((parent) => this.removeDir(`${this.cwdPath}/page/${parent}${AppExecutor.#pageLibsDir}`)),
1461
- );
1462
- for (const parent of parents) {
1463
- if (!libs.length) break;
1464
- const libsDir = `${this.cwdPath}/page/${parent}${AppExecutor.#pageLibsDir}`;
1465
- await this.mkdir(libsDir);
1466
- await Promise.all(
1467
- libs.map((lib) =>
1468
- AppExecutor.#linkLibAsset(`${this.workspace.workspaceRoot}/libs/${lib}/page`, `${libsDir}/(${lib})`),
1469
- ),
1470
- );
1471
- }
1472
- this.#pageKeys = null;
1473
- return true;
1474
- }
1475
- async #resolvePageLibs(syncPageLibs: string[] | boolean, libDeps: string[]): Promise<string[]> {
1476
- if (!syncPageLibs) return [];
1477
- const hasPageDir = async (lib: string) =>
1478
- await FileSys.dirExists(`${this.workspace.workspaceRoot}/libs/${lib}/page`);
1479
- if (syncPageLibs === true) {
1480
- const libs: string[] = [];
1481
- for (const lib of libDeps) if (await hasPageDir(lib)) libs.push(lib);
1482
- return libs;
1483
- }
1484
- for (const lib of syncPageLibs) {
1485
- if (!libDeps.includes(lib))
1486
- throw new Error(
1487
- `[syncPageLibs] app "${this.name}" lists lib "${lib}" but does not depend on it (deps: ${libDeps.join(", ") || "none"})`,
1488
- );
1489
- if (!(await hasPageDir(lib)))
1490
- throw new Error(`[syncPageLibs] app "${this.name}" lists lib "${lib}" but libs/${lib}/page does not exist`);
1491
- }
1492
- return [...syncPageLibs];
1493
- }
1494
- async syncAssets(libDeps: string[]) {
1495
- await Promise.all((["public", "private"] as const).map((facet) => this.#syncLibAssets(facet, libDeps)));
1496
- }
1497
- async #syncLibAssets(facet: "public" | "private", libDeps: string[]) {
1498
- const libLinkPath = `${this.cwdPath}/${facet}/libs`;
1499
- await this.removeDir(libLinkPath);
1500
- const targetDeps = [] as string[];
1501
- for (const dep of libDeps) {
1502
- if (await this.exists(`${this.workspace.workspaceRoot}/libs/${dep}/${facet}`)) targetDeps.push(dep);
1503
- }
1504
- if (!targetDeps.length) return;
1505
- await this.mkdir(libLinkPath);
1506
- await Promise.all(
1507
- targetDeps.map((dep) =>
1508
- AppExecutor.#linkLibAsset(`${this.workspace.workspaceRoot}/libs/${dep}/${facet}`, `${libLinkPath}/${dep}`),
1509
- ),
1510
- );
1511
- }
1512
- static async #linkLibAsset(targetPath: string, linkPath: string) {
1513
- //* Relative, so it survives a remount (containers, CI); a Windows junction needs an absolute target.
1514
- const isWindows = process.platform === "win32";
1515
- try {
1516
- const target = isWindows ? targetPath : path.relative(path.dirname(linkPath), targetPath);
1517
- await symlink(target, linkPath, isWindows ? "junction" : "dir");
1518
- } catch (error) {
1519
- if (!isWindows) throw error;
1520
- await mkdir(linkPath, { recursive: true });
1521
- await cpEntry(targetPath, linkPath, { recursive: true, dereference: true, force: true });
1522
- }
1523
- }
1524
- async scanSync({ refresh = false, write = true }: { refresh?: boolean; write?: boolean } = {}) {
1525
- const scanInfo = (await this.scan({
1526
- refresh,
1527
- write,
1528
- writeLib: write,
1529
- })) as AppInfo;
1530
- if (write) await this.syncAssets(scanInfo.getScanResult().libDeps);
1531
- //* `scan` read the routes off the page tree this sync may be about to change, so re-read them.
1532
- if (write && (await this.syncPages(scanInfo.getScanResult().libDeps)))
1533
- scanInfo.setRoutes(await this.getPageKeys({ refresh: true }));
1534
- if (write) await this.#runPluginSyncAssets();
1535
- return scanInfo;
1536
- }
1537
- async #runPluginSyncAssets() {
1538
- const plugins = await this.collectPlugins();
1539
- if (!plugins.some((plugin) => plugin.syncAssets)) return;
1540
- const ctx = this.#makeSyncContext();
1541
- for (const plugin of plugins) await plugin.syncAssets?.(ctx);
1542
- }
1543
- #makeSyncContext(): AkanSyncContext {
1544
- return {
1545
- appName: this.name,
1546
- appPath: this.cwdPath,
1547
- executor: this,
1548
- getPath: (rel) => this.getPath(rel),
1549
- fileExists: (rel) => FileSys.fileExists(this.getPath(rel)),
1550
- readFile: (rel) => this.readFile(rel),
1551
- writeFile: async (rel, content, opts) => {
1552
- await this.writeFile(rel, content, opts);
1553
- },
1554
- readEnvClient: async () => {
1555
- const envClientPath = path.join(this.cwdPath, "env", "env.client.ts");
1556
- if (!(await FileSys.fileExists(envClientPath))) return null;
1557
- try {
1558
- const envUrl = pathToFileURL(envClientPath);
1559
- envUrl.searchParams.set("t", String(Date.now()));
1560
- const envModule = (await import(envUrl.href)) as { env?: Record<string, unknown> };
1561
- return envModule.env ?? null;
1562
- } catch {
1563
- return null;
1564
- }
1565
- },
1566
- };
1567
- }
1568
- async collectPlugins(): Promise<AkanPlugin[]> {
1569
- const scanInfo = (await this.scan({ write: false })) as AppInfo;
1570
- const libDeps = scanInfo.getLibs();
1571
- const appConfig = await this.getConfig();
1572
- const collected: AkanPlugin[] = [...appConfig.plugins];
1573
- for (const libName of libDeps) {
1574
- const libConfig = await LibExecutor.from(this, libName)
1575
- .getConfig()
1576
- .catch(() => null);
1577
- if (libConfig) collected.push(...libConfig.plugins);
1578
- }
1579
- const seen = new Set<string>();
1580
- return collected.filter((plugin) => {
1581
- if (seen.has(plugin.name)) return false;
1582
- seen.add(plugin.name);
1583
- return true;
1584
- });
1585
- }
1586
- async increaseBuildNum() {
1587
- await increaseBuildNum(this);
1588
- }
1589
- async decreaseBuildNum() {
1590
- await decreaseBuildNum(this);
1591
- }
1592
- }
1593
- export class LibExecutor extends SysExecutor {
1594
- dist: Executor;
1595
- override emoji = execEmoji.lib;
1596
- constructor({ workspace, name }: NamedExecutorOptions) {
1597
- super({ workspace, name, type: "lib" });
1598
- this.dist = new Executor(`dist/${name}`, `${this.workspace.workspaceRoot}/dist/libs/${name}`);
1599
- }
1600
- static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
1601
- return new LibExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
1602
- }
1603
-
1604
- #akanConfig: AkanLibConfig | null = null;
1605
- override async getConfig({ refresh }: { refresh?: boolean } = {}) {
1606
- if (this.#akanConfig && !refresh) return this.#akanConfig;
1607
- this.#akanConfig = await AkanLibConfig.from(this, { bustImportCache: refresh });
1608
- return this.#akanConfig;
1609
- }
1610
- }
1611
-
1612
- export class PkgExecutor extends Executor {
1613
- workspace: WorkspaceExecutor;
1614
- override name: string;
1615
- dist: Executor;
1616
- override emoji = execEmoji.pkg;
1617
- constructor({ workspace = WorkspaceExecutor.fromRoot(), name }: NamedExecutorOptions) {
1618
- super(name, `${workspace.workspaceRoot}/pkgs/${name}`);
1619
- this.workspace = workspace;
1620
- this.name = name;
1621
- this.dist = new Executor(`dist/${name}`, `${this.workspace.workspaceRoot}/dist/pkgs/${name}`);
1622
- }
1623
- static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
1624
- return new PkgExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
1625
- }
1626
-
1627
- #scanInfo: PkgInfo | null = null;
1628
- async scan({ refresh }: { refresh?: boolean } = {}): Promise<PkgInfo> {
1629
- if (this.#scanInfo && !refresh) return this.#scanInfo;
1630
- const scanInfo = await PkgInfo.fromExecutor(this, { refresh });
1631
- this.#scanInfo = scanInfo;
1632
- return scanInfo;
1633
- }
1634
- async #getDependencyVersion(rootPackageJson: PackageJson, dep: string): Promise<string | undefined> {
1635
- const rootDeps = {
1636
- ...rootPackageJson.dependencies,
1637
- ...rootPackageJson.devDependencies,
1638
- };
1639
- const rootVersion = rootDeps[dep];
1640
- if (rootVersion) return rootVersion;
1641
- // Overrides never reach a consumer's install, so a pinned transitive dep is published as a dependency.
1642
- const overrideVersion = rootPackageJson.overrides?.[dep];
1643
- if (typeof overrideVersion === "string") return overrideVersion;
1644
-
1645
- try {
1646
- const packageJsonPath = `pkgs/${dep}/package.json`;
1647
- if (!(await Bun.file(path.join(this.workspace.workspaceRoot, packageJsonPath)).exists())) return undefined;
1648
- const packageJson = await this.workspace.readJson(packageJsonPath);
1649
- if ((packageJson as PackageJson).name === dep) return (packageJson as PackageJson).version;
1650
- } catch {
1651
- return undefined;
1652
- }
1653
- }
1654
- async #toDependencyMap(
1655
- rootPackageJson: PackageJson,
1656
- dependencies: string[] = [],
1657
- devDependencies: string[] = [],
1658
- ): Promise<Pick<PackageJson, "dependencies" | "devDependencies">> {
1659
- const dependencyNames = [...new Set(dependencies)].sort();
1660
- const devDependencyNames = [...new Set(devDependencies)]
1661
- .filter((dep) => !dependencyNames.includes(dep))
1662
- .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1663
- const dependencyVersions = new Map<string, string>();
1664
- const missingDeps: string[] = [];
1665
- for (const dep of [...dependencyNames, ...devDependencyNames]) {
1666
- const version = await this.#getDependencyVersion(rootPackageJson, dep);
1667
- if (version) dependencyVersions.set(dep, version);
1668
- else missingDeps.push(dep);
1669
- }
1670
- if (missingDeps.length > 0)
1671
- throw new Error(`Missing dependency versions in root package.json: ${missingDeps.join(", ")}`);
1672
-
1673
- const toDependencyMap = (names: string[]) =>
1674
- Object.fromEntries(names.map((dep) => [dep, dependencyVersions.get(dep) as string]));
1675
- return { dependencies: toDependencyMap(dependencyNames), devDependencies: toDependencyMap(devDependencyNames) };
1676
- }
1677
- async updatePackageJsonDependencies(
1678
- dependencies: string[] = [],
1679
- devDependencies: string[] = [],
1680
- ): Promise<PackageJson> {
1681
- const [rootPackageJson, pkgJson] = await Promise.all([this.workspace.getPackageJson(), this.getPackageJson()]);
1682
- const dependencyMaps = await this.#toDependencyMap(rootPackageJson, dependencies, devDependencies);
1683
- const newPkgJson = {
1684
- ...pkgJson,
1685
- ...dependencyMaps,
1686
- };
1687
- await this.writeJson("package.json", newPkgJson);
1688
- return newPkgJson;
1689
- }
1690
- async generateDistPackageJson(dependencies: string[] = [], devDependencies: string[] = []): Promise<PackageJson> {
1691
- const [rootPackageJson, pkgJson] = await Promise.all([this.workspace.getPackageJson(), this.getPackageJson()]);
1692
- const dependencyMaps = await this.#toDependencyMap(rootPackageJson, dependencies, devDependencies);
1693
- const distPkgJson: PackageJson = {
1694
- ...pkgJson,
1695
- type: "module",
1696
- exports: {
1697
- ...pkgJson.exports,
1698
- ".": {
1699
- import: "./index.ts",
1700
- types: "./index.ts",
1701
- default: "./index.ts",
1702
- },
1703
- },
1704
- engines: { bun: ">=1.4.4" },
1705
- ...dependencyMaps,
1706
- };
1707
- await Promise.all([this.dist.writeJson("package.json", distPkgJson), this.writeJson("package.json", distPkgJson)]);
1708
- return distPkgJson;
1709
- }
1710
- async build(): Promise<void> {
1711
- await Bun.build({
1712
- root: this.cwdPath,
1713
- entrypoints: [`${this.cwdPath}/index.ts`],
1714
- splitting: false,
1715
- target: "bun",
1716
- });
1717
- await this.cp(`${this.cwdPath}/dist`, this.dist.cwdPath);
1718
- }
1719
- async generateTsconfigJson(): Promise<TsConfigJson> {
1720
- const [rootTsconfig, pkgTsconfig] = await Promise.all([this.workspace.getTsConfig(), this.getTsConfig()]);
1721
- const tsconfig: TsConfigJson = {
1722
- ...rootTsconfig,
1723
- ...pkgTsconfig,
1724
- compilerOptions: {
1725
- ...rootTsconfig.compilerOptions,
1726
- ...pkgTsconfig.compilerOptions,
1727
- paths: {},
1728
- },
1729
- };
1730
- await this.dist.writeJson("tsconfig.json", tsconfig);
1731
- return tsconfig;
1732
- }
1733
- }
1734
-
1735
- interface ModuleExecutorOptions {
1736
- sys: SysExecutor;
1737
- name: string;
1738
- }
1739
- export class ModuleExecutor extends Executor {
1740
- sys: SysExecutor;
1741
- override emoji = execEmoji.module;
1742
- constructor({ sys, name }: ModuleExecutorOptions) {
1743
- super(name, `${sys.workspace.workspaceRoot}/${sys.type}s/${sys.name}/lib/${name}`);
1744
- this.sys = sys;
1745
- }
1746
- static from(sysExecutor: SysExecutor, name: string) {
1747
- return new ModuleExecutor({ sys: sysExecutor, name });
1748
- }
1749
- }
1
+ export { AppExecutor, type AppRouteSource, type PageRoot } from "./executors/appExecutor";
2
+ export { CommandExecutionError, type CommandExecutionErrorOptions } from "./executors/commandExecutionError";
3
+ export { Executor, execEmoji, type WrittenFileContent } from "./executors/executor";
4
+ export { LibExecutor } from "./executors/libExecutor";
5
+ export { ModuleExecutor } from "./executors/moduleExecutor";
6
+ export { PkgExecutor } from "./executors/pkgExecutor";
7
+ export { SysExecutor } from "./executors/sysExecutor";
8
+ export { parseEnvFile, WorkspaceExecutor } from "./executors/workspaceExecutor";