@akanjs/cli 3.1.1-rc.16 → 3.1.1-rc.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-23ewzxqa.js → CodeAgent-fbcq8vks.js} +2 -2
  3. package/{CodeTui-kc99fk78.js → CodeTui-0626gxqd.js} +1 -1
  4. package/TunnelShare-2p24xxza.js +14 -0
  5. package/agent.command-hpza0pg9.js +46 -0
  6. package/akanCode.js +5 -3
  7. package/{application.command-bvfd1680.js → application.command-3a7q1hs2.js} +11 -10
  8. package/{applicationBuildRunner-4ajaesk1.js → applicationBuildRunner-s7yt71j4.js} +5 -5
  9. package/buildBatch.proc.js +6 -6
  10. package/{cloud.command-f2w40fyy.js → cloud.command-4vg0pcea.js} +15 -14
  11. package/cloud.script-nkmeyhet.js +25 -0
  12. package/{code.command-dbhhnahn.js → code.command-fbntb67p.js} +6 -6
  13. package/commandManifest.json +1 -1
  14. package/{context.command-yswjwv6y.js → context.command-31rm54v0.js} +18 -18
  15. package/context.runner-w01a32ph.js +26 -0
  16. package/{guideline.command-ztx6dkpk.js → guideline.command-cv3by2ng.js} +3 -3
  17. package/guidelines/conventions/core.md +104 -0
  18. package/guidelines/conventions/rules/app.md +83 -0
  19. package/guidelines/conventions/rules/auth.md +45 -0
  20. package/guidelines/conventions/rules/config.md +56 -0
  21. package/guidelines/conventions/rules/constant.md +24 -0
  22. package/guidelines/conventions/rules/gates.md +31 -0
  23. package/guidelines/conventions/rules/layer.md +25 -0
  24. package/guidelines/conventions/rules/migration.md +27 -0
  25. package/guidelines/conventions/rules/module.md +90 -0
  26. package/guidelines/conventions/rules/page.md +56 -0
  27. package/guidelines/conventions/rules/sensitive.md +16 -0
  28. package/guidelines/conventions/rules/server.md +86 -0
  29. package/guidelines/conventions/rules/ssr.md +47 -0
  30. package/guidelines/conventions/rules/style.md +43 -0
  31. package/guidelines/conventions/rules/test.md +34 -0
  32. package/guidelines/conventions/rules/ts.md +95 -0
  33. package/guidelines/conventions/rules/tsx.md +75 -0
  34. package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
  35. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +3 -3
  36. package/incrementalBuilder.proc.js +6 -6
  37. package/{index-xjwcp91m.js → index-05nxx4m5.js} +43 -12
  38. package/{index-k9k18vq9.js → index-0ht91675.js} +37 -59
  39. package/{index-er16p89s.js → index-0zwznvv1.js} +1 -1
  40. package/{index-76jwsm3g.js → index-0zyatd10.js} +2 -2
  41. package/{index-97fsvy66.js → index-12kzwak1.js} +3 -3
  42. package/{index-005dqc83.js → index-1dhf8ymv.js} +2 -2
  43. package/{index-00ke4phc.js → index-3gccwenr.js} +1 -1
  44. package/{index-2epb3wgh.js → index-3txrjt6n.js} +2 -2
  45. package/{index-7ndgffg4.js → index-57q1ayd2.js} +18 -1240
  46. package/index-5kh9scvs.js +514 -0
  47. package/index-5n5hds19.js +1246 -0
  48. package/{index-9sa6abze.js → index-6269mf2s.js} +10 -9
  49. package/{index-921cxqrd.js → index-64g9fsjy.js} +41 -12
  50. package/index-7zeb5r1p.js +653 -0
  51. package/{index-s4c2y5gs.js → index-8s8b4eba.js} +45 -4
  52. package/{index-4332q6yj.js → index-922k2zwq.js} +3 -3
  53. package/{index-m6qgr1rx.js → index-9ndw5d8j.js} +7 -7
  54. package/{index-xfp4dcnx.js → index-et6ce601.js} +1 -1
  55. package/{index-saj9cx3a.js → index-f5adsa58.js} +4 -4
  56. package/{index-vgt25eh1.js → index-fbewhg4g.js} +7 -32
  57. package/{index-ysyt782g.js → index-hm7x0c11.js} +4 -4
  58. package/{index-2p1brf5e.js → index-hvv5rnaq.js} +2 -2
  59. package/index-jje9qzyq.js +27 -0
  60. package/{index-rxse80x6.js → index-js1gj6f6.js} +12 -10
  61. package/{index-p2pahmsa.js → index-kjrvwzav.js} +3 -3
  62. package/index-m6r88hhr.js +3582 -0
  63. package/{index-mk391h0z.js → index-mt0wa941.js} +4 -4
  64. package/{index-m93qg20j.js → index-mwj9q2ya.js} +1 -1
  65. package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
  66. package/index-r2wedvqn.js +138 -0
  67. package/{index-gxj80jz7.js → index-rvynj5gz.js} +1 -1
  68. package/{index-m54n0v29.js → index-tdv66eah.js} +4 -4
  69. package/{index-vq77g679.js → index-w134p86k.js} +1 -1
  70. package/{index-deeskxjh.js → index-wfczhj1z.js} +14 -36
  71. package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
  72. package/{index-qx4r4cj2.js → index-x5ecanqh.js} +2 -2
  73. package/{index-nzfgyw3b.js → index-zre4m2ce.js} +4 -4
  74. package/index.js +23 -22
  75. package/{library.command-hmbkcwzw.js → library.command-sh70fyvy.js} +3 -3
  76. package/{localRegistry.command-sq5p4c9x.js → localRegistry.command-2nbyy84d.js} +14 -13
  77. package/{module.command-n4z29zcv.js → module.command-n0bmtzwy.js} +5 -5
  78. package/{package.command-20025dy3.js → package.command-7h9r51bz.js} +3 -3
  79. package/package.json +2 -2
  80. package/{page.command-q8fvpjer.js → page.command-vjtpfbb1.js} +3 -3
  81. package/{pipeline.command-8j97fq88.js → pipeline.command-c93se3ar.js} +2 -2
  82. package/{primitive.command-e5y6dqp1.js → primitive.command-a3075qp2.js} +6 -6
  83. package/{projectTypecheck-tbdye9k3.js → projectTypecheck-sf9xwaga.js} +1 -1
  84. package/{prompter-76k56b37.js → prompter-hgcta8pb.js} +1 -1
  85. package/quality.command-dw1y9hmy.js +76 -0
  86. package/{repair.command-dq1gckth.js → repair.command-tg57d8yt.js} +5 -5
  87. package/{scalar.command-5vwf152w.js → scalar.command-cwzge353.js} +4 -4
  88. package/skills/akan-agent/SKILL.md +36 -0
  89. package/skills/akan-debug/SKILL.md +3 -3
  90. package/skills/akan-deps/SKILL.md +1 -2
  91. package/skills/akan-mcp/SKILL.md +40 -0
  92. package/skills/akan-page/SKILL.md +44 -0
  93. package/skills/akan-query/SKILL.md +38 -0
  94. package/skills/akan-runtime/SKILL.md +40 -0
  95. package/skills/akan-scaffold/SKILL.md +16 -6
  96. package/skills/akan-transport/SKILL.md +40 -0
  97. package/skills/akan-validate/SKILL.md +13 -11
  98. package/{subspace.command-182be8vj.js → subspace.command-3h03c7kc.js} +8 -8
  99. package/templates/workspaceRoot/.gitignore.template +3 -0
  100. package/templates/workspaceRoot/AGENTS.md.template +4 -10
  101. package/{tunnel.command-bfzj7xkb.js → tunnel.command-czaz6ys4.js} +7 -7
  102. package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
  103. package/typecheck.proc.js +6 -1
  104. package/verify.command-nzwhtz71.js +91 -0
  105. package/{workflow.command-3g53242s.js → workflow.command-srhky88x.js} +23 -13
  106. package/{workspace.command-h7399jwv.js → workspace.command-9stchcd2.js} +31 -29
  107. package/TunnelShare-dk2gw78d.js +0 -14
  108. package/agent.command-knp5j7bq.js +0 -25
  109. package/cloud.script-2r82sv0f.js +0 -24
  110. package/context.runner-c3wsh2jw.js +0 -26
  111. package/guidelines/conventions/conventions.instruction.md +0 -663
  112. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
  113. package/index-4t4qb8jg.js +0 -279
  114. package/index-hvg3esm0.js +0 -1844
  115. package/index-zzvvc845.js +0 -74
  116. package/quality.command-168pt5vm.js +0 -1788
  117. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
  118. package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
@@ -1,6 +1,14 @@
1
1
  // @bun
2
2
  import {
3
- ApplicationBuildReporter,
3
+ AppInfo,
4
+ CommandExecutionError,
5
+ WorkspaceExecutor,
6
+ SysExecutor,
7
+ AppExecutor,
8
+ LibExecutor,
9
+ PkgExecutor
10
+ } from "./index-64g9fsjy.js";
11
+ import {
4
12
  UNAVAILABLE_REDIS_HOST,
5
13
  redisTunnelPolicy,
6
14
  BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
@@ -35,53 +43,31 @@ import {
35
43
  filesChangedSince,
36
44
  HmrWatcher,
37
45
  WatchRootResolver
38
- } from "./index-5nd1wtkv.js";
46
+ } from "./index-p6x5b7hr.js";
39
47
  import {
40
48
  runner,
41
- script,
42
- markCliErrorPrinted,
43
49
  assertPromptable
44
- } from "./index-00ke4phc.js";
45
- import {
46
- AppInfo,
47
- CommandExecutionError,
48
- WorkspaceExecutor,
49
- SysExecutor,
50
- AppExecutor,
51
- LibExecutor,
52
- PkgExecutor
53
- } from "./index-921cxqrd.js";
50
+ } from "./index-3gccwenr.js";
54
51
  import {
55
52
  UpdatePackFolder,
56
53
  UpdateUploader,
57
54
  NativePublicEnv,
58
55
  NativeApp
59
- } from "./index-p2pahmsa.js";
56
+ } from "./index-kjrvwzav.js";
60
57
  import {
61
58
  DesktopServerStage
62
- } from "./index-vq77g679.js";
59
+ } from "./index-w134p86k.js";
63
60
  import {
64
61
  resolveMobileTargets,
65
62
  resolveAppId
66
63
  } from "./index-m9jj544v.js";
67
64
  import {
68
- LibraryScript
69
- } from "./index-2p1brf5e.js";
70
- import {
71
- stripAnsi
72
- } from "./index-7md2g9vw.js";
73
- import {
74
- SlicePlanner,
75
- formatSlicePlan
76
- } from "./index-m93qg20j.js";
65
+ SlicePlanner
66
+ } from "./index-mwj9q2ya.js";
77
67
  import {
78
68
  openBrowser
79
69
  } from "./index-9dp031by.js";
80
70
 
81
- // pkgs/@akanjs/cli/application/application.script.ts
82
- import { confirm } from "@inquirer/prompts";
83
- import { Logger as Logger6, toError as toError2 } from "akanjs/common";
84
-
85
71
  // pkgs/@akanjs/cli/application/application.runner.ts
86
72
  import { existsSync, realpathSync } from "fs";
87
73
  import path5 from "path";
@@ -1909,7 +1895,7 @@ ${uniqueCandidates.map((candidate) => ` - ${candidate}`).join(`
1909
1895
 
1910
1896
  // pkgs/@akanjs/cli/application/application.runner.ts
1911
1897
  import { Logger as Logger3, toError } from "akanjs/common";
1912
- var loadBuildRunner = async () => (await import("./applicationBuildRunner-4ajaesk1.js")).ApplicationBuildRunner;
1898
+ var loadBuildRunner = async () => (await import("./applicationBuildRunner-s7yt71j4.js")).ApplicationBuildRunner;
1913
1899
  var loadPrompts = async () => await import("@inquirer/prompts");
1914
1900
 
1915
1901
  class ApplicationRunner extends runner("application") {
@@ -2110,7 +2096,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2110
2096
  await new (await loadBuildRunner())(app).typecheck(options);
2111
2097
  }
2112
2098
  async typecheckLibrary(lib, options = {}) {
2113
- const { ProjectTypecheck } = await import("./projectTypecheck-tbdye9k3.js");
2099
+ const { ProjectTypecheck } = await import("./projectTypecheck-sf9xwaga.js");
2114
2100
  const root = lib.workspace.workspaceRoot;
2115
2101
  await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
2116
2102
  "../../server.ts",
@@ -2534,1212 +2520,4 @@ ${detail}`
2534
2520
  }
2535
2521
  }
2536
2522
 
2537
- // pkgs/@akanjs/cli/application/hostProcessProbe.ts
2538
- import { readdirSync, readFileSync, readlinkSync } from "fs";
2539
-
2540
- class HostProcessProbe {
2541
- static timeoutMs = 3000;
2542
- static win32TimeoutMs = 20000;
2543
- static #procTcpListen = "0A";
2544
- static #win32ProcessQuery = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress";
2545
- platform;
2546
- #win32Table = null;
2547
- constructor(platform = process.platform) {
2548
- this.platform = platform;
2549
- }
2550
- async listenersOn(port) {
2551
- if (this.platform === "win32")
2552
- return HostProcessProbe.parseNetstat(await HostProcessProbe.run(["netstat", "-ano"]), port);
2553
- if (this.platform === "linux")
2554
- return HostProcessProbe.#procListenersOn(port);
2555
- const output = await HostProcessProbe.run(["lsof", "-ti", `tcp:${port}`, "-sTCP:LISTEN"]);
2556
- return [
2557
- ...new Set(output.split(`
2558
- `).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))
2559
- ];
2560
- }
2561
- async parentOf(pid) {
2562
- if (this.platform === "win32") {
2563
- const child = await this.#win32Process(pid);
2564
- const parent = child ? await this.#win32Process(child.ppid) : null;
2565
- return child && parent ? HostProcessProbe.parentPidOf(child, parent) : null;
2566
- }
2567
- if (this.platform === "linux") {
2568
- const stat = HostProcessProbe.#readProc(pid, "stat");
2569
- return stat === null ? null : HostProcessProbe.parseProcStatPpid(stat);
2570
- }
2571
- const parsed = Number((await HostProcessProbe.run(["ps", "-p", String(pid), "-o", "ppid="])).trim());
2572
- return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
2573
- }
2574
- async commandOf(pid) {
2575
- if (this.platform === "win32")
2576
- return (await this.#win32Process(pid))?.command ?? null;
2577
- if (this.platform === "linux") {
2578
- const cmdline = HostProcessProbe.#readProc(pid, "cmdline");
2579
- return cmdline?.split("\x00").filter(Boolean).join(" ") || null;
2580
- }
2581
- return (await HostProcessProbe.run(["ps", "-ww", "-p", String(pid), "-o", "command="])).trim() || null;
2582
- }
2583
- static parentPidOf(child, parent) {
2584
- if (child.ppid !== parent.pid)
2585
- return null;
2586
- if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
2587
- return null;
2588
- return parent.pid;
2589
- }
2590
- static parseNetstat(output, port) {
2591
- const pids = new Set;
2592
- for (const line of output.split(/\r?\n/)) {
2593
- const fields = line.trim().split(/\s+/);
2594
- if (fields[0] !== "TCP" || fields.length < 5)
2595
- continue;
2596
- const [, local, remote] = fields;
2597
- if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
2598
- continue;
2599
- const pid = Number(fields.at(-1));
2600
- if (Number.isInteger(pid) && pid > 0)
2601
- pids.add(pid);
2602
- }
2603
- return [...pids];
2604
- }
2605
- static parseProcNetTcp(text, port) {
2606
- const inodes = [];
2607
- for (const line of text.split(`
2608
- `).slice(1)) {
2609
- const fields = line.trim().split(/\s+/);
2610
- const [, local, , state, , , , , , inode] = fields;
2611
- if (!local || !inode || state !== HostProcessProbe.#procTcpListen || inode === "0")
2612
- continue;
2613
- if (Number.parseInt(local.slice(local.lastIndexOf(":") + 1), 16) === port)
2614
- inodes.push(inode);
2615
- }
2616
- return inodes;
2617
- }
2618
- static parseProcStatPpid(stat) {
2619
- const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
2620
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
2621
- }
2622
- static parseWin32Processes(json) {
2623
- const table = new Map;
2624
- let parsed;
2625
- try {
2626
- parsed = JSON.parse(json.trim() || "[]");
2627
- } catch {
2628
- return table;
2629
- }
2630
- const rows = Array.isArray(parsed) ? parsed : [parsed];
2631
- for (const row of rows) {
2632
- if (typeof row?.ProcessId !== "number")
2633
- continue;
2634
- table.set(row.ProcessId, {
2635
- pid: row.ProcessId,
2636
- ppid: row.ParentProcessId ?? 0,
2637
- command: row.CommandLine?.trim() || null,
2638
- startedAt: HostProcessProbe.#parseCimDate(row.CreationDate)
2639
- });
2640
- }
2641
- return table;
2642
- }
2643
- static async run(command, timeoutMs = HostProcessProbe.timeoutMs) {
2644
- let proc;
2645
- try {
2646
- proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
2647
- } catch {
2648
- return "";
2649
- }
2650
- const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
2651
- try {
2652
- return await new Response(proc.stdout).text();
2653
- } catch {
2654
- return "";
2655
- } finally {
2656
- clearTimeout(timer);
2657
- }
2658
- }
2659
- async#win32Process(pid) {
2660
- this.#win32Table ??= await HostProcessProbe.#queryWin32Processes();
2661
- if (!this.#win32Table.has(pid))
2662
- this.#win32Table = await HostProcessProbe.#queryWin32Processes();
2663
- return this.#win32Table.get(pid) ?? null;
2664
- }
2665
- static async#queryWin32Processes() {
2666
- const output = await HostProcessProbe.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", HostProcessProbe.#win32ProcessQuery], HostProcessProbe.win32TimeoutMs);
2667
- return HostProcessProbe.parseWin32Processes(output);
2668
- }
2669
- static #parseCimDate(value) {
2670
- if (!value)
2671
- return null;
2672
- const legacy = /\/Date\((\d+)/.exec(value)?.[1];
2673
- const ms = legacy ? Number(legacy) : Date.parse(value);
2674
- return Number.isFinite(ms) ? ms : null;
2675
- }
2676
- static #procListenersOn(port) {
2677
- const inodes = new Set(["tcp", "tcp6"].flatMap((table) => HostProcessProbe.parseProcNetTcp(HostProcessProbe.#readProc("net", table) ?? "", port)));
2678
- if (!inodes.size)
2679
- return [];
2680
- const pids = [];
2681
- for (const entry of HostProcessProbe.#listDir("/proc")) {
2682
- if (!/^\d+$/.test(entry))
2683
- continue;
2684
- const holds = HostProcessProbe.#listDir(`/proc/${entry}/fd`).some((fd) => {
2685
- const link = HostProcessProbe.#orElse(() => readlinkSync(`/proc/${entry}/fd/${fd}`), "");
2686
- const inode = /^socket:\[(\d+)\]$/.exec(link)?.[1];
2687
- return !!inode && inodes.has(inode);
2688
- });
2689
- if (holds)
2690
- pids.push(Number(entry));
2691
- }
2692
- return pids;
2693
- }
2694
- static #readProc(pid, file) {
2695
- return HostProcessProbe.#orElse(() => readFileSync(`/proc/${pid}/${file}`, "utf8"), null);
2696
- }
2697
- static #listDir(dir) {
2698
- return HostProcessProbe.#orElse(() => readdirSync(dir), []);
2699
- }
2700
- static #orElse(read, fallback) {
2701
- try {
2702
- return read();
2703
- } catch {
2704
- return fallback;
2705
- }
2706
- }
2707
- }
2708
-
2709
- // pkgs/@akanjs/cli/application/devPortReclaimer.ts
2710
- class DevPortReclaimer {
2711
- static releaseTimeoutMs = 8000;
2712
- static maxAncestorDepth = 8;
2713
- static #releasePollMs = 100;
2714
- static wsPortOffset = 1e4;
2715
- static portsFor(ports) {
2716
- return [...new Set(ports.flatMap((port) => [port, port + DevPortReclaimer.wsPortOffset]))].sort((left, right) => left - right);
2717
- }
2718
- static isAkanCommand(command) {
2719
- const normalized = command.replaceAll("\\", "/");
2720
- return /(^|\/)akan(\.exe)?"?(\s|$)/.test(normalized) || normalized.includes("@akanjs/cli") || normalized.includes("akanjs/server") || /\bapps\/[^/\s]+\/main\.ts\b/.test(normalized) || normalized.includes("incrementalBuilder.proc") || normalized.includes("rscWorker");
2721
- }
2722
- #probe;
2723
- constructor(probe = new HostProcessProbe) {
2724
- this.#probe = probe;
2725
- }
2726
- async reclaim(ports) {
2727
- const killed = [];
2728
- const foreign = [];
2729
- const seen = new Set;
2730
- for (const port of DevPortReclaimer.portsFor(ports)) {
2731
- for (const holder of await this.holdersOf(port)) {
2732
- if (seen.has(holder.pid))
2733
- continue;
2734
- seen.add(holder.pid);
2735
- if (!holder.akan) {
2736
- foreign.push(holder);
2737
- continue;
2738
- }
2739
- if (await this.#terminate(holder.pid))
2740
- killed.push(holder);
2741
- else
2742
- foreign.push(holder);
2743
- }
2744
- }
2745
- return { killed, foreign };
2746
- }
2747
- async holdersOf(port) {
2748
- const holders = [];
2749
- for (const listenerPid of await this.#probe.listenersOn(port)) {
2750
- if (listenerPid === process.pid || listenerPid === process.ppid)
2751
- continue;
2752
- const command = await this.#probe.commandOf(listenerPid);
2753
- if (!command)
2754
- continue;
2755
- if (!DevPortReclaimer.isAkanCommand(command)) {
2756
- holders.push({ pid: listenerPid, command, port, listenerPid, akan: false });
2757
- continue;
2758
- }
2759
- const root = await this.#akanRootOf(listenerPid, command);
2760
- holders.push({ pid: root.pid, command: root.command, port, listenerPid, akan: true });
2761
- }
2762
- return holders;
2763
- }
2764
- async#akanRootOf(pid, command) {
2765
- let root = { pid, command };
2766
- for (let depth = 0;depth < DevPortReclaimer.maxAncestorDepth; depth += 1) {
2767
- const parentPid = await this.#probe.parentOf(root.pid);
2768
- if (parentPid === null || parentPid <= 1 || parentPid === process.pid || parentPid === process.ppid)
2769
- break;
2770
- const parentCommand = await this.#probe.commandOf(parentPid);
2771
- if (!parentCommand || !DevPortReclaimer.isAkanCommand(parentCommand))
2772
- break;
2773
- root = { pid: parentPid, command: parentCommand };
2774
- }
2775
- return root;
2776
- }
2777
- async#terminate(pid) {
2778
- if (this.#probe.platform === "win32") {
2779
- await HostProcessProbe.run(["taskkill", "/PID", String(pid), "/T", "/F"]);
2780
- return await this.#released(pid);
2781
- }
2782
- if (!this.#signal(pid, "SIGTERM"))
2783
- return !this.#alive(pid);
2784
- if (await this.#released(pid))
2785
- return true;
2786
- this.#signal(pid, "SIGKILL");
2787
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
2788
- return !this.#alive(pid);
2789
- }
2790
- async#released(pid) {
2791
- const deadline = Date.now() + DevPortReclaimer.releaseTimeoutMs;
2792
- while (Date.now() < deadline) {
2793
- if (!this.#alive(pid))
2794
- return true;
2795
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
2796
- }
2797
- return false;
2798
- }
2799
- #signal(pid, signal) {
2800
- try {
2801
- process.kill(pid, signal);
2802
- return true;
2803
- } catch {
2804
- return false;
2805
- }
2806
- }
2807
- #alive(pid) {
2808
- try {
2809
- process.kill(pid, 0);
2810
- return true;
2811
- } catch (error) {
2812
- return error.code === "EPERM";
2813
- }
2814
- }
2815
- }
2816
-
2817
- // pkgs/@akanjs/cli/application/devStreamView.ts
2818
- import { Logger as Logger4 } from "akanjs/common";
2819
- import chalk from "chalk";
2820
- var appColors = ["cyan", "magenta", "yellow", "green", "blue", "red"];
2821
-
2822
- class DevStreamView {
2823
- #logger = new Logger4("akan start");
2824
- #partial = new Map;
2825
- #lastState = new Map;
2826
- #color = new Map;
2827
- #width = 0;
2828
- constructor(appNames) {
2829
- this.#width = appNames.reduce((max, name) => Math.max(max, name.length), 0);
2830
- appNames.forEach((name, idx) => {
2831
- this.#color.set(name, appColors[idx % appColors.length] ?? "cyan");
2832
- });
2833
- }
2834
- onOutput = (app, kind, text) => {
2835
- const key = `${app}:${kind}`;
2836
- const pending = `${this.#partial.get(key) ?? ""}${text}`;
2837
- const lines = pending.split(`
2838
- `);
2839
- this.#partial.set(key, lines.pop() ?? "");
2840
- if (lines.length === 0)
2841
- return;
2842
- const prefixed = lines.map((line) => `${this.#prefix(app)}${line}`).join(`
2843
- `);
2844
- (kind === "stderr" ? process.stderr : process.stdout).write(`${prefixed}
2845
- `);
2846
- };
2847
- onStatus = (statuses) => {
2848
- for (const status of statuses) {
2849
- if (this.#lastState.get(status.name) === status.state)
2850
- continue;
2851
- this.#lastState.set(status.name, status.state);
2852
- const detail = status.detail ? ` (${status.detail})` : "";
2853
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
2854
- const line = `${status.name} ${status.state}${detail}${where}`;
2855
- if (status.state === "failed")
2856
- this.#logger.error(line);
2857
- else if (status.state === "stopped")
2858
- this.#logger.warn(line);
2859
- else
2860
- this.#logger.info(line);
2861
- }
2862
- };
2863
- onNote = (text, level) => {
2864
- if (level === "warn")
2865
- this.#logger.warn(text);
2866
- else
2867
- this.#logger.info(text);
2868
- };
2869
- waitForExit = () => new Promise(() => {
2870
- return;
2871
- });
2872
- close = () => {
2873
- for (const [key, remainder] of this.#partial) {
2874
- if (!remainder)
2875
- continue;
2876
- const app = key.slice(0, key.lastIndexOf(":"));
2877
- process.stdout.write(`${this.#prefix(app)}${remainder}
2878
- `);
2879
- }
2880
- this.#partial.clear();
2881
- };
2882
- #prefix(app) {
2883
- const color = this.#color.get(app) ?? "cyan";
2884
- return `${chalk[color](app.padEnd(this.#width))} ${chalk.dim("\u2502")} `;
2885
- }
2886
- }
2887
-
2888
- // pkgs/@akanjs/cli/application/devBootConcurrency.ts
2889
- import os from "os";
2890
- import { MemoryLimit as MemoryLimit2 } from "akanjs/server/memoryLimit";
2891
-
2892
- class DevBootConcurrency {
2893
- static perAppBytes = 1800 * 1024 * 1024;
2894
- static memoryShare = 0.5;
2895
- static coresPerApp = 4;
2896
- static budget() {
2897
- const hostBytes = os.totalmem();
2898
- const declaredBytes = MemoryLimit2.parseBytesEnv("AKAN_MEMORY_LIMIT") ?? MemoryLimit2.readCgroupBytes();
2899
- return { memoryBytes: Math.min(hostBytes, declaredBytes ?? hostBytes), cores: os.availableParallelism() };
2900
- }
2901
- static resolve(appCount, requested, budget = DevBootConcurrency.budget()) {
2902
- const apps = Math.max(1, Math.trunc(appCount));
2903
- if (requested !== null && Number.isFinite(requested)) {
2904
- const asked = Math.max(1, Math.trunc(requested));
2905
- return { concurrency: Math.min(apps, asked), reason: `--concurrency ${asked}` };
2906
- }
2907
- const byMemory = Math.floor(budget.memoryBytes * DevBootConcurrency.memoryShare / DevBootConcurrency.perAppBytes);
2908
- const byCores = Math.floor(budget.cores / DevBootConcurrency.coresPerApp);
2909
- return {
2910
- concurrency: Math.max(1, Math.min(apps, byMemory, byCores)),
2911
- reason: `${budget.cores} cores, ${DevBootConcurrency.#formatBytes(budget.memoryBytes)} memory`
2912
- };
2913
- }
2914
- static describe(appCount, plan) {
2915
- if (plan.concurrency >= appCount)
2916
- return `booting all ${appCount} apps at once (${plan.reason})`;
2917
- return `booting ${plan.concurrency} of ${appCount} apps at a time (${plan.reason}) \u2014 --concurrency raises it`;
2918
- }
2919
- static #formatBytes(bytes) {
2920
- const gigabytes = bytes / 1024 ** 3;
2921
- return gigabytes >= 10 ? `${Math.round(gigabytes)}GB` : `${gigabytes.toFixed(1)}GB`;
2922
- }
2923
- }
2924
-
2925
- // pkgs/@akanjs/cli/application/devSessionLog.ts
2926
- import { mkdir, rename } from "fs/promises";
2927
- import path6 from "path";
2928
- import dayjs from "dayjs";
2929
-
2930
- class DevSessionLog {
2931
- static fileName = "dev.log";
2932
- static previousFileName = "dev.prev.log";
2933
- static flushMs = 200;
2934
- static bufferBytes = 64 * 1024;
2935
- #workspaceRoot;
2936
- #appNames;
2937
- #now;
2938
- #writers = new Map;
2939
- #partial = new Map;
2940
- #lastState = new Map;
2941
- #flushTimer = null;
2942
- constructor({ workspaceRoot, apps, now = () => new Date }) {
2943
- this.#workspaceRoot = workspaceRoot;
2944
- this.#appNames = [...apps];
2945
- this.#now = now;
2946
- }
2947
- get appNames() {
2948
- return [...this.#appNames];
2949
- }
2950
- pathOf(app) {
2951
- return path6.join(this.#runtimeDirOf(app), DevSessionLog.fileName);
2952
- }
2953
- previousPathOf(app) {
2954
- return path6.join(this.#runtimeDirOf(app), DevSessionLog.previousFileName);
2955
- }
2956
- relativePathOf(app) {
2957
- return path6.relative(this.#workspaceRoot, this.pathOf(app));
2958
- }
2959
- async open() {
2960
- const stamp = dayjs(this.#now()).format("YYYY-MM-DD HH:mm:ss");
2961
- for (const app of this.#appNames) {
2962
- const file = this.pathOf(app);
2963
- await mkdir(path6.dirname(file), { recursive: true });
2964
- await rename(file, this.previousPathOf(app)).catch(() => {
2965
- return;
2966
- });
2967
- this.#writers.set(app, Bun.file(file).writer({ highWaterMark: DevSessionLog.bufferBytes }));
2968
- this.#writeLine(app, `\u2500\u2500 akan start \xB7 ${app} \xB7 ${stamp} \u2500\u2500`);
2969
- }
2970
- }
2971
- write(app, kind, chunk) {
2972
- const key = `${app}:${kind}`;
2973
- const parts = `${this.#partial.get(key) ?? ""}${chunk}`.split(`
2974
- `);
2975
- this.#partial.set(key, parts.pop() ?? "");
2976
- for (const line of parts)
2977
- this.#writeLine(app, stripAnsi(line));
2978
- }
2979
- note(text) {
2980
- for (const app of this.#appNames)
2981
- this.#writeLine(app, `[akan] ${text}`);
2982
- }
2983
- status(statuses) {
2984
- for (const status of statuses) {
2985
- if (this.#lastState.get(status.name) === status.state)
2986
- continue;
2987
- this.#lastState.set(status.name, status.state);
2988
- const detail = status.detail ? ` (${status.detail})` : "";
2989
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
2990
- this.#writeLine(status.name, `[akan] ${status.name} ${status.state}${detail}${where}`);
2991
- }
2992
- }
2993
- async close() {
2994
- for (const [key, remainder] of this.#partial) {
2995
- if (!remainder)
2996
- continue;
2997
- this.#writeLine(key.slice(0, key.lastIndexOf(":")), stripAnsi(remainder));
2998
- }
2999
- this.#partial.clear();
3000
- if (this.#flushTimer)
3001
- clearTimeout(this.#flushTimer);
3002
- this.#flushTimer = null;
3003
- await Promise.all([...this.#writers.values()].map(async (writer) => await writer.end()));
3004
- this.#writers.clear();
3005
- }
3006
- #runtimeDirOf(app) {
3007
- return path6.join(this.#workspaceRoot, "local", "apps", app, "runtime");
3008
- }
3009
- #writeLine(app, text) {
3010
- const writer = this.#writers.get(app);
3011
- if (!writer)
3012
- return;
3013
- writer.write(`${text}
3014
- `);
3015
- this.#scheduleFlush();
3016
- }
3017
- #scheduleFlush() {
3018
- if (this.#flushTimer)
3019
- return;
3020
- this.#flushTimer = setTimeout(() => {
3021
- this.#flushTimer = null;
3022
- for (const writer of this.#writers.values())
3023
- writer.flush();
3024
- }, DevSessionLog.flushMs);
3025
- }
3026
- }
3027
-
3028
- // pkgs/@akanjs/cli/application/devSupervisor.ts
3029
- class DevSupervisor {
3030
- static resolveDevUi(plain, {
3031
- isTty = !!process.stdout.isTTY,
3032
- columns = process.stdout.columns ?? 0
3033
- } = {}) {
3034
- if (plain)
3035
- return { mode: "stream", downgraded: false };
3036
- if (!isTty || columns <= 0)
3037
- return { mode: "stream", downgraded: true };
3038
- return { mode: "tui", downgraded: false };
3039
- }
3040
- static supervisedEnvKey = "AKAN_DEV_SUPERVISED";
3041
- static childHooks() {
3042
- if (process.env[DevSupervisor.supervisedEnvKey] !== "1" || !process.send)
3043
- return {};
3044
- const send = process.send.bind(process);
3045
- return {
3046
- stdio: "pipe",
3047
- onDevEvent: (event) => {
3048
- try {
3049
- send(event);
3050
- } catch {}
3051
- }
3052
- };
3053
- }
3054
- static bootTimeoutMs = 180000;
3055
- static shutdownGraceMs = 12000;
3056
- #options;
3057
- #children = new Map;
3058
- #sessionLog;
3059
- #view = null;
3060
- #stopping = false;
3061
- constructor(options) {
3062
- this.#options = options;
3063
- this.#sessionLog = new DevSessionLog({
3064
- workspaceRoot: options.apps[0]?.workspace.workspaceRoot ?? process.cwd(),
3065
- apps: options.apps.map((app) => app.name)
3066
- });
3067
- }
3068
- get statuses() {
3069
- return [...this.#children.values()].map((child) => child.status);
3070
- }
3071
- get sessionLog() {
3072
- return this.#sessionLog;
3073
- }
3074
- async run(view) {
3075
- this.#view = view;
3076
- await this.#sessionLog.open();
3077
- const ports = await this.#assignPorts();
3078
- for (const app of this.#options.apps)
3079
- this.#children.set(app.name, this.#makeChild(app, ports.get(app.name) ?? 0));
3080
- this.#publishStatus();
3081
- const logPaths = this.#sessionLog.appNames.map((name) => this.#sessionLog.relativePathOf(name));
3082
- this.#note(`session log: ${logPaths.join(" \xB7 ")}`, "info");
3083
- const stopped = this.#installSignalHandlers();
3084
- this.#bootInOrder();
3085
- await Promise.race([view.waitForExit(), stopped]);
3086
- await this.stop();
3087
- view.close?.();
3088
- await this.#sessionLog.close();
3089
- }
3090
- async#assignPorts() {
3091
- const taken = new Set;
3092
- const ports = new Map;
3093
- for (const app of this.#options.apps) {
3094
- let port = await app.getDevPort();
3095
- while (taken.has(port))
3096
- port += 1;
3097
- taken.add(port);
3098
- ports.set(app.name, port);
3099
- }
3100
- return ports;
3101
- }
3102
- #makeChild(app, port) {
3103
- const { promise: booted, resolve: markBooted } = Promise.withResolvers();
3104
- return {
3105
- status: {
3106
- app,
3107
- name: app.name,
3108
- port,
3109
- url: `http://localhost:${port}`,
3110
- shareUrl: this.#options.shares?.get(app.name) ?? null,
3111
- state: "starting",
3112
- detail: "queued",
3113
- exitCode: null
3114
- },
3115
- proc: null,
3116
- booted,
3117
- markBooted,
3118
- opened: false
3119
- };
3120
- }
3121
- async#bootInOrder() {
3122
- const queue = [...this.#children.values()];
3123
- const plan = DevBootConcurrency.resolve(queue.length, this.#options.concurrency ?? null);
3124
- const concurrency = plan.concurrency;
3125
- if (queue.length > 1)
3126
- this.#note(DevBootConcurrency.describe(queue.length, plan), "info");
3127
- const waves = [];
3128
- for (let idx = 0;idx < queue.length; idx += concurrency)
3129
- waves.push(queue.slice(idx, idx + concurrency));
3130
- for (const wave of waves) {
3131
- if (this.#stopping)
3132
- return;
3133
- for (const child of wave)
3134
- this.#spawnChild(child);
3135
- this.#publishStatus();
3136
- await Promise.all(wave.map(async (child) => await this.#waitForBoot(child)));
3137
- }
3138
- }
3139
- async#waitForBoot(child) {
3140
- if (await DevSupervisor.timesOut(child.booted, DevSupervisor.bootTimeoutMs))
3141
- this.#note(`${child.status.name} has not finished booting after ${Math.round(DevSupervisor.bootTimeoutMs / 1000)}s; starting the next app anyway`, "warn");
3142
- }
3143
- static async timesOut(work, ms) {
3144
- let timer;
3145
- const expired = new Promise((resolve) => {
3146
- timer = setTimeout(() => resolve(true), ms);
3147
- });
3148
- try {
3149
- return await Promise.race([work.then(() => false), expired]);
3150
- } finally {
3151
- clearTimeout(timer);
3152
- }
3153
- }
3154
- static childArgs(name, { write = true } = {}) {
3155
- return [
3156
- "start",
3157
- name,
3158
- "--plain",
3159
- "--dbup",
3160
- "false",
3161
- "--write",
3162
- String(write)
3163
- ];
3164
- }
3165
- #spawnChild(child) {
3166
- const { app, name, port } = child.status;
3167
- const args = DevSupervisor.childArgs(name, { write: this.#options.write ?? true });
3168
- const proc = Bun.spawn([process.execPath, Bun.main, ...args], {
3169
- cwd: app.workspace.workspaceRoot,
3170
- env: {
3171
- ...process.env,
3172
- [DevSupervisor.supervisedEnvKey]: "1",
3173
- AKAN_PUBLIC_APP_NAME: name,
3174
- AKAN_DEV_PORT: String(port)
3175
- },
3176
- stdio: ["ignore", "pipe", "pipe"],
3177
- ipc: (message) => {
3178
- if (!message || typeof message !== "object")
3179
- return;
3180
- if ("booted" in message)
3181
- child.markBooted();
3182
- else if (typeof message.state === "string")
3183
- this.#applyChildEvent(child, message);
3184
- },
3185
- serialization: "advanced",
3186
- onExit: (_proc, exitCode, signalCode) => {
3187
- child.proc = null;
3188
- child.status.exitCode = exitCode;
3189
- if (this.#stopping)
3190
- return;
3191
- child.status.state = "stopped";
3192
- child.status.detail = signalCode ? `killed by ${signalCode}` : `exited with ${exitCode}`;
3193
- child.markBooted();
3194
- this.#publishStatus();
3195
- }
3196
- });
3197
- child.proc = proc;
3198
- child.status.state = "starting";
3199
- child.status.detail = `pid ${proc.pid}`;
3200
- this.#drain(proc.stdout, name, "stdout");
3201
- this.#drain(proc.stderr, name, "stderr");
3202
- }
3203
- #applyChildEvent(child, event) {
3204
- child.status.state = event.state;
3205
- child.status.detail = event.detail ?? "";
3206
- if (event.state === "ready") {
3207
- if (this.#options.open && !child.opened) {
3208
- child.opened = true;
3209
- openBrowser(child.status.url);
3210
- }
3211
- }
3212
- if (event.state === "failed")
3213
- child.markBooted();
3214
- this.#publishStatus();
3215
- }
3216
- async#drain(stream, name, kind) {
3217
- const decoder = new TextDecoder;
3218
- try {
3219
- for await (const chunk of stream) {
3220
- const text = decoder.decode(chunk, { stream: true });
3221
- if (!text)
3222
- continue;
3223
- this.#view?.onOutput(name, kind, text);
3224
- this.#sessionLog.write(name, kind, text);
3225
- }
3226
- } catch {}
3227
- }
3228
- #publishStatus() {
3229
- this.#view?.onStatus(this.statuses);
3230
- this.#sessionLog.status(this.statuses);
3231
- }
3232
- #note(text, level) {
3233
- this.#view?.onNote(text, level);
3234
- this.#sessionLog.note(text);
3235
- }
3236
- #installSignalHandlers() {
3237
- return new Promise((resolve) => {
3238
- let asked = false;
3239
- const onSignal = () => {
3240
- if (asked) {
3241
- this.#note("abandoning the wait; children may be left running", "warn");
3242
- process.exit(130);
3243
- }
3244
- asked = true;
3245
- resolve();
3246
- };
3247
- process.on("SIGINT", onSignal);
3248
- process.on("SIGTERM", onSignal);
3249
- });
3250
- }
3251
- async restart(name) {
3252
- const child = this.#children.get(name);
3253
- if (!child || this.#stopping)
3254
- return;
3255
- const running = child.proc;
3256
- if (running) {
3257
- running.kill("SIGTERM");
3258
- await running.exited;
3259
- }
3260
- child.status.state = "starting";
3261
- child.status.detail = "restarting";
3262
- child.status.exitCode = null;
3263
- this.#publishStatus();
3264
- this.#spawnChild(child);
3265
- this.#publishStatus();
3266
- }
3267
- async stop() {
3268
- if (this.#stopping)
3269
- return;
3270
- this.#stopping = true;
3271
- const running = [...this.#children.values()].filter((child) => Boolean(child.proc));
3272
- for (const child of running)
3273
- child.proc.kill("SIGTERM");
3274
- const exited = Promise.all(running.map(async (child) => await child.proc.exited));
3275
- if (!await DevSupervisor.timesOut(exited, DevSupervisor.shutdownGraceMs))
3276
- return;
3277
- for (const child of running) {
3278
- if (child.proc.killed)
3279
- continue;
3280
- this.#note(`${child.status.name} did not exit in time; killing it`, "warn");
3281
- child.proc.kill("SIGKILL");
3282
- }
3283
- }
3284
- }
3285
-
3286
- // pkgs/@akanjs/cli/application/interruptTeardown.ts
3287
- import { Logger as Logger5 } from "akanjs/common";
3288
-
3289
- class InterruptTeardown {
3290
- #teardowns = [];
3291
- #exit;
3292
- #listen;
3293
- #report;
3294
- #interrupted = false;
3295
- #chain = Promise.resolve();
3296
- ownsExit = true;
3297
- constructor({ exit, listen, report } = {}) {
3298
- this.#exit = exit ?? ((code) => process.exit(code));
3299
- this.#listen = listen ?? ((onSignal) => {
3300
- process.on("SIGINT", onSignal);
3301
- });
3302
- this.#report = report ?? ((message) => Logger5.rawLog(message, undefined, "error"));
3303
- }
3304
- add(run, abandoned, exitCode = 0) {
3305
- this.#teardowns.push({ run, abandoned, exitCode, state: "pending" });
3306
- if (this.#teardowns.length === 1)
3307
- this.#listen(() => this.#onSignal());
3308
- }
3309
- async runAll() {
3310
- await this.#runTeardowns();
3311
- }
3312
- #onSignal() {
3313
- if (this.#interrupted) {
3314
- for (const one of this.#teardowns)
3315
- if (one.state !== "done")
3316
- this.#report(one.abandoned);
3317
- this.#exit(130);
3318
- return;
3319
- }
3320
- this.#interrupted = true;
3321
- this.#runTeardowns().finally(() => {
3322
- if (this.ownsExit)
3323
- this.#exit(Math.max(0, ...this.#teardowns.map((one) => one.exitCode)));
3324
- });
3325
- }
3326
- async#runTeardowns() {
3327
- this.#chain = this.#chain.then(async () => {
3328
- for (const one of this.#teardowns.toReversed()) {
3329
- if (one.state !== "pending")
3330
- continue;
3331
- one.state = "running";
3332
- await one.run().catch(() => {
3333
- return;
3334
- });
3335
- one.state = "done";
3336
- }
3337
- });
3338
- await this.#chain;
3339
- }
3340
- }
3341
-
3342
- // pkgs/@akanjs/cli/application/application.script.ts
3343
- class ApplicationScript extends script("application", [ApplicationRunner, LibraryScript]) {
3344
- static dbShutdownTimeoutMs = 20000;
3345
- static devServerReadyTimeoutMs = DevSupervisor.bootTimeoutMs;
3346
- #interrupt = new InterruptTeardown;
3347
- async confirmDatabaseModeDependencyInstall(databaseMode, installSpecs) {
3348
- assertPromptable(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}`, {
3349
- remedy: `install them first with \`bun add ${installSpecs.join(" ")}\``
3350
- });
3351
- return await confirm({
3352
- message: `Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}. Install them now?`,
3353
- default: true
3354
- });
3355
- }
3356
- async syncDatabaseModeDependencies(app, akanConfig, databaseMode) {
3357
- const installSpecs = akanConfig.getMissingDatabaseModeDependencySpecs(databaseMode);
3358
- if (installSpecs.length === 0)
3359
- return;
3360
- const shouldInstall = await this.confirmDatabaseModeDependencyInstall(databaseMode, installSpecs);
3361
- if (!shouldInstall)
3362
- throw new Error(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}.`);
3363
- await this.#addDependencies(app, installSpecs, `database dependencies for ${databaseMode} mode`);
3364
- }
3365
- async#addDependencies(app, installSpecs, what) {
3366
- const spinner = app.workspace.spinning(`Installing ${what}...`);
3367
- try {
3368
- await app.workspace.spawn("bun", ["add", ...installSpecs], { stdio: "inherit" });
3369
- await app.workspace.getPackageJson({ refresh: true });
3370
- spinner.succeed(`Installed ${what}`);
3371
- } catch (error) {
3372
- spinner.fail(`Failed to install ${what}`);
3373
- throw error;
3374
- }
3375
- }
3376
- async createApplication(appName, workspace, { start = false, libs = [], sample = false } = {}) {
3377
- const spinner = workspace.spinning("Creating application...");
3378
- const app = await this.applicationRunner.createApplication(appName, workspace, libs, { sample });
3379
- spinner.succeed(`Application created in apps/${app.name}`);
3380
- await app.scanSync();
3381
- if (start)
3382
- await this.startOne(app, { open: true });
3383
- }
3384
- async removeApplication(app) {
3385
- const spinner = app.spinning("Removing application...");
3386
- await this.applicationRunner.removeApplication(app);
3387
- spinner.succeed(`Application ${app.name} (apps/${app.name}) removed`);
3388
- }
3389
- async planSlice(app, format = "text") {
3390
- const spinner = app.spinning("Planning distributable slice...");
3391
- const plan = await this.applicationRunner.planSlice(app);
3392
- spinner.succeed(`Slice planned (${plan.libs.length} libs, ${plan.warnings.length} warnings)`);
3393
- Logger6.rawLog(format === "json" ? JSON.stringify(plan, null, 2) : formatSlicePlan(plan));
3394
- }
3395
- async sync(sys) {
3396
- if (sys.type === "app")
3397
- await sys.scanSync();
3398
- else
3399
- await this.libraryScript.syncLibrary(sys);
3400
- }
3401
- async script(app, filename) {
3402
- const scriptFilename = filename ?? await this.applicationRunner.getScriptFilename(app);
3403
- await app.scanSync();
3404
- await this.applicationRunner.runScript(app, scriptFilename);
3405
- }
3406
- async console(app) {
3407
- await app.scanSync();
3408
- await this.applicationRunner.runConsole(app);
3409
- }
3410
- async migrate(app, argv) {
3411
- await app.scanSync();
3412
- await this.applicationRunner.migrate(app, argv);
3413
- }
3414
- async createMigration(app, migrationName) {
3415
- const migrationId = await this.applicationRunner.createMigration(app, migrationName);
3416
- Logger6.rawLog(`Created apps/${app.name}/script/migration/${migrationId}.ts; plan it with \`akan migrate ${app.name} plan ${migrationId}\``);
3417
- }
3418
- async logs(app, options) {
3419
- await this.applicationRunner.runLogs(app, options);
3420
- }
3421
- async build(app, {
3422
- write = true,
3423
- fast = false,
3424
- quiet = false,
3425
- profile
3426
- } = {}) {
3427
- await app.scanSync({ write });
3428
- if (!quiet)
3429
- Logger6.rawLog(`Creating an optimized production build for ${app.name}...`);
3430
- try {
3431
- const result = await this.applicationRunner.build(app, { fast, spinner: !quiet, envProfile: profile });
3432
- Logger6.rawLog(`${app.name} built in dist/apps/${app.name}`);
3433
- if (!quiet)
3434
- ApplicationBuildReporter.printSummary(result);
3435
- } catch (error) {
3436
- Logger6.rawLog(`${app.name} build failed in dist/apps/${app.name}`, undefined, "error");
3437
- Logger6.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
3438
- markCliErrorPrinted(error);
3439
- throw error;
3440
- }
3441
- }
3442
- async typecheck(exec, { write = true, clean = false, incremental = true, tests = false } = {}) {
3443
- if (!(exec instanceof AppExecutor) && !(exec instanceof LibExecutor))
3444
- throw new Error(`akan typecheck takes an app or a library; ${exec.name} is a package, checked by its own tsconfig.`);
3445
- if (exec instanceof AppExecutor)
3446
- await exec.scanSync({ write });
3447
- else if (write)
3448
- await this.libraryScript.syncLibrary(exec);
3449
- else
3450
- await exec.scan({ write: false });
3451
- const spinner = exec.spinning(`Typechecking ${exec.name}${tests ? " with its tests" : ""}...`);
3452
- try {
3453
- if (exec instanceof LibExecutor)
3454
- await this.applicationRunner.typecheckLibrary(exec, { clean, incremental, tests });
3455
- else
3456
- await this.applicationRunner.typecheck(exec, { clean, incremental, tests });
3457
- spinner.succeed(`${exec.name} typechecked`);
3458
- } catch (error) {
3459
- spinner.fail(`${exec.name} typecheck failed`);
3460
- Logger6.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
3461
- markCliErrorPrinted(error);
3462
- throw error;
3463
- }
3464
- }
3465
- async test(exec, { write = true, files = [] } = {}) {
3466
- const testPaths = this.applicationRunner.resolveTestPaths(exec, files);
3467
- if (exec instanceof LibExecutor) {
3468
- if (write)
3469
- await this.libraryScript.syncLibrary(exec);
3470
- else
3471
- await exec.scan({ write: false });
3472
- exec.spinning(`Preparing ${exec.name}...`).succeed(`${exec.name} prepared`);
3473
- await this.applicationRunner.test(exec, testPaths);
3474
- return;
3475
- }
3476
- const spinner = exec.spinning(`Preparing ${exec.name}...`);
3477
- try {
3478
- if (exec instanceof PkgExecutor)
3479
- await exec.scan({ refresh: true });
3480
- else
3481
- await exec.scanSync({ write });
3482
- spinner.succeed(`${exec.name} prepared`);
3483
- } catch (error) {
3484
- spinner.fail(`${exec.name} prepare failed`);
3485
- throw error;
3486
- }
3487
- await this.applicationRunner.test(exec, testPaths);
3488
- }
3489
- async start(apps, {
3490
- open = false,
3491
- dbup = true,
3492
- write = true,
3493
- plain = false,
3494
- kill = false,
3495
- share = false,
3496
- concurrency = null
3497
- } = {}) {
3498
- const first = apps[0];
3499
- if (!first)
3500
- throw new Error("No app selected to start");
3501
- const { mode, downgraded } = DevSupervisor.resolveDevUi(plain);
3502
- if (downgraded)
3503
- first.workspace.log("no sized terminal to draw on; printing prefixed lines instead");
3504
- if (kill)
3505
- await this.reclaimDevPorts(apps);
3506
- const shares = share ? await this.#shareOnInterrupt(apps) : null;
3507
- if (mode === "stream" && apps.length === 1)
3508
- return await this.startOne(first, { open, dbup, write, ...DevSupervisor.childHooks() });
3509
- this.#interrupt.ownsExit = false;
3510
- await this.#startMany(apps, { open, dbup, write, mode, concurrency, shares });
3511
- }
3512
- async startOne(app, { open = false, dbup = true, stdio = "inherit", write = true, onDevEvent } = {}) {
3513
- await app.scanSync({ write });
3514
- const akanConfig = await app.getConfig();
3515
- const databaseMode = akanConfig.resolveDatabaseMode();
3516
- await this.syncDatabaseModeDependencies(app, akanConfig, databaseMode);
3517
- if (app.getEnv() === "local" && dbup && databaseMode !== "single") {
3518
- const wasDbAlreadyUp = await this.dbup(app.workspace, databaseMode);
3519
- if (!wasDbAlreadyUp)
3520
- this.#stopDatabaseOnInterrupt(app.workspace);
3521
- }
3522
- const spinner = app.spinning("Preparing backend...");
3523
- return await this.applicationRunner.start(app, {
3524
- open,
3525
- onStart: () => spinner.succeed(`${app.name} prepared, ready to start`),
3526
- onDevEvent,
3527
- stdio
3528
- });
3529
- }
3530
- async reclaimDevPorts(apps) {
3531
- const workspace = apps[0]?.workspace;
3532
- if (!workspace)
3533
- return;
3534
- const ports = await Promise.all(apps.map(async (app) => await app.getDevPort()));
3535
- const { killed, foreign } = await new DevPortReclaimer().reclaim(ports);
3536
- for (const holder of killed)
3537
- workspace.log(`freed port ${holder.port} \u2014 killed pid ${holder.pid} (${holder.command})`);
3538
- for (const holder of foreign)
3539
- Logger6.rawLog(`port ${holder.port} is held by pid ${holder.pid} and was left alone: ${holder.command}`, undefined, "error");
3540
- if (killed.length === 0 && foreign.length === 0)
3541
- workspace.log("dev ports are free; nothing to kill");
3542
- }
3543
- async#startMany(apps, {
3544
- open,
3545
- dbup,
3546
- write,
3547
- mode,
3548
- concurrency,
3549
- shares
3550
- }) {
3551
- const workspace = apps[0]?.workspace;
3552
- if (!workspace)
3553
- throw new Error("No app selected to start");
3554
- const startedDatabase = dbup ? await this.#prepareSharedDatabase(apps) : false;
3555
- const supervisor = new DevSupervisor({ apps, mode, concurrency, open, write, shares });
3556
- const view = mode === "tui" ? new (await import("./devTui-q7k7bakd.js")).DevTui(supervisor) : new DevStreamView(apps.map((app) => app.name));
3557
- await supervisor.run(view);
3558
- if (startedDatabase)
3559
- await this.#stopDatabase(workspace);
3560
- }
3561
- async#prepareSharedDatabase(apps) {
3562
- const workspace = apps[0]?.workspace;
3563
- if (!workspace)
3564
- return false;
3565
- const modes = new Set;
3566
- for (const app of apps) {
3567
- if (app.getEnv() !== "local")
3568
- continue;
3569
- const akanConfig = await app.getConfig();
3570
- const mode = akanConfig.resolveDatabaseMode();
3571
- await this.syncDatabaseModeDependencies(app, akanConfig, mode);
3572
- if (mode !== "single")
3573
- modes.add(mode);
3574
- }
3575
- let started = false;
3576
- for (const mode of modes)
3577
- if (!await this.dbup(workspace, mode))
3578
- started = true;
3579
- return started;
3580
- }
3581
- async buildIos(app, { write = true, ...options } = {}) {
3582
- await app.scanSync({ write });
3583
- await this.applicationRunner.buildMobile(app, "ios", options);
3584
- }
3585
- async buildAndroid(app, { write = true, ...options } = {}) {
3586
- await app.scanSync({ write });
3587
- await this.applicationRunner.buildMobile(app, "android", options);
3588
- }
3589
- async buildDesktop(app, { write = true, ...options } = {}) {
3590
- await app.scanSync({ write });
3591
- await this.applicationRunner.buildDesktop(app, options);
3592
- }
3593
- async startIos(app, { write = true, ...options } = {}) {
3594
- await app.scanSync({ write });
3595
- await this.applicationRunner.startMobile(app, "ios", options);
3596
- }
3597
- async startAndroid(app, { write = true, ...options } = {}) {
3598
- await app.scanSync({ write });
3599
- await this.applicationRunner.startMobile(app, "android", options);
3600
- }
3601
- async startDesktop(app, { write = true, ...options } = {}) {
3602
- await app.scanSync({ write });
3603
- if (options.operation === "release")
3604
- return await this.applicationRunner.startDesktop(app, options);
3605
- const mobileTarget = await ApplicationRunner.startTarget(app, undefined, options.target);
3606
- if (!ApplicationRunner.carriesServer(mobileTarget))
3607
- return await this.applicationRunner.startDesktop(app, options);
3608
- DesktopServerStage.assertCarriable(await app.getConfig());
3609
- const upstream = `http://localhost:${await app.getDevPort()}`;
3610
- try {
3611
- if (await ApplicationRunner.answers(upstream, app.name, app.workspace.workspaceRoot))
3612
- app.log(`The desktop app follows the dev server on ${upstream}.`);
3613
- else
3614
- await this.#startDevServerFor(app, upstream);
3615
- await this.applicationRunner.startDesktop(app, { ...options, interrupt: this.#interrupt });
3616
- } finally {
3617
- await this.#interrupt.runAll();
3618
- }
3619
- }
3620
- async#startDevServerFor(app, upstream) {
3621
- app.log(`No dev server answers on ${upstream}; starting \`akan start ${app.name}\` for the desktop app.`);
3622
- let settle = () => {};
3623
- const settled = new Promise((resolve) => settle = resolve);
3624
- const appHost = await this.startOne(app, {
3625
- write: false,
3626
- onDevEvent: (event) => {
3627
- if ("state" in event && (event.state === "ready" || event.state === "failed"))
3628
- settle(event.state);
3629
- }
3630
- });
3631
- this.#interrupt.add(async () => {
3632
- await appHost.stop();
3633
- }, "Abandoning the dev server shutdown; its processes may still be running.", 130);
3634
- let state;
3635
- const timedOut = await DevSupervisor.timesOut(settled.then((settledState) => state = settledState), ApplicationScript.devServerReadyTimeoutMs);
3636
- if (state === "ready")
3637
- return;
3638
- await this.#interrupt.runAll();
3639
- throw new Error(timedOut ? `akan start ${app.name} did not answer within ${ApplicationScript.devServerReadyTimeoutMs / 1000}s; see its log above.` : `akan start ${app.name} gave up restarting its server; see its log above.`);
3640
- }
3641
- async releaseIos(app, {
3642
- write = true,
3643
- allowLocalRelease = false,
3644
- ...options
3645
- } = {}) {
3646
- await app.scanSync({ write });
3647
- ApplicationScript.#assertReleaseEnv("releaseIos", options.env ?? "main", allowLocalRelease);
3648
- await this.applicationRunner.releaseIos(app, options);
3649
- }
3650
- async releaseAndroid(app, format, {
3651
- write = true,
3652
- allowLocalRelease = false,
3653
- ...options
3654
- } = {}) {
3655
- await app.scanSync({ write });
3656
- ApplicationScript.#assertReleaseEnv("releaseAndroid", options.env ?? "main", allowLocalRelease);
3657
- await this.applicationRunner.releaseAndroid(app, format, options);
3658
- }
3659
- async packUpdate(app, platform, {
3660
- write = true,
3661
- allowLocalRelease = false,
3662
- ...options
3663
- } = {}) {
3664
- await app.scanSync({ write });
3665
- ApplicationScript.#assertReleaseEnv("packUpdate", options.env ?? "main", allowLocalRelease);
3666
- return await this.applicationRunner.packUpdate(app, platform, options);
3667
- }
3668
- async updateKeygen(app, platform, { target } = {}) {
3669
- await this.applicationRunner.updateKeygen(app, platform, target);
3670
- }
3671
- async publishUpdate(app, platform, {
3672
- write = true,
3673
- allowLocalRelease = false,
3674
- ...options
3675
- } = {}) {
3676
- await app.scanSync({ write });
3677
- ApplicationScript.#assertReleaseEnv("publishUpdate", options.env ?? "main", allowLocalRelease);
3678
- await this.applicationRunner.publishUpdate(app, platform, options);
3679
- }
3680
- static #assertReleaseEnv(command, env, allowLocalRelease) {
3681
- if (env === "local" && !allowLocalRelease)
3682
- throw new Error(`${command} --env local is blocked. Pass allowLocalRelease only for explicit local release testing.`);
3683
- }
3684
- async transferDatabase(app, direction, dir) {
3685
- await this.applicationRunner.transferDatabase(app, direction, dir);
3686
- }
3687
- async dbupDeclared(workspace, mode) {
3688
- const declared = mode ? [mode] : await Promise.all((await workspace.getApps()).map(async (appName) => (await AppExecutor.from(workspace, appName).getConfig()).database.modes)).then((modes) => [...new Set(modes.flat())]);
3689
- const needing = declared.filter((each) => each !== "single");
3690
- if (!needing.length) {
3691
- workspace.log("No app here declares a database mode that runs on local services; single needs none.");
3692
- return;
3693
- }
3694
- for (const each of needing)
3695
- await this.dbup(workspace, each);
3696
- }
3697
- async dbup(workspace, mode = "multiple") {
3698
- const spinner = workspace.spinning(`Starting local database (${mode})...`);
3699
- const wasAlreadyUp = await this.applicationRunner.dbup(workspace, mode);
3700
- spinner.succeed(wasAlreadyUp ? `Local database (${mode}) was already up` : `Local database (${mode}) is up`);
3701
- return wasAlreadyUp;
3702
- }
3703
- async dbdown(workspace) {
3704
- const spinner = workspace.spinning("Stopping local database...");
3705
- try {
3706
- await this.applicationRunner.dbdown(workspace);
3707
- } catch (error) {
3708
- spinner.fail("Local database failed to stop");
3709
- throw error;
3710
- }
3711
- spinner.succeed("Local database (/local/docker-compose.yaml) is down");
3712
- }
3713
- async#shareOnInterrupt(apps) {
3714
- const shares = [];
3715
- const urls = new Map;
3716
- this.#interrupt.add(async () => {
3717
- await Promise.all(shares.map(async (share) => await share.close()));
3718
- }, "Abandoning the tunnel release; the shares expire on their own.");
3719
- await Promise.all(apps.map(async (app) => {
3720
- const { TunnelShare } = await import("./TunnelShare-dk2gw78d.js");
3721
- const share = await TunnelShare.open(app, { workspace: app.workspace });
3722
- shares.push(share);
3723
- urls.set(app.name, share.url);
3724
- Logger6.rawLog(`${app.name} is shared at ${share.url}`);
3725
- })).catch((error) => {
3726
- Logger6.rawLog(`Could not open the tunnel: ${toError2(error).message}`, undefined, "error");
3727
- });
3728
- return urls;
3729
- }
3730
- #stopDatabaseOnInterrupt(workspace) {
3731
- this.#interrupt.add(async () => {
3732
- await this.#stopDatabase(workspace);
3733
- }, "Abandoning the local database teardown; containers are left running.");
3734
- }
3735
- async#stopDatabase(workspace) {
3736
- const stopped = this.dbdown(workspace).catch(() => {
3737
- return;
3738
- });
3739
- if (!await DevSupervisor.timesOut(stopped, ApplicationScript.dbShutdownTimeoutMs))
3740
- return;
3741
- Logger6.rawLog(`Local database did not stop within ${ApplicationScript.dbShutdownTimeoutMs}ms; run \`akan dbdown\` once Docker responds.`, undefined, "error");
3742
- }
3743
- }
3744
-
3745
- export { ApplicationScript };
2523
+ export { ApplicationRunner };