@akanjs/cli 3.1.1-rc.9 → 3.1.1
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/.build-stamp +1 -1
- package/CodeAgent-35wnb7w5.js +9 -0
- package/{CodeTui-z5vkm9ea.js → CodeTui-h6yz2kvq.js} +1 -1
- package/TunnelShare-xyjpa7gx.js +14 -0
- package/agent.command-3r4jsck8.js +46 -0
- package/akanCode.js +10 -6
- package/{application.command-wthg8nn9.js → application.command-g7xv6ad0.js} +44 -11
- package/{applicationBuildRunner-t2r84sz6.js → applicationBuildRunner-qvjnhr9j.js} +9 -6
- package/buildBatch.proc.js +6 -6
- package/{cloud.command-sz11hpre.js → cloud.command-6ebygmhw.js} +17 -15
- package/cloud.script-0s1jybd5.js +26 -0
- package/{code.command-9h3yrzhe.js → code.command-mpkm2emr.js} +6 -6
- package/commandManifest.json +1 -1
- package/{context.command-15j9b7c0.js → context.command-svdh6b2w.js} +18 -17
- package/context.runner-ch0z3a8g.js +26 -0
- package/{devTui-q7k7bakd.js → devTui-evr3b35y.js} +1 -1
- package/{guideline.command-snh85ctf.js → guideline.command-qwp3tnjx.js} +3 -3
- package/guidelines/conventions/core.md +106 -0
- package/guidelines/conventions/rules/app.md +83 -0
- package/guidelines/conventions/rules/auth.md +45 -0
- package/guidelines/conventions/rules/config.md +56 -0
- package/guidelines/conventions/rules/constant.md +24 -0
- package/guidelines/conventions/rules/gates.md +31 -0
- package/guidelines/conventions/rules/layer.md +25 -0
- package/guidelines/conventions/rules/migration.md +27 -0
- package/guidelines/conventions/rules/module.md +90 -0
- package/guidelines/conventions/rules/page.md +56 -0
- package/guidelines/conventions/rules/sensitive.md +16 -0
- package/guidelines/conventions/rules/server.md +86 -0
- package/guidelines/conventions/rules/ssr.md +47 -0
- package/guidelines/conventions/rules/style.md +43 -0
- package/guidelines/conventions/rules/test.md +34 -0
- package/guidelines/conventions/rules/ts.md +95 -0
- package/guidelines/conventions/rules/tsx.md +75 -0
- package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
- package/guidelines/pageRule/pageRule.instruction.md +4 -3
- package/guidelines/queryRule/queryRule.instruction.md +4 -0
- package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +3 -3
- package/incrementalBuilder.proc.js +6 -6
- package/{index-pcwzkdqb.js → index-1p0qbq3m.js} +1 -1
- package/{index-xb8809yb.js → index-1shvxzt0.js} +3 -3
- package/{index-a58emady.js → index-266dewjs.js} +11 -11
- package/{index-bt438yxm.js → index-3yz30c07.js} +5 -4
- package/{index-xjf5j657.js → index-4mj92tsh.js} +952 -47
- package/index-4pdts00b.js +1604 -0
- package/{index-42j4a8zq.js → index-8559hsz4.js} +4 -3
- package/{index-wcej7g4z.js → index-8scw1pjk.js} +93 -23
- package/{index-a5dhqkdr.js → index-96wzdhfh.js} +74 -233
- package/index-9bv479q5.js +1 -0
- package/index-9rvcs76p.js +653 -0
- package/index-am36s3jh.js +3582 -0
- package/index-b8c289dx.js +444 -0
- package/{index-espk51ah.js → index-dd44g6vz.js} +3 -3
- package/{index-3wypz6xj.js → index-eja64h28.js} +7 -3
- package/index-fbewhg4g.js +590 -0
- package/index-jje9qzyq.js +27 -0
- package/{index-j9vyj3dj.js → index-k5jbcxyh.js} +3 -3
- package/{index-2mwc0g0d.js → index-ksfgqq1x.js} +1 -1
- package/index-m5n3ka0p.js +18 -0
- package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
- package/{index-6txx6a9p.js → index-payhwt51.js} +21 -29
- package/{index-2azahjaw.js → index-qkkdhjm6.js} +2 -2
- package/{index-74tjjsnc.js → index-qxzrp5xt.js} +33 -37
- package/{index-qfp55x1y.js → index-r0k3ham2.js} +4 -4
- package/{index-hmt54t45.js → index-r2w2eh93.js} +4 -4
- package/index-r2wedvqn.js +138 -0
- package/{index-skk9zc1x.js → index-rnphv731.js} +2 -2
- package/{index-9th4gszy.js → index-s6da8ta9.js} +82 -1227
- package/index-tenw3mah.js +225 -0
- package/{index-31es1yev.js → index-tgt2fnd6.js} +107 -6
- package/{index-55j120r8.js → index-vxmy1p4f.js} +16 -36
- package/{index-301pdbzz.js → index-w4k2ragk.js} +7 -7
- package/{index-js6geqjn.js → index-w7q6h97v.js} +1 -1
- package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
- package/{index-2xcc2ax5.js → index-xq543a5y.js} +2 -2
- package/{index-0fz95kxe.js → index-xqgwjz7a.js} +1 -1
- package/{index-40brg4px.js → index-xxfy1jp2.js} +4 -4
- package/{index-905qdgqp.js → index-z4b84y6k.js} +1 -1
- package/index-zcf6k8a5.js +410 -0
- package/index.js +23 -22
- package/{library.command-gycrwhf1.js → library.command-2853y6mk.js} +3 -3
- package/{localRegistry.command-jtd8gaes.js → localRegistry.command-76ds31p4.js} +19 -15
- package/{module.command-v6hgs1bc.js → module.command-yfnb0abs.js} +5 -5
- package/{package.command-shzpcfph.js → package.command-d9s86hp9.js} +3 -3
- package/package.json +2 -2
- package/{page.command-ptxn5kqk.js → page.command-6a8a8rd1.js} +3 -3
- package/{pipeline.command-zz31pgax.js → pipeline.command-rt3rwd2z.js} +2 -2
- package/{primitive.command-a1vse91z.js → primitive.command-emcebgrq.js} +6 -6
- package/{projectTypecheck-2ztky9cf.js → projectTypecheck-51m7eh1f.js} +1 -1
- package/{prompter-76k56b37.js → prompter-hgcta8pb.js} +1 -1
- package/quality.command-xtrk0n3x.js +76 -0
- package/{repair.command-cvazbz99.js → repair.command-51szxnxx.js} +5 -5
- package/{routeSourceValidator-6jd0q6r6.js → routeSourceValidator-4h947v7c.js} +13 -3
- package/{scalar.command-0acvyp26.js → scalar.command-8qv27t82.js} +4 -4
- package/skills/akan-agent/SKILL.md +36 -0
- package/skills/akan-code/SKILL.md +1 -0
- package/skills/akan-debug/SKILL.md +40 -6
- package/skills/akan-deps/SKILL.md +1 -2
- package/skills/akan-mcp/SKILL.md +40 -0
- package/skills/akan-page/SKILL.md +44 -0
- package/skills/akan-query/SKILL.md +38 -0
- package/skills/akan-runtime/SKILL.md +40 -0
- package/skills/akan-scaffold/SKILL.md +16 -6
- package/skills/akan-transport/SKILL.md +40 -0
- package/skills/akan-validate/SKILL.md +13 -11
- package/{subspace.command-822qx2bx.js → subspace.command-pn56pnh8.js} +8 -8
- package/templates/__scalar/__model__/__model__.constant.ts +3 -5
- package/templates/__scalar/__model__/__model__.dictionary.ts +6 -5
- package/templates/__scalar/__model__/__model__.document.ts +3 -3
- package/templates/app/akan.config.ts +2 -3
- package/templates/app/env/env.client.ts +2 -4
- package/templates/app/env/env.client.type.ts +2 -3
- package/templates/app/env/env.server.ts +2 -3
- package/templates/app/lib/___appName__/__appName__.dictionary.ts +1 -2
- package/templates/app/lib/___appName__/__appName__.service.ts +3 -3
- package/templates/app/lib/___appName__/__appName__.signal.ts +5 -5
- package/templates/app/lib/___appName__/__appName__.store.ts +4 -6
- package/templates/app/lib/option.ts +2 -3
- package/templates/app/main.ts +2 -4
- package/templates/app/page/_index.tsx +3 -3
- package/templates/app/page/_layout.tsx +13 -10
- package/templates/appSample/lib/__scalar/workHistory/workHistory.constant.ts +1 -5
- package/templates/appSample/lib/__scalar/workHistory/workHistory.dictionary.ts +1 -1
- package/templates/appSample/lib/_noti/noti.signal.ts +1 -1
- package/templates/appSample/lib/task/Task.Template.tsx +2 -1
- package/templates/appSample/lib/task/Task.Unit.tsx +3 -2
- package/templates/appSample/lib/task/Task.Util.tsx +16 -4
- package/templates/appSample/lib/task/task.constant.ts +1 -5
- package/templates/appSample/lib/task/task.dictionary.ts +2 -8
- package/templates/appSample/lib/task/task.document.ts +1 -1
- package/templates/appSample/page/task/_index.tsx +2 -1
- package/templates/appSample/page/task/new.tsx +2 -1
- package/templates/appSample/ui/QuantityControl.tsx +5 -9
- package/templates/biomeForm.ts +144 -0
- package/templates/crudPages/[__model__Id]/edit/page.tsx +3 -3
- package/templates/crudPages/[__model__Id]/page.tsx +5 -5
- package/templates/crudPages/new/page.tsx +4 -3
- package/templates/crudPages/page.tsx +3 -3
- package/templates/crudSinglePage/page.tsx +9 -5
- package/templates/libRoot/akan.config.ts +2 -3
- package/templates/libRoot/lib/___libName__/__libName__.dictionary.ts +1 -2
- package/templates/libRoot/lib/___libName__/__libName__.service.ts +5 -4
- package/templates/libRoot/lib/___libName__/__libName__.signal.ts +6 -5
- package/templates/libRoot/lib/___libName__/__libName__.store.ts +5 -6
- package/templates/libRoot/lib/option.ts +1 -2
- package/templates/module/__Model__.Template.tsx +11 -10
- package/templates/module/__Model__.Unit.tsx +18 -5
- package/templates/module/__Model__.Util.tsx +9 -7
- package/templates/module/__Model__.View.tsx +9 -6
- package/templates/module/__Model__.Zone.tsx +25 -17
- package/templates/module/__model__.constant.ts +8 -9
- package/templates/module/__model__.dictionary.ts +16 -17
- package/templates/module/__model__.document.ts +6 -8
- package/templates/module/__model__.service.ts +3 -3
- package/templates/module/__model__.signal.ts +11 -10
- package/templates/module/__model__.store.ts +3 -5
- package/templates/service/__model__.dictionary.ts +6 -5
- package/templates/service/__model__.service.ts +3 -3
- package/templates/service/__model__.signal.ts +5 -4
- package/templates/service/__model__.store.ts +3 -5
- package/templates/workspaceRoot/.gitignore.template +3 -0
- package/templates/workspaceRoot/.vscode/settings.json.template +21 -21
- package/templates/workspaceRoot/AGENTS.md.template +4 -10
- package/{tunnel.command-ycmja19q.js → tunnel.command-q2h0j2en.js} +7 -7
- package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
- package/typecheck.proc.js +6 -1
- package/verify.command-z1dsbmrt.js +91 -0
- package/{workflow.command-abb1d5xy.js → workflow.command-r3y67jeq.js} +47 -13
- package/workspace.command-t2f0xsrw.js +263 -0
- package/CodeAgent-8d5qs787.js +0 -9
- package/TunnelShare-qkm8zp03.js +0 -14
- package/agent.command-ydftceda.js +0 -25
- package/cloud.script-nqevg5qw.js +0 -24
- package/context.runner-8gg030b0.js +0 -25
- package/guidelines/conventions/conventions.instruction.md +0 -617
- package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
- package/index-4vgbysa0.js +0 -279
- package/index-7md2g9vw.js +0 -6
- package/index-b70zct19.js +0 -856
- package/index-zzvvc845.js +0 -74
- package/quality.command-ah8qcakd.js +0 -1478
- package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
- package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
- package/workspace.command-qm7cw29v.js +0 -521
|
@@ -0,0 +1,1604 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
ApplicationBuildReporter
|
|
4
|
+
} from "./index-p6x5b7hr.js";
|
|
5
|
+
import {
|
|
6
|
+
script,
|
|
7
|
+
ExitCodeError,
|
|
8
|
+
markCliErrorPrinted,
|
|
9
|
+
assertPromptable
|
|
10
|
+
} from "./index-eja64h28.js";
|
|
11
|
+
import {
|
|
12
|
+
AppExecutor,
|
|
13
|
+
LibExecutor,
|
|
14
|
+
PkgExecutor
|
|
15
|
+
} from "./index-8scw1pjk.js";
|
|
16
|
+
import {
|
|
17
|
+
DesktopServerStage
|
|
18
|
+
} from "./index-w7q6h97v.js";
|
|
19
|
+
import {
|
|
20
|
+
LibraryScript
|
|
21
|
+
} from "./index-xq543a5y.js";
|
|
22
|
+
import {
|
|
23
|
+
ApplicationRunner,
|
|
24
|
+
VerifyScope
|
|
25
|
+
} from "./index-s6da8ta9.js";
|
|
26
|
+
import {
|
|
27
|
+
PreviewChrome2,
|
|
28
|
+
PreviewView2,
|
|
29
|
+
stripAnsi
|
|
30
|
+
} from "./index-tenw3mah.js";
|
|
31
|
+
import {
|
|
32
|
+
formatSlicePlan
|
|
33
|
+
} from "./index-1p0qbq3m.js";
|
|
34
|
+
import {
|
|
35
|
+
openBrowser
|
|
36
|
+
} from "./index-9dp031by.js";
|
|
37
|
+
|
|
38
|
+
// pkgs/@akanjs/cli/application/application.script.ts
|
|
39
|
+
import { confirm } from "@inquirer/prompts";
|
|
40
|
+
import { Logger as Logger3, toError } from "akanjs/common";
|
|
41
|
+
|
|
42
|
+
// pkgs/@akanjs/cli/application/appPreview.ts
|
|
43
|
+
import { closeSync, openSync, realpathSync } from "fs";
|
|
44
|
+
import { mkdir as mkdir2 } from "fs/promises";
|
|
45
|
+
import path2 from "path";
|
|
46
|
+
import { parseRouteModuleKey } from "akanjs/common";
|
|
47
|
+
|
|
48
|
+
// pkgs/@akanjs/cli/application/devBootConcurrency.ts
|
|
49
|
+
import os from "os";
|
|
50
|
+
import { MemoryLimit } from "akanjs/server/memoryLimit";
|
|
51
|
+
|
|
52
|
+
class DevBootConcurrency {
|
|
53
|
+
static perAppBytes = 1800 * 1024 * 1024;
|
|
54
|
+
static memoryShare = 0.5;
|
|
55
|
+
static coresPerApp = 4;
|
|
56
|
+
static budget() {
|
|
57
|
+
const hostBytes = os.totalmem();
|
|
58
|
+
const declaredBytes = MemoryLimit.parseBytesEnv("AKAN_MEMORY_LIMIT") ?? MemoryLimit.readCgroupBytes();
|
|
59
|
+
return { memoryBytes: Math.min(hostBytes, declaredBytes ?? hostBytes), cores: os.availableParallelism() };
|
|
60
|
+
}
|
|
61
|
+
static resolve(appCount, requested, budget = DevBootConcurrency.budget()) {
|
|
62
|
+
const apps = Math.max(1, Math.trunc(appCount));
|
|
63
|
+
if (requested !== null && Number.isFinite(requested)) {
|
|
64
|
+
const asked = Math.max(1, Math.trunc(requested));
|
|
65
|
+
return { concurrency: Math.min(apps, asked), reason: `--concurrency ${asked}` };
|
|
66
|
+
}
|
|
67
|
+
const byMemory = Math.floor(budget.memoryBytes * DevBootConcurrency.memoryShare / DevBootConcurrency.perAppBytes);
|
|
68
|
+
const byCores = Math.floor(budget.cores / DevBootConcurrency.coresPerApp);
|
|
69
|
+
return {
|
|
70
|
+
concurrency: Math.max(1, Math.min(apps, byMemory, byCores)),
|
|
71
|
+
reason: `${budget.cores} cores, ${DevBootConcurrency.#formatBytes(budget.memoryBytes)} memory`
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
static describe(appCount, plan) {
|
|
75
|
+
if (plan.concurrency >= appCount)
|
|
76
|
+
return `booting all ${appCount} apps at once (${plan.reason})`;
|
|
77
|
+
return `booting ${plan.concurrency} of ${appCount} apps at a time (${plan.reason}) \u2014 --concurrency raises it`;
|
|
78
|
+
}
|
|
79
|
+
static #formatBytes(bytes) {
|
|
80
|
+
const gigabytes = bytes / 1024 ** 3;
|
|
81
|
+
return gigabytes >= 10 ? `${Math.round(gigabytes)}GB` : `${gigabytes.toFixed(1)}GB`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// pkgs/@akanjs/cli/application/devSessionLog.ts
|
|
86
|
+
import { mkdir, rename } from "fs/promises";
|
|
87
|
+
import path from "path";
|
|
88
|
+
import dayjs from "dayjs";
|
|
89
|
+
|
|
90
|
+
class DevSessionLog {
|
|
91
|
+
static fileName = "dev.log";
|
|
92
|
+
static previousFileName = "dev.prev.log";
|
|
93
|
+
static flushMs = 200;
|
|
94
|
+
static bufferBytes = 64 * 1024;
|
|
95
|
+
#workspaceRoot;
|
|
96
|
+
#appNames;
|
|
97
|
+
#now;
|
|
98
|
+
#writers = new Map;
|
|
99
|
+
#partial = new Map;
|
|
100
|
+
#lastState = new Map;
|
|
101
|
+
#flushTimer = null;
|
|
102
|
+
constructor({ workspaceRoot, apps, now = () => new Date }) {
|
|
103
|
+
this.#workspaceRoot = workspaceRoot;
|
|
104
|
+
this.#appNames = [...apps];
|
|
105
|
+
this.#now = now;
|
|
106
|
+
}
|
|
107
|
+
get appNames() {
|
|
108
|
+
return [...this.#appNames];
|
|
109
|
+
}
|
|
110
|
+
pathOf(app) {
|
|
111
|
+
return path.join(this.#runtimeDirOf(app), DevSessionLog.fileName);
|
|
112
|
+
}
|
|
113
|
+
previousPathOf(app) {
|
|
114
|
+
return path.join(this.#runtimeDirOf(app), DevSessionLog.previousFileName);
|
|
115
|
+
}
|
|
116
|
+
relativePathOf(app) {
|
|
117
|
+
return path.relative(this.#workspaceRoot, this.pathOf(app));
|
|
118
|
+
}
|
|
119
|
+
async open() {
|
|
120
|
+
const stamp = dayjs(this.#now()).format("YYYY-MM-DD HH:mm:ss");
|
|
121
|
+
for (const app of this.#appNames) {
|
|
122
|
+
const file = this.pathOf(app);
|
|
123
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
124
|
+
await rename(file, this.previousPathOf(app)).catch(() => {
|
|
125
|
+
return;
|
|
126
|
+
});
|
|
127
|
+
this.#writers.set(app, Bun.file(file).writer({ highWaterMark: DevSessionLog.bufferBytes }));
|
|
128
|
+
this.#writeLine(app, `\u2500\u2500 akan start \xB7 ${app} \xB7 ${stamp} \u2500\u2500`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
write(app, kind, chunk) {
|
|
132
|
+
const key = `${app}:${kind}`;
|
|
133
|
+
const parts = `${this.#partial.get(key) ?? ""}${chunk}`.split(`
|
|
134
|
+
`);
|
|
135
|
+
this.#partial.set(key, parts.pop() ?? "");
|
|
136
|
+
for (const line of parts)
|
|
137
|
+
this.#writeLine(app, stripAnsi(line));
|
|
138
|
+
}
|
|
139
|
+
note(text) {
|
|
140
|
+
for (const app of this.#appNames)
|
|
141
|
+
this.#writeLine(app, `[akan] ${text}`);
|
|
142
|
+
}
|
|
143
|
+
status(statuses) {
|
|
144
|
+
for (const status of statuses) {
|
|
145
|
+
if (this.#lastState.get(status.name) === status.state)
|
|
146
|
+
continue;
|
|
147
|
+
this.#lastState.set(status.name, status.state);
|
|
148
|
+
const detail = status.detail ? ` (${status.detail})` : "";
|
|
149
|
+
const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
|
|
150
|
+
this.#writeLine(status.name, `[akan] ${status.name} ${status.state}${detail}${where}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async close() {
|
|
154
|
+
for (const [key, remainder] of this.#partial) {
|
|
155
|
+
if (!remainder)
|
|
156
|
+
continue;
|
|
157
|
+
this.#writeLine(key.slice(0, key.lastIndexOf(":")), stripAnsi(remainder));
|
|
158
|
+
}
|
|
159
|
+
this.#partial.clear();
|
|
160
|
+
if (this.#flushTimer)
|
|
161
|
+
clearTimeout(this.#flushTimer);
|
|
162
|
+
this.#flushTimer = null;
|
|
163
|
+
await Promise.all([...this.#writers.values()].map(async (writer) => await writer.end()));
|
|
164
|
+
this.#writers.clear();
|
|
165
|
+
}
|
|
166
|
+
#runtimeDirOf(app) {
|
|
167
|
+
return path.join(this.#workspaceRoot, "local", "apps", app, "runtime");
|
|
168
|
+
}
|
|
169
|
+
#writeLine(app, text) {
|
|
170
|
+
const writer = this.#writers.get(app);
|
|
171
|
+
if (!writer)
|
|
172
|
+
return;
|
|
173
|
+
writer.write(`${text}
|
|
174
|
+
`);
|
|
175
|
+
this.#scheduleFlush();
|
|
176
|
+
}
|
|
177
|
+
#scheduleFlush() {
|
|
178
|
+
if (this.#flushTimer)
|
|
179
|
+
return;
|
|
180
|
+
this.#flushTimer = setTimeout(() => {
|
|
181
|
+
this.#flushTimer = null;
|
|
182
|
+
for (const writer of this.#writers.values())
|
|
183
|
+
writer.flush();
|
|
184
|
+
}, DevSessionLog.flushMs);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// pkgs/@akanjs/cli/application/devSupervisor.ts
|
|
189
|
+
class DevSupervisor {
|
|
190
|
+
static resolveDevUi(plain, {
|
|
191
|
+
isTty = !!process.stdout.isTTY,
|
|
192
|
+
columns = process.stdout.columns ?? 0
|
|
193
|
+
} = {}) {
|
|
194
|
+
if (plain)
|
|
195
|
+
return { mode: "stream", downgraded: false };
|
|
196
|
+
if (!isTty || columns <= 0)
|
|
197
|
+
return { mode: "stream", downgraded: true };
|
|
198
|
+
return { mode: "tui", downgraded: false };
|
|
199
|
+
}
|
|
200
|
+
static supervisedEnvKey = "AKAN_DEV_SUPERVISED";
|
|
201
|
+
static childHooks() {
|
|
202
|
+
if (process.env[DevSupervisor.supervisedEnvKey] !== "1" || !process.send)
|
|
203
|
+
return {};
|
|
204
|
+
const send = process.send.bind(process);
|
|
205
|
+
return {
|
|
206
|
+
stdio: "pipe",
|
|
207
|
+
onDevEvent: (event) => {
|
|
208
|
+
try {
|
|
209
|
+
send(event);
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
static bootTimeoutMs = 180000;
|
|
215
|
+
static shutdownGraceMs = 12000;
|
|
216
|
+
#options;
|
|
217
|
+
#children = new Map;
|
|
218
|
+
#sessionLog;
|
|
219
|
+
#view = null;
|
|
220
|
+
#stopping = false;
|
|
221
|
+
constructor(options) {
|
|
222
|
+
this.#options = options;
|
|
223
|
+
this.#sessionLog = new DevSessionLog({
|
|
224
|
+
workspaceRoot: options.apps[0]?.workspace.workspaceRoot ?? process.cwd(),
|
|
225
|
+
apps: options.apps.map((app) => app.name)
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
get statuses() {
|
|
229
|
+
return [...this.#children.values()].map((child) => child.status);
|
|
230
|
+
}
|
|
231
|
+
get sessionLog() {
|
|
232
|
+
return this.#sessionLog;
|
|
233
|
+
}
|
|
234
|
+
async run(view) {
|
|
235
|
+
this.#view = view;
|
|
236
|
+
await this.#sessionLog.open();
|
|
237
|
+
const ports = await this.#assignPorts();
|
|
238
|
+
for (const app of this.#options.apps)
|
|
239
|
+
this.#children.set(app.name, this.#makeChild(app, ports.get(app.name) ?? 0));
|
|
240
|
+
this.#publishStatus();
|
|
241
|
+
const logPaths = this.#sessionLog.appNames.map((name) => this.#sessionLog.relativePathOf(name));
|
|
242
|
+
this.#note(`session log: ${logPaths.join(" \xB7 ")}`, "info");
|
|
243
|
+
const stopped = this.#installSignalHandlers();
|
|
244
|
+
this.#bootInOrder();
|
|
245
|
+
await Promise.race([view.waitForExit(), stopped]);
|
|
246
|
+
await this.stop();
|
|
247
|
+
view.close?.();
|
|
248
|
+
await this.#sessionLog.close();
|
|
249
|
+
}
|
|
250
|
+
async#assignPorts() {
|
|
251
|
+
const taken = new Set;
|
|
252
|
+
const ports = new Map;
|
|
253
|
+
for (const app of this.#options.apps) {
|
|
254
|
+
let port = await app.getDevPort();
|
|
255
|
+
while (taken.has(port))
|
|
256
|
+
port += 1;
|
|
257
|
+
taken.add(port);
|
|
258
|
+
ports.set(app.name, port);
|
|
259
|
+
}
|
|
260
|
+
return ports;
|
|
261
|
+
}
|
|
262
|
+
#makeChild(app, port) {
|
|
263
|
+
const { promise: booted, resolve: markBooted } = Promise.withResolvers();
|
|
264
|
+
return {
|
|
265
|
+
status: {
|
|
266
|
+
app,
|
|
267
|
+
name: app.name,
|
|
268
|
+
port,
|
|
269
|
+
url: `http://localhost:${port}`,
|
|
270
|
+
shareUrl: this.#options.shares?.get(app.name) ?? null,
|
|
271
|
+
state: "starting",
|
|
272
|
+
detail: "queued",
|
|
273
|
+
exitCode: null
|
|
274
|
+
},
|
|
275
|
+
proc: null,
|
|
276
|
+
booted,
|
|
277
|
+
markBooted,
|
|
278
|
+
opened: false
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
async#bootInOrder() {
|
|
282
|
+
const queue = [...this.#children.values()];
|
|
283
|
+
const plan = DevBootConcurrency.resolve(queue.length, this.#options.concurrency ?? null);
|
|
284
|
+
const concurrency = plan.concurrency;
|
|
285
|
+
if (queue.length > 1)
|
|
286
|
+
this.#note(DevBootConcurrency.describe(queue.length, plan), "info");
|
|
287
|
+
const waves = [];
|
|
288
|
+
for (let idx = 0;idx < queue.length; idx += concurrency)
|
|
289
|
+
waves.push(queue.slice(idx, idx + concurrency));
|
|
290
|
+
for (const wave of waves) {
|
|
291
|
+
if (this.#stopping)
|
|
292
|
+
return;
|
|
293
|
+
for (const child of wave)
|
|
294
|
+
this.#spawnChild(child);
|
|
295
|
+
this.#publishStatus();
|
|
296
|
+
await Promise.all(wave.map(async (child) => await this.#waitForBoot(child)));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async#waitForBoot(child) {
|
|
300
|
+
if (await DevSupervisor.timesOut(child.booted, DevSupervisor.bootTimeoutMs))
|
|
301
|
+
this.#note(`${child.status.name} has not finished booting after ${Math.round(DevSupervisor.bootTimeoutMs / 1000)}s; starting the next app anyway`, "warn");
|
|
302
|
+
}
|
|
303
|
+
static async timesOut(work, ms) {
|
|
304
|
+
let timer;
|
|
305
|
+
const expired = new Promise((resolve) => {
|
|
306
|
+
timer = setTimeout(() => resolve(true), ms);
|
|
307
|
+
});
|
|
308
|
+
try {
|
|
309
|
+
return await Promise.race([work.then(() => false), expired]);
|
|
310
|
+
} finally {
|
|
311
|
+
clearTimeout(timer);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
static childArgs(name, { write = true } = {}) {
|
|
315
|
+
return [
|
|
316
|
+
"start",
|
|
317
|
+
name,
|
|
318
|
+
"--plain",
|
|
319
|
+
"--dbup",
|
|
320
|
+
"false",
|
|
321
|
+
"--write",
|
|
322
|
+
String(write)
|
|
323
|
+
];
|
|
324
|
+
}
|
|
325
|
+
#spawnChild(child) {
|
|
326
|
+
const { app, name, port } = child.status;
|
|
327
|
+
const args = DevSupervisor.childArgs(name, { write: this.#options.write ?? true });
|
|
328
|
+
const proc = Bun.spawn([process.execPath, Bun.main, ...args], {
|
|
329
|
+
cwd: app.workspace.workspaceRoot,
|
|
330
|
+
env: {
|
|
331
|
+
...process.env,
|
|
332
|
+
[DevSupervisor.supervisedEnvKey]: "1",
|
|
333
|
+
AKAN_PUBLIC_APP_NAME: name,
|
|
334
|
+
AKAN_DEV_PORT: String(port)
|
|
335
|
+
},
|
|
336
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
337
|
+
ipc: (message) => {
|
|
338
|
+
if (!message || typeof message !== "object")
|
|
339
|
+
return;
|
|
340
|
+
if ("booted" in message)
|
|
341
|
+
child.markBooted();
|
|
342
|
+
else if (typeof message.state === "string")
|
|
343
|
+
this.#applyChildEvent(child, message);
|
|
344
|
+
},
|
|
345
|
+
serialization: "advanced",
|
|
346
|
+
onExit: (_proc, exitCode, signalCode) => {
|
|
347
|
+
child.proc = null;
|
|
348
|
+
child.status.exitCode = exitCode;
|
|
349
|
+
if (this.#stopping)
|
|
350
|
+
return;
|
|
351
|
+
child.status.state = "stopped";
|
|
352
|
+
child.status.detail = signalCode ? `killed by ${signalCode}` : `exited with ${exitCode}`;
|
|
353
|
+
child.markBooted();
|
|
354
|
+
this.#publishStatus();
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
child.proc = proc;
|
|
358
|
+
child.status.state = "starting";
|
|
359
|
+
child.status.detail = `pid ${proc.pid}`;
|
|
360
|
+
this.#drain(proc.stdout, name, "stdout");
|
|
361
|
+
this.#drain(proc.stderr, name, "stderr");
|
|
362
|
+
}
|
|
363
|
+
#applyChildEvent(child, event) {
|
|
364
|
+
child.status.state = event.state;
|
|
365
|
+
child.status.detail = event.detail ?? "";
|
|
366
|
+
if (event.state === "ready") {
|
|
367
|
+
if (this.#options.open && !child.opened) {
|
|
368
|
+
child.opened = true;
|
|
369
|
+
openBrowser(child.status.url);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (event.state === "failed")
|
|
373
|
+
child.markBooted();
|
|
374
|
+
this.#publishStatus();
|
|
375
|
+
}
|
|
376
|
+
async#drain(stream, name, kind) {
|
|
377
|
+
const decoder = new TextDecoder;
|
|
378
|
+
try {
|
|
379
|
+
for await (const chunk of stream) {
|
|
380
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
381
|
+
if (!text)
|
|
382
|
+
continue;
|
|
383
|
+
this.#view?.onOutput(name, kind, text);
|
|
384
|
+
this.#sessionLog.write(name, kind, text);
|
|
385
|
+
}
|
|
386
|
+
} catch {}
|
|
387
|
+
}
|
|
388
|
+
#publishStatus() {
|
|
389
|
+
this.#view?.onStatus(this.statuses);
|
|
390
|
+
this.#sessionLog.status(this.statuses);
|
|
391
|
+
}
|
|
392
|
+
#note(text, level) {
|
|
393
|
+
this.#view?.onNote(text, level);
|
|
394
|
+
this.#sessionLog.note(text);
|
|
395
|
+
}
|
|
396
|
+
#installSignalHandlers() {
|
|
397
|
+
return new Promise((resolve) => {
|
|
398
|
+
let asked = false;
|
|
399
|
+
const onSignal = () => {
|
|
400
|
+
if (asked) {
|
|
401
|
+
this.#note("abandoning the wait; children may be left running", "warn");
|
|
402
|
+
process.exit(130);
|
|
403
|
+
}
|
|
404
|
+
asked = true;
|
|
405
|
+
resolve();
|
|
406
|
+
};
|
|
407
|
+
process.on("SIGINT", onSignal);
|
|
408
|
+
process.on("SIGTERM", onSignal);
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
async restart(name) {
|
|
412
|
+
const child = this.#children.get(name);
|
|
413
|
+
if (!child || this.#stopping)
|
|
414
|
+
return;
|
|
415
|
+
const running = child.proc;
|
|
416
|
+
if (running) {
|
|
417
|
+
running.kill("SIGTERM");
|
|
418
|
+
await running.exited;
|
|
419
|
+
}
|
|
420
|
+
child.status.state = "starting";
|
|
421
|
+
child.status.detail = "restarting";
|
|
422
|
+
child.status.exitCode = null;
|
|
423
|
+
this.#publishStatus();
|
|
424
|
+
this.#spawnChild(child);
|
|
425
|
+
this.#publishStatus();
|
|
426
|
+
}
|
|
427
|
+
async stop() {
|
|
428
|
+
if (this.#stopping)
|
|
429
|
+
return;
|
|
430
|
+
this.#stopping = true;
|
|
431
|
+
const running = [...this.#children.values()].filter((child) => Boolean(child.proc));
|
|
432
|
+
for (const child of running)
|
|
433
|
+
child.proc.kill("SIGTERM");
|
|
434
|
+
const exited = Promise.all(running.map(async (child) => await child.proc.exited));
|
|
435
|
+
if (!await DevSupervisor.timesOut(exited, DevSupervisor.shutdownGraceMs))
|
|
436
|
+
return;
|
|
437
|
+
for (const child of running) {
|
|
438
|
+
if (child.proc.killed)
|
|
439
|
+
continue;
|
|
440
|
+
this.#note(`${child.status.name} did not exit in time; killing it`, "warn");
|
|
441
|
+
child.proc.kill("SIGKILL");
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// pkgs/@akanjs/cli/application/hostProcessProbe.ts
|
|
447
|
+
import { readdirSync, readFileSync, readlinkSync } from "fs";
|
|
448
|
+
|
|
449
|
+
class HostProcessProbe {
|
|
450
|
+
static timeoutMs = 3000;
|
|
451
|
+
static win32TimeoutMs = 20000;
|
|
452
|
+
static #procTcpListen = "0A";
|
|
453
|
+
static #win32ProcessQuery = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress";
|
|
454
|
+
platform;
|
|
455
|
+
#win32Table = null;
|
|
456
|
+
constructor(platform = process.platform) {
|
|
457
|
+
this.platform = platform;
|
|
458
|
+
}
|
|
459
|
+
async listenersOn(port) {
|
|
460
|
+
if (this.platform === "win32")
|
|
461
|
+
return HostProcessProbe.parseNetstat(await HostProcessProbe.run(["netstat", "-ano"]), port);
|
|
462
|
+
if (this.platform === "linux")
|
|
463
|
+
return HostProcessProbe.#procListenersOn(port);
|
|
464
|
+
const output = await HostProcessProbe.run(["lsof", "-ti", `tcp:${port}`, "-sTCP:LISTEN"]);
|
|
465
|
+
return [
|
|
466
|
+
...new Set(output.split(`
|
|
467
|
+
`).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))
|
|
468
|
+
];
|
|
469
|
+
}
|
|
470
|
+
async parentOf(pid) {
|
|
471
|
+
if (this.platform === "win32") {
|
|
472
|
+
const child = await this.#win32Process(pid);
|
|
473
|
+
const parent = child ? await this.#win32Process(child.ppid) : null;
|
|
474
|
+
return child && parent ? HostProcessProbe.parentPidOf(child, parent) : null;
|
|
475
|
+
}
|
|
476
|
+
if (this.platform === "linux") {
|
|
477
|
+
const stat = HostProcessProbe.#readProc(pid, "stat");
|
|
478
|
+
return stat === null ? null : HostProcessProbe.parseProcStatPpid(stat);
|
|
479
|
+
}
|
|
480
|
+
const parsed = Number((await HostProcessProbe.run(["ps", "-p", String(pid), "-o", "ppid="])).trim());
|
|
481
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
|
482
|
+
}
|
|
483
|
+
async commandOf(pid) {
|
|
484
|
+
if (this.platform === "win32")
|
|
485
|
+
return (await this.#win32Process(pid))?.command ?? null;
|
|
486
|
+
if (this.platform === "linux") {
|
|
487
|
+
const cmdline = HostProcessProbe.#readProc(pid, "cmdline");
|
|
488
|
+
return cmdline?.split("\x00").filter(Boolean).join(" ") || null;
|
|
489
|
+
}
|
|
490
|
+
return (await HostProcessProbe.run(["ps", "-ww", "-p", String(pid), "-o", "command="])).trim() || null;
|
|
491
|
+
}
|
|
492
|
+
static parentPidOf(child, parent) {
|
|
493
|
+
if (child.ppid !== parent.pid)
|
|
494
|
+
return null;
|
|
495
|
+
if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
|
|
496
|
+
return null;
|
|
497
|
+
return parent.pid;
|
|
498
|
+
}
|
|
499
|
+
static parseNetstat(output, port) {
|
|
500
|
+
const pids = new Set;
|
|
501
|
+
for (const line of output.split(/\r?\n/)) {
|
|
502
|
+
const fields = line.trim().split(/\s+/);
|
|
503
|
+
if (fields[0] !== "TCP" || fields.length < 5)
|
|
504
|
+
continue;
|
|
505
|
+
const [, local, remote] = fields;
|
|
506
|
+
if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
|
|
507
|
+
continue;
|
|
508
|
+
const pid = Number(fields.at(-1));
|
|
509
|
+
if (Number.isInteger(pid) && pid > 0)
|
|
510
|
+
pids.add(pid);
|
|
511
|
+
}
|
|
512
|
+
return [...pids];
|
|
513
|
+
}
|
|
514
|
+
static parseProcNetTcp(text, port) {
|
|
515
|
+
const inodes = [];
|
|
516
|
+
for (const line of text.split(`
|
|
517
|
+
`).slice(1)) {
|
|
518
|
+
const fields = line.trim().split(/\s+/);
|
|
519
|
+
const [, local, , state, , , , , , inode] = fields;
|
|
520
|
+
if (!local || !inode || state !== HostProcessProbe.#procTcpListen || inode === "0")
|
|
521
|
+
continue;
|
|
522
|
+
if (Number.parseInt(local.slice(local.lastIndexOf(":") + 1), 16) === port)
|
|
523
|
+
inodes.push(inode);
|
|
524
|
+
}
|
|
525
|
+
return inodes;
|
|
526
|
+
}
|
|
527
|
+
static parseProcStatPpid(stat) {
|
|
528
|
+
const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
|
|
529
|
+
return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
|
|
530
|
+
}
|
|
531
|
+
static parseWin32Processes(json) {
|
|
532
|
+
const table = new Map;
|
|
533
|
+
let parsed;
|
|
534
|
+
try {
|
|
535
|
+
parsed = JSON.parse(json.trim() || "[]");
|
|
536
|
+
} catch {
|
|
537
|
+
return table;
|
|
538
|
+
}
|
|
539
|
+
const rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
540
|
+
for (const row of rows) {
|
|
541
|
+
if (typeof row?.ProcessId !== "number")
|
|
542
|
+
continue;
|
|
543
|
+
table.set(row.ProcessId, {
|
|
544
|
+
pid: row.ProcessId,
|
|
545
|
+
ppid: row.ParentProcessId ?? 0,
|
|
546
|
+
command: row.CommandLine?.trim() || null,
|
|
547
|
+
startedAt: HostProcessProbe.#parseCimDate(row.CreationDate)
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
return table;
|
|
551
|
+
}
|
|
552
|
+
static async run(command, timeoutMs = HostProcessProbe.timeoutMs) {
|
|
553
|
+
let proc;
|
|
554
|
+
try {
|
|
555
|
+
proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
556
|
+
} catch {
|
|
557
|
+
return "";
|
|
558
|
+
}
|
|
559
|
+
const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
|
|
560
|
+
try {
|
|
561
|
+
return await new Response(proc.stdout).text();
|
|
562
|
+
} catch {
|
|
563
|
+
return "";
|
|
564
|
+
} finally {
|
|
565
|
+
clearTimeout(timer);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
async#win32Process(pid) {
|
|
569
|
+
this.#win32Table ??= await HostProcessProbe.#queryWin32Processes();
|
|
570
|
+
if (!this.#win32Table.has(pid))
|
|
571
|
+
this.#win32Table = await HostProcessProbe.#queryWin32Processes();
|
|
572
|
+
return this.#win32Table.get(pid) ?? null;
|
|
573
|
+
}
|
|
574
|
+
static async#queryWin32Processes() {
|
|
575
|
+
const output = await HostProcessProbe.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", HostProcessProbe.#win32ProcessQuery], HostProcessProbe.win32TimeoutMs);
|
|
576
|
+
return HostProcessProbe.parseWin32Processes(output);
|
|
577
|
+
}
|
|
578
|
+
static #parseCimDate(value) {
|
|
579
|
+
if (!value)
|
|
580
|
+
return null;
|
|
581
|
+
const legacy = /\/Date\((\d+)/.exec(value)?.[1];
|
|
582
|
+
const ms = legacy ? Number(legacy) : Date.parse(value);
|
|
583
|
+
return Number.isFinite(ms) ? ms : null;
|
|
584
|
+
}
|
|
585
|
+
static #procListenersOn(port) {
|
|
586
|
+
const inodes = new Set(["tcp", "tcp6"].flatMap((table) => HostProcessProbe.parseProcNetTcp(HostProcessProbe.#readProc("net", table) ?? "", port)));
|
|
587
|
+
if (!inodes.size)
|
|
588
|
+
return [];
|
|
589
|
+
const pids = [];
|
|
590
|
+
for (const entry of HostProcessProbe.#listDir("/proc")) {
|
|
591
|
+
if (!/^\d+$/.test(entry))
|
|
592
|
+
continue;
|
|
593
|
+
const holds = HostProcessProbe.#listDir(`/proc/${entry}/fd`).some((fd) => {
|
|
594
|
+
const link = HostProcessProbe.#orElse(() => readlinkSync(`/proc/${entry}/fd/${fd}`), "");
|
|
595
|
+
const inode = /^socket:\[(\d+)\]$/.exec(link)?.[1];
|
|
596
|
+
return !!inode && inodes.has(inode);
|
|
597
|
+
});
|
|
598
|
+
if (holds)
|
|
599
|
+
pids.push(Number(entry));
|
|
600
|
+
}
|
|
601
|
+
return pids;
|
|
602
|
+
}
|
|
603
|
+
static #readProc(pid, file) {
|
|
604
|
+
return HostProcessProbe.#orElse(() => readFileSync(`/proc/${pid}/${file}`, "utf8"), null);
|
|
605
|
+
}
|
|
606
|
+
static #listDir(dir) {
|
|
607
|
+
return HostProcessProbe.#orElse(() => readdirSync(dir), []);
|
|
608
|
+
}
|
|
609
|
+
static #orElse(read, fallback) {
|
|
610
|
+
try {
|
|
611
|
+
return read();
|
|
612
|
+
} catch {
|
|
613
|
+
return fallback;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// pkgs/@akanjs/cli/application/appPreview.ts
|
|
619
|
+
class AppPreview {
|
|
620
|
+
static mobileViewport = { width: 390, height: 844 };
|
|
621
|
+
static desktopViewport = { width: 1280, height: 800 };
|
|
622
|
+
static csrTarget = "preview";
|
|
623
|
+
static settleMs = 1000;
|
|
624
|
+
static logGraceMs = 300;
|
|
625
|
+
static stopGraceMs = 15000;
|
|
626
|
+
static async run(app, options = {}) {
|
|
627
|
+
const engine = options.engine ?? PreviewChrome2.backend;
|
|
628
|
+
const unavailable = PreviewView2.unavailableReason(engine);
|
|
629
|
+
if (unavailable)
|
|
630
|
+
throw new Error(unavailable);
|
|
631
|
+
const { i18n } = await app.getConfig();
|
|
632
|
+
const changed = options.changed ? await AppPreview.#changedPages(app) : { paths: [], skipped: [] };
|
|
633
|
+
if (options.changed && !changed.paths.length && !options.paths?.length)
|
|
634
|
+
throw new Error(`No page to open: ${changed.skipped.join("; ")}. Pass a concrete path, e.g. \`akan preview ${app.name} /memo/1\`.`);
|
|
635
|
+
const paths = AppPreview.pagePaths([...options.paths ?? [], ...changed.paths], i18n, { csr: !!options.csr });
|
|
636
|
+
const port = await app.getDevPort();
|
|
637
|
+
const origin = `http://localhost:${port}`;
|
|
638
|
+
const root = app.workspace.workspaceRoot;
|
|
639
|
+
const previewDir = path2.join(ApplicationRunner.runtimeDirOf(app), "preview");
|
|
640
|
+
const started = await ApplicationRunner.answers(origin, app.name, root) ? null : await AppPreview.#startServer(app, port, previewDir);
|
|
641
|
+
const viewport = options.desktop ? AppPreview.desktopViewport : AppPreview.mobileViewport;
|
|
642
|
+
const report = {
|
|
643
|
+
app: app.name,
|
|
644
|
+
origin,
|
|
645
|
+
engine,
|
|
646
|
+
viewport,
|
|
647
|
+
server: started ? options.keep ? "kept" : "started" : "running",
|
|
648
|
+
serverPid: started?.proc.pid ?? null,
|
|
649
|
+
serverLog: started ? path2.relative(root, started.logPath) : null,
|
|
650
|
+
logsRead: false,
|
|
651
|
+
skipped: changed.skipped,
|
|
652
|
+
pages: []
|
|
653
|
+
};
|
|
654
|
+
try {
|
|
655
|
+
if (started)
|
|
656
|
+
await AppPreview.#waitBooted(started);
|
|
657
|
+
const records = [];
|
|
658
|
+
const tail = await AppPreview.#tail(app, records);
|
|
659
|
+
report.logsRead = !!tail;
|
|
660
|
+
try {
|
|
661
|
+
for (const pagePath of paths) {
|
|
662
|
+
const mark = records.length;
|
|
663
|
+
const page = await AppPreview.#probe(origin, pagePath, {
|
|
664
|
+
engine,
|
|
665
|
+
viewport,
|
|
666
|
+
screenshot: options.screenshot ? path2.join(previewDir, AppPreview.screenshotName(pagePath)) : null,
|
|
667
|
+
timeoutMs: options.timeoutMs ?? 60000
|
|
668
|
+
});
|
|
669
|
+
if (tail)
|
|
670
|
+
await Bun.sleep(AppPreview.logGraceMs);
|
|
671
|
+
AppPreview.attribute(page, records.slice(mark));
|
|
672
|
+
if (page.screenshot)
|
|
673
|
+
page.screenshot = path2.relative(root, page.screenshot);
|
|
674
|
+
report.pages.push(page);
|
|
675
|
+
}
|
|
676
|
+
} finally {
|
|
677
|
+
tail?.close();
|
|
678
|
+
}
|
|
679
|
+
return report;
|
|
680
|
+
} finally {
|
|
681
|
+
if (started && !options.keep)
|
|
682
|
+
await AppPreview.#stopServer(started.proc);
|
|
683
|
+
else
|
|
684
|
+
started?.proc.unref();
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
static pagePaths(paths, i18n, { csr }) {
|
|
688
|
+
const pages = (paths.length ? paths : ["/"]).map((raw) => {
|
|
689
|
+
const url = new URL(/^https?:\/\//.test(raw) ? raw : `http://localhost${raw.startsWith("/") ? "" : "/"}${raw}`);
|
|
690
|
+
const [first] = url.pathname.split("/").filter(Boolean);
|
|
691
|
+
if (!first || !i18n.locales.includes(first))
|
|
692
|
+
url.pathname = `/${i18n.defaultLocale}${url.pathname === "/" ? "/" : url.pathname}`;
|
|
693
|
+
if (csr) {
|
|
694
|
+
url.searchParams.set("csr", "true");
|
|
695
|
+
url.searchParams.set("akanMobileTarget", AppPreview.csrTarget);
|
|
696
|
+
}
|
|
697
|
+
return `${url.pathname}${url.search}`;
|
|
698
|
+
});
|
|
699
|
+
return [...new Set(pages)];
|
|
700
|
+
}
|
|
701
|
+
static changedPageLimit = 8;
|
|
702
|
+
static changedPages(sources, changedFiles) {
|
|
703
|
+
const realOf = (file) => {
|
|
704
|
+
try {
|
|
705
|
+
return realpathSync(file);
|
|
706
|
+
} catch {
|
|
707
|
+
return file;
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
const changed = new Set([...changedFiles].map(realOf));
|
|
711
|
+
const routes = sources.map((source) => ({
|
|
712
|
+
route: parseRouteModuleKey(source.key),
|
|
713
|
+
touched: changed.has(realOf(source.absPath))
|
|
714
|
+
}));
|
|
715
|
+
const layouts = routes.filter(({ route, touched }) => touched && route.kind === "layout").map(({ route }) => route.routeSegments.join("/"));
|
|
716
|
+
const reached = [];
|
|
717
|
+
const skipped = [];
|
|
718
|
+
let anyRoute = layouts.length > 0;
|
|
719
|
+
for (const { route, touched } of routes) {
|
|
720
|
+
if (route.kind !== "page")
|
|
721
|
+
continue;
|
|
722
|
+
anyRoute ||= touched;
|
|
723
|
+
const segments = route.routeSegments;
|
|
724
|
+
const reach = route.leaf === "_index" ? segments.length : segments.length - 1;
|
|
725
|
+
const wrapped = layouts.some((layout) => Array.from({ length: reach + 1 }, (_, idx) => segments.slice(0, idx).join("/")).includes(layout));
|
|
726
|
+
if (!touched && !wrapped)
|
|
727
|
+
continue;
|
|
728
|
+
const urlPath = route.pattern.replace(/^\/:lang/, "") || "/";
|
|
729
|
+
if (urlPath.includes("/:"))
|
|
730
|
+
skipped.push(`${urlPath} needs a concrete path`);
|
|
731
|
+
else
|
|
732
|
+
reached.push(urlPath);
|
|
733
|
+
}
|
|
734
|
+
if (!anyRoute)
|
|
735
|
+
return { paths: ["/"], skipped };
|
|
736
|
+
const paths = reached.sort((a, b) => a.localeCompare(b)).slice(0, AppPreview.changedPageLimit);
|
|
737
|
+
if (reached.length > paths.length)
|
|
738
|
+
skipped.push(`${reached.length - paths.length} more page(s) under a changed layout`);
|
|
739
|
+
return { paths, skipped };
|
|
740
|
+
}
|
|
741
|
+
static screenshotName(pagePath) {
|
|
742
|
+
const url = new URL(pagePath, "http://localhost");
|
|
743
|
+
const slug = url.pathname.split("/").filter(Boolean).join("-").replace(/[^\w-]/g, "_") || "index";
|
|
744
|
+
return `${slug}${url.searchParams.get("csr") === "true" ? ".csr" : ""}.png`;
|
|
745
|
+
}
|
|
746
|
+
static attribute(page, records) {
|
|
747
|
+
const pathname = new URL(page.finalUrl).pathname;
|
|
748
|
+
for (const record of records) {
|
|
749
|
+
if (record.name === "ClientReport") {
|
|
750
|
+
const href = typeof record.attrs?.href === "string" ? record.attrs.href : null;
|
|
751
|
+
if (href && new URL(href, page.finalUrl).pathname !== pathname)
|
|
752
|
+
continue;
|
|
753
|
+
page.clientReports.push(record.message);
|
|
754
|
+
} else
|
|
755
|
+
page.serverErrors.push(AppPreview.#firstLines(`[${record.name}] ${record.message}`));
|
|
756
|
+
}
|
|
757
|
+
page.failed ||= page.clientReports.length > 0 || page.serverErrors.length > 0;
|
|
758
|
+
}
|
|
759
|
+
static render(report) {
|
|
760
|
+
const server = {
|
|
761
|
+
running: "already running",
|
|
762
|
+
started: `started for this preview and stopped; its log: ${report.serverLog}`,
|
|
763
|
+
kept: `started for this preview and left running (pid ${report.serverPid}; stop it with \`${AppPreview.stopArgvOf(report.serverPid ?? 0).join(" ")}\`); its log: ${report.serverLog}`
|
|
764
|
+
}[report.server];
|
|
765
|
+
const lines = [
|
|
766
|
+
`${report.origin}: ${report.app} dev server, ${server}`,
|
|
767
|
+
`${report.engine}, ${report.viewport.width}x${report.viewport.height}`
|
|
768
|
+
];
|
|
769
|
+
if (!report.logsRead)
|
|
770
|
+
lines.push("The app's log socket did not answer, so client and server errors are not shown.");
|
|
771
|
+
for (const reason of report.skipped)
|
|
772
|
+
lines.push(`Not opened: ${reason}.`);
|
|
773
|
+
lines.push("");
|
|
774
|
+
for (const page of report.pages) {
|
|
775
|
+
const verdict = page.failed ? "FAIL" : page.domFindings.length || page.consoleWarnings.length ? "warn" : "ok";
|
|
776
|
+
const landed = new URL(page.finalUrl).pathname;
|
|
777
|
+
const moved = landed !== new URL(page.url).pathname ? ` -> ${landed}` : "";
|
|
778
|
+
const status = page.status === null ? "---" : String(page.status);
|
|
779
|
+
lines.push(`${verdict.padEnd(4)} ${page.path}${moved} ${status} "${page.title}" ${(page.ms / 1000).toFixed(1)}s`);
|
|
780
|
+
const items = [
|
|
781
|
+
["error", page.error ? [page.error] : []],
|
|
782
|
+
["page", page.pageErrors],
|
|
783
|
+
["client", page.clientReports],
|
|
784
|
+
["server", page.serverErrors],
|
|
785
|
+
["console", [...page.consoleErrors, ...page.consoleWarnings]],
|
|
786
|
+
["dom", page.domFindings],
|
|
787
|
+
[
|
|
788
|
+
"text",
|
|
789
|
+
page.text ? [JSON.stringify(page.text.length > 160 ? `${page.text.slice(0, 160)}...` : page.text)] : []
|
|
790
|
+
],
|
|
791
|
+
["screenshot", page.screenshot ? [page.screenshot] : []]
|
|
792
|
+
];
|
|
793
|
+
for (const [label, entries] of items)
|
|
794
|
+
for (const entry of entries)
|
|
795
|
+
lines.push(` ${label}: ${entry.split(`
|
|
796
|
+
`).join(`
|
|
797
|
+
`)}`);
|
|
798
|
+
}
|
|
799
|
+
const failed = report.pages.filter((page) => page.failed).length;
|
|
800
|
+
lines.push("", failed ? `${failed} of ${report.pages.length} page(s) failed.` : `${report.pages.length} page(s) rendered.`);
|
|
801
|
+
return lines.join(`
|
|
802
|
+
`);
|
|
803
|
+
}
|
|
804
|
+
static async#probe(origin, pagePath, {
|
|
805
|
+
engine,
|
|
806
|
+
viewport,
|
|
807
|
+
screenshot,
|
|
808
|
+
timeoutMs
|
|
809
|
+
}) {
|
|
810
|
+
const url = new URL(pagePath, origin).toString();
|
|
811
|
+
const at = Date.now();
|
|
812
|
+
const page = {
|
|
813
|
+
path: pagePath,
|
|
814
|
+
url,
|
|
815
|
+
finalUrl: url,
|
|
816
|
+
status: null,
|
|
817
|
+
title: "",
|
|
818
|
+
text: "",
|
|
819
|
+
ms: 0,
|
|
820
|
+
failed: true,
|
|
821
|
+
error: null,
|
|
822
|
+
pageErrors: [],
|
|
823
|
+
clientReports: [],
|
|
824
|
+
serverErrors: [],
|
|
825
|
+
consoleErrors: [],
|
|
826
|
+
consoleWarnings: [],
|
|
827
|
+
domFindings: [],
|
|
828
|
+
screenshot: null
|
|
829
|
+
};
|
|
830
|
+
try {
|
|
831
|
+
const probe = await PreviewView2.probe(url, {
|
|
832
|
+
engine,
|
|
833
|
+
...viewport,
|
|
834
|
+
screenshot: !!screenshot,
|
|
835
|
+
timeoutMs,
|
|
836
|
+
settleMs: AppPreview.settleMs
|
|
837
|
+
});
|
|
838
|
+
Object.assign(page, {
|
|
839
|
+
finalUrl: probe.finalUrl,
|
|
840
|
+
status: probe.status,
|
|
841
|
+
title: probe.title,
|
|
842
|
+
text: probe.text,
|
|
843
|
+
pageErrors: probe.pageErrors,
|
|
844
|
+
consoleErrors: probe.consoleErrors,
|
|
845
|
+
consoleWarnings: probe.consoleWarnings,
|
|
846
|
+
domFindings: probe.domFindings
|
|
847
|
+
});
|
|
848
|
+
if (screenshot && probe.screenshot) {
|
|
849
|
+
await mkdir2(path2.dirname(screenshot), { recursive: true });
|
|
850
|
+
await Bun.write(screenshot, Buffer.from(probe.screenshot, "base64"));
|
|
851
|
+
page.screenshot = screenshot;
|
|
852
|
+
}
|
|
853
|
+
page.failed = page.status !== null && page.status >= 400 || page.pageErrors.length > 0 || page.consoleErrors.length > 0;
|
|
854
|
+
} catch (error) {
|
|
855
|
+
page.error = error instanceof Error ? error.message : String(error);
|
|
856
|
+
}
|
|
857
|
+
page.ms = Date.now() - at;
|
|
858
|
+
return page;
|
|
859
|
+
}
|
|
860
|
+
static async#changedPages(app) {
|
|
861
|
+
const root = app.workspace.workspaceRoot;
|
|
862
|
+
const changes = await VerifyScope.changesIn(root) ?? [];
|
|
863
|
+
const files = changes.filter((change) => !change.code.includes("D")).map((change) => path2.join(root, change.file));
|
|
864
|
+
return AppPreview.changedPages(await app.getRouteSources(), files);
|
|
865
|
+
}
|
|
866
|
+
static async#tail(app, records) {
|
|
867
|
+
const { LogTailClient } = await import("akanjs/server/logging/logTailClient");
|
|
868
|
+
const socketPath = LogTailClient.socketPath(ApplicationRunner.runtimeDirOf(app));
|
|
869
|
+
try {
|
|
870
|
+
const client = await LogTailClient.connect(socketPath, { onRecord: (entry) => void records.push(entry.record) });
|
|
871
|
+
await client.subscribe({ level: "error" });
|
|
872
|
+
return client;
|
|
873
|
+
} catch {
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
static async#startServer(app, port, previewDir) {
|
|
878
|
+
await mkdir2(previewDir, { recursive: true });
|
|
879
|
+
const logPath = path2.join(previewDir, "server.log");
|
|
880
|
+
const { promise: settled, resolve: settle } = Promise.withResolvers();
|
|
881
|
+
const fd = openSync(logPath, "w");
|
|
882
|
+
try {
|
|
883
|
+
const proc = Bun.spawn([process.execPath, Bun.main, "start", app.name, "--plain"], {
|
|
884
|
+
cwd: app.workspace.workspaceRoot,
|
|
885
|
+
env: { ...process.env, AKAN_DEV_PORT: String(port), [DevSupervisor.supervisedEnvKey]: "1" },
|
|
886
|
+
stdio: ["ignore", fd, fd],
|
|
887
|
+
detached: true,
|
|
888
|
+
ipc: (message) => {
|
|
889
|
+
if (!message || typeof message !== "object")
|
|
890
|
+
return;
|
|
891
|
+
if ("booted" in message)
|
|
892
|
+
settle({ state: "booted" });
|
|
893
|
+
else if (message.state === "failed")
|
|
894
|
+
settle({ state: "failed", ...message.detail ? { detail: message.detail } : {} });
|
|
895
|
+
},
|
|
896
|
+
serialization: "advanced",
|
|
897
|
+
onExit: (_proc, exitCode) => settle({ state: "exited", detail: `exit code ${exitCode}` })
|
|
898
|
+
});
|
|
899
|
+
return { proc, logPath, settled };
|
|
900
|
+
} finally {
|
|
901
|
+
closeSync(fd);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
static async#waitBooted({ settled, logPath }) {
|
|
905
|
+
const { state, detail } = await AppPreview.#raceTimer(settled, DevSupervisor.bootTimeoutMs, {
|
|
906
|
+
state: "timeout",
|
|
907
|
+
detail: undefined
|
|
908
|
+
});
|
|
909
|
+
if (state === "booted")
|
|
910
|
+
return;
|
|
911
|
+
const what = {
|
|
912
|
+
failed: "failed to boot",
|
|
913
|
+
exited: "exited before it booted",
|
|
914
|
+
timeout: `did not boot within ${DevSupervisor.bootTimeoutMs / 1000}s`
|
|
915
|
+
}[state];
|
|
916
|
+
throw new Error(`The dev server this preview started ${what}${detail ? ` (${detail})` : ""}; see ${logPath}`);
|
|
917
|
+
}
|
|
918
|
+
static stopArgvOf(pid, platform = process.platform) {
|
|
919
|
+
return platform === "win32" ? ["taskkill", "/PID", String(pid), "/T", "/F"] : ["kill", "-INT", `-${pid}`];
|
|
920
|
+
}
|
|
921
|
+
static async#stopServer(proc) {
|
|
922
|
+
if (proc.exitCode !== null)
|
|
923
|
+
return;
|
|
924
|
+
if (process.platform === "win32") {
|
|
925
|
+
await HostProcessProbe.run(AppPreview.stopArgvOf(proc.pid));
|
|
926
|
+
await AppPreview.#raceTimer(proc.exited, AppPreview.stopGraceMs, null);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
const signal = (name) => {
|
|
930
|
+
try {
|
|
931
|
+
process.kill(-proc.pid, name);
|
|
932
|
+
} catch {}
|
|
933
|
+
};
|
|
934
|
+
signal("SIGINT");
|
|
935
|
+
const exited = await AppPreview.#raceTimer(proc.exited.then(() => true), AppPreview.stopGraceMs, false);
|
|
936
|
+
if (!exited)
|
|
937
|
+
signal("SIGKILL");
|
|
938
|
+
}
|
|
939
|
+
static async#raceTimer(work, ms, fallback) {
|
|
940
|
+
let timer;
|
|
941
|
+
const expired = new Promise((resolve) => {
|
|
942
|
+
timer = setTimeout(() => resolve(fallback), ms);
|
|
943
|
+
});
|
|
944
|
+
try {
|
|
945
|
+
return await Promise.race([work, expired]);
|
|
946
|
+
} finally {
|
|
947
|
+
clearTimeout(timer);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
static #firstLines(text, count = 6) {
|
|
951
|
+
return text.split(`
|
|
952
|
+
`).slice(0, count).join(`
|
|
953
|
+
`).slice(0, 2000);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// pkgs/@akanjs/cli/application/devPortReclaimer.ts
|
|
958
|
+
class DevPortReclaimer {
|
|
959
|
+
static releaseTimeoutMs = 8000;
|
|
960
|
+
static maxAncestorDepth = 8;
|
|
961
|
+
static #releasePollMs = 100;
|
|
962
|
+
static wsPortOffset = 1e4;
|
|
963
|
+
static portsFor(ports) {
|
|
964
|
+
return [...new Set(ports.flatMap((port) => [port, port + DevPortReclaimer.wsPortOffset]))].sort((left, right) => left - right);
|
|
965
|
+
}
|
|
966
|
+
static isAkanCommand(command) {
|
|
967
|
+
const normalized = command.replaceAll("\\", "/");
|
|
968
|
+
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");
|
|
969
|
+
}
|
|
970
|
+
#probe;
|
|
971
|
+
constructor(probe = new HostProcessProbe) {
|
|
972
|
+
this.#probe = probe;
|
|
973
|
+
}
|
|
974
|
+
async reclaim(ports) {
|
|
975
|
+
const killed = [];
|
|
976
|
+
const foreign = [];
|
|
977
|
+
const seen = new Set;
|
|
978
|
+
for (const port of DevPortReclaimer.portsFor(ports)) {
|
|
979
|
+
for (const holder of await this.holdersOf(port)) {
|
|
980
|
+
if (seen.has(holder.pid))
|
|
981
|
+
continue;
|
|
982
|
+
seen.add(holder.pid);
|
|
983
|
+
if (!holder.akan) {
|
|
984
|
+
foreign.push(holder);
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
if (await this.#terminate(holder.pid))
|
|
988
|
+
killed.push(holder);
|
|
989
|
+
else
|
|
990
|
+
foreign.push(holder);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
return { killed, foreign };
|
|
994
|
+
}
|
|
995
|
+
async holdersOf(port) {
|
|
996
|
+
const holders = [];
|
|
997
|
+
for (const listenerPid of await this.#probe.listenersOn(port)) {
|
|
998
|
+
if (listenerPid === process.pid || listenerPid === process.ppid)
|
|
999
|
+
continue;
|
|
1000
|
+
const command = await this.#probe.commandOf(listenerPid);
|
|
1001
|
+
if (!command)
|
|
1002
|
+
continue;
|
|
1003
|
+
if (!DevPortReclaimer.isAkanCommand(command)) {
|
|
1004
|
+
holders.push({ pid: listenerPid, command, port, listenerPid, akan: false });
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
const root = await this.#akanRootOf(listenerPid, command);
|
|
1008
|
+
holders.push({ pid: root.pid, command: root.command, port, listenerPid, akan: true });
|
|
1009
|
+
}
|
|
1010
|
+
return holders;
|
|
1011
|
+
}
|
|
1012
|
+
async#akanRootOf(pid, command) {
|
|
1013
|
+
let root = { pid, command };
|
|
1014
|
+
for (let depth = 0;depth < DevPortReclaimer.maxAncestorDepth; depth += 1) {
|
|
1015
|
+
const parentPid = await this.#probe.parentOf(root.pid);
|
|
1016
|
+
if (parentPid === null || parentPid <= 1 || parentPid === process.pid || parentPid === process.ppid)
|
|
1017
|
+
break;
|
|
1018
|
+
const parentCommand = await this.#probe.commandOf(parentPid);
|
|
1019
|
+
if (!parentCommand || !DevPortReclaimer.isAkanCommand(parentCommand))
|
|
1020
|
+
break;
|
|
1021
|
+
root = { pid: parentPid, command: parentCommand };
|
|
1022
|
+
}
|
|
1023
|
+
return root;
|
|
1024
|
+
}
|
|
1025
|
+
async#terminate(pid) {
|
|
1026
|
+
if (this.#probe.platform === "win32") {
|
|
1027
|
+
await HostProcessProbe.run(["taskkill", "/PID", String(pid), "/T", "/F"]);
|
|
1028
|
+
return await this.#released(pid);
|
|
1029
|
+
}
|
|
1030
|
+
if (!this.#signal(pid, "SIGTERM"))
|
|
1031
|
+
return !this.#alive(pid);
|
|
1032
|
+
if (await this.#released(pid))
|
|
1033
|
+
return true;
|
|
1034
|
+
this.#signal(pid, "SIGKILL");
|
|
1035
|
+
await Bun.sleep(DevPortReclaimer.#releasePollMs);
|
|
1036
|
+
return !this.#alive(pid);
|
|
1037
|
+
}
|
|
1038
|
+
async#released(pid) {
|
|
1039
|
+
const deadline = Date.now() + DevPortReclaimer.releaseTimeoutMs;
|
|
1040
|
+
while (Date.now() < deadline) {
|
|
1041
|
+
if (!this.#alive(pid))
|
|
1042
|
+
return true;
|
|
1043
|
+
await Bun.sleep(DevPortReclaimer.#releasePollMs);
|
|
1044
|
+
}
|
|
1045
|
+
return false;
|
|
1046
|
+
}
|
|
1047
|
+
#signal(pid, signal) {
|
|
1048
|
+
try {
|
|
1049
|
+
process.kill(pid, signal);
|
|
1050
|
+
return true;
|
|
1051
|
+
} catch {
|
|
1052
|
+
return false;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
#alive(pid) {
|
|
1056
|
+
try {
|
|
1057
|
+
process.kill(pid, 0);
|
|
1058
|
+
return true;
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
return error.code === "EPERM";
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// pkgs/@akanjs/cli/application/devStreamView.ts
|
|
1066
|
+
import { Logger } from "akanjs/common";
|
|
1067
|
+
import chalk from "chalk";
|
|
1068
|
+
var appColors = ["cyan", "magenta", "yellow", "green", "blue", "red"];
|
|
1069
|
+
|
|
1070
|
+
class DevStreamView {
|
|
1071
|
+
#logger = new Logger("akan start");
|
|
1072
|
+
#partial = new Map;
|
|
1073
|
+
#lastState = new Map;
|
|
1074
|
+
#color = new Map;
|
|
1075
|
+
#width = 0;
|
|
1076
|
+
constructor(appNames) {
|
|
1077
|
+
this.#width = appNames.reduce((max, name) => Math.max(max, name.length), 0);
|
|
1078
|
+
appNames.forEach((name, idx) => {
|
|
1079
|
+
this.#color.set(name, appColors[idx % appColors.length] ?? "cyan");
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
onOutput = (app, kind, text) => {
|
|
1083
|
+
const key = `${app}:${kind}`;
|
|
1084
|
+
const pending = `${this.#partial.get(key) ?? ""}${text}`;
|
|
1085
|
+
const lines = pending.split(`
|
|
1086
|
+
`);
|
|
1087
|
+
this.#partial.set(key, lines.pop() ?? "");
|
|
1088
|
+
if (lines.length === 0)
|
|
1089
|
+
return;
|
|
1090
|
+
const prefixed = lines.map((line) => `${this.#prefix(app)}${line}`).join(`
|
|
1091
|
+
`);
|
|
1092
|
+
(kind === "stderr" ? process.stderr : process.stdout).write(`${prefixed}
|
|
1093
|
+
`);
|
|
1094
|
+
};
|
|
1095
|
+
onStatus = (statuses) => {
|
|
1096
|
+
for (const status of statuses) {
|
|
1097
|
+
if (this.#lastState.get(status.name) === status.state)
|
|
1098
|
+
continue;
|
|
1099
|
+
this.#lastState.set(status.name, status.state);
|
|
1100
|
+
const detail = status.detail ? ` (${status.detail})` : "";
|
|
1101
|
+
const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
|
|
1102
|
+
const line = `${status.name} ${status.state}${detail}${where}`;
|
|
1103
|
+
if (status.state === "failed")
|
|
1104
|
+
this.#logger.error(line);
|
|
1105
|
+
else if (status.state === "stopped")
|
|
1106
|
+
this.#logger.warn(line);
|
|
1107
|
+
else
|
|
1108
|
+
this.#logger.info(line);
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
onNote = (text, level) => {
|
|
1112
|
+
if (level === "warn")
|
|
1113
|
+
this.#logger.warn(text);
|
|
1114
|
+
else
|
|
1115
|
+
this.#logger.info(text);
|
|
1116
|
+
};
|
|
1117
|
+
waitForExit = () => new Promise(() => {
|
|
1118
|
+
return;
|
|
1119
|
+
});
|
|
1120
|
+
close = () => {
|
|
1121
|
+
for (const [key, remainder] of this.#partial) {
|
|
1122
|
+
if (!remainder)
|
|
1123
|
+
continue;
|
|
1124
|
+
const app = key.slice(0, key.lastIndexOf(":"));
|
|
1125
|
+
process.stdout.write(`${this.#prefix(app)}${remainder}
|
|
1126
|
+
`);
|
|
1127
|
+
}
|
|
1128
|
+
this.#partial.clear();
|
|
1129
|
+
};
|
|
1130
|
+
#prefix(app) {
|
|
1131
|
+
const color = this.#color.get(app) ?? "cyan";
|
|
1132
|
+
return `${chalk[color](app.padEnd(this.#width))} ${chalk.dim("\u2502")} `;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// pkgs/@akanjs/cli/application/interruptTeardown.ts
|
|
1137
|
+
import { Logger as Logger2 } from "akanjs/common";
|
|
1138
|
+
|
|
1139
|
+
class InterruptTeardown {
|
|
1140
|
+
#teardowns = [];
|
|
1141
|
+
#exit;
|
|
1142
|
+
#listen;
|
|
1143
|
+
#report;
|
|
1144
|
+
#interrupted = false;
|
|
1145
|
+
#chain = Promise.resolve();
|
|
1146
|
+
ownsExit = true;
|
|
1147
|
+
constructor({ exit, listen, report } = {}) {
|
|
1148
|
+
this.#exit = exit ?? ((code) => process.exit(code));
|
|
1149
|
+
this.#listen = listen ?? ((onSignal) => {
|
|
1150
|
+
process.on("SIGINT", onSignal);
|
|
1151
|
+
});
|
|
1152
|
+
this.#report = report ?? ((message) => Logger2.rawLog(message, undefined, "error"));
|
|
1153
|
+
}
|
|
1154
|
+
add(run, abandoned, exitCode = 0) {
|
|
1155
|
+
this.#teardowns.push({ run, abandoned, exitCode, state: "pending" });
|
|
1156
|
+
if (this.#teardowns.length === 1)
|
|
1157
|
+
this.#listen(() => this.#onSignal());
|
|
1158
|
+
}
|
|
1159
|
+
async runAll() {
|
|
1160
|
+
await this.#runTeardowns();
|
|
1161
|
+
}
|
|
1162
|
+
#onSignal() {
|
|
1163
|
+
if (this.#interrupted) {
|
|
1164
|
+
for (const one of this.#teardowns)
|
|
1165
|
+
if (one.state !== "done")
|
|
1166
|
+
this.#report(one.abandoned);
|
|
1167
|
+
this.#exit(130);
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
this.#interrupted = true;
|
|
1171
|
+
this.#runTeardowns().finally(() => {
|
|
1172
|
+
if (this.ownsExit)
|
|
1173
|
+
this.#exit(Math.max(0, ...this.#teardowns.map((one) => one.exitCode)));
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
async#runTeardowns() {
|
|
1177
|
+
this.#chain = this.#chain.then(async () => {
|
|
1178
|
+
for (const one of this.#teardowns.toReversed()) {
|
|
1179
|
+
if (one.state !== "pending")
|
|
1180
|
+
continue;
|
|
1181
|
+
one.state = "running";
|
|
1182
|
+
await one.run().catch(() => {
|
|
1183
|
+
return;
|
|
1184
|
+
});
|
|
1185
|
+
one.state = "done";
|
|
1186
|
+
}
|
|
1187
|
+
});
|
|
1188
|
+
await this.#chain;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// pkgs/@akanjs/cli/application/application.script.ts
|
|
1193
|
+
class ApplicationScript extends script("application", [ApplicationRunner, LibraryScript]) {
|
|
1194
|
+
static dbShutdownTimeoutMs = 20000;
|
|
1195
|
+
static devServerReadyTimeoutMs = DevSupervisor.bootTimeoutMs;
|
|
1196
|
+
#interrupt = new InterruptTeardown;
|
|
1197
|
+
async confirmDatabaseModeDependencyInstall(databaseMode, installSpecs) {
|
|
1198
|
+
assertPromptable(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}`, {
|
|
1199
|
+
remedy: `install them first with \`bun add ${installSpecs.join(" ")}\``
|
|
1200
|
+
});
|
|
1201
|
+
return await confirm({
|
|
1202
|
+
message: `Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}. Install them now?`,
|
|
1203
|
+
default: true
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
async syncDatabaseModeDependencies(app, akanConfig, databaseMode) {
|
|
1207
|
+
const installSpecs = akanConfig.getMissingDatabaseModeDependencySpecs(databaseMode);
|
|
1208
|
+
if (installSpecs.length === 0)
|
|
1209
|
+
return;
|
|
1210
|
+
const shouldInstall = await this.confirmDatabaseModeDependencyInstall(databaseMode, installSpecs);
|
|
1211
|
+
if (!shouldInstall)
|
|
1212
|
+
throw new Error(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}.`);
|
|
1213
|
+
await this.#addDependencies(app, installSpecs, `database dependencies for ${databaseMode} mode`);
|
|
1214
|
+
}
|
|
1215
|
+
async#addDependencies(app, installSpecs, what) {
|
|
1216
|
+
const spinner = app.workspace.spinning(`Installing ${what}...`);
|
|
1217
|
+
try {
|
|
1218
|
+
await app.workspace.spawn("bun", ["add", ...installSpecs], { stdio: "inherit" });
|
|
1219
|
+
await app.workspace.getPackageJson({ refresh: true });
|
|
1220
|
+
spinner.succeed(`Installed ${what}`);
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
spinner.fail(`Failed to install ${what}`);
|
|
1223
|
+
throw error;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
async createApplication(appName, workspace, { start = false, libs = [], sample = false } = {}) {
|
|
1227
|
+
const spinner = workspace.spinning("Creating application...");
|
|
1228
|
+
const app = await this.applicationRunner.createApplication(appName, workspace, libs, { sample });
|
|
1229
|
+
spinner.succeed(`Application created in apps/${app.name}`);
|
|
1230
|
+
await app.scanSync();
|
|
1231
|
+
if (start)
|
|
1232
|
+
await this.startOne(app, { open: true });
|
|
1233
|
+
}
|
|
1234
|
+
async removeApplication(app) {
|
|
1235
|
+
const spinner = app.spinning("Removing application...");
|
|
1236
|
+
await this.applicationRunner.removeApplication(app);
|
|
1237
|
+
spinner.succeed(`Application ${app.name} (apps/${app.name}) removed`);
|
|
1238
|
+
}
|
|
1239
|
+
async planSlice(app, format = "text") {
|
|
1240
|
+
const spinner = app.spinning("Planning distributable slice...");
|
|
1241
|
+
const plan = await this.applicationRunner.planSlice(app);
|
|
1242
|
+
spinner.succeed(`Slice planned (${plan.libs.length} libs, ${plan.warnings.length} warnings)`);
|
|
1243
|
+
Logger3.rawLog(format === "json" ? JSON.stringify(plan, null, 2) : formatSlicePlan(plan));
|
|
1244
|
+
}
|
|
1245
|
+
async sync(sys) {
|
|
1246
|
+
if (sys.type === "app")
|
|
1247
|
+
await sys.scanSync();
|
|
1248
|
+
else
|
|
1249
|
+
await this.libraryScript.syncLibrary(sys);
|
|
1250
|
+
}
|
|
1251
|
+
async script(app, filename) {
|
|
1252
|
+
const scriptFilename = filename ?? await this.applicationRunner.getScriptFilename(app);
|
|
1253
|
+
await app.scanSync();
|
|
1254
|
+
await this.applicationRunner.runScript(app, scriptFilename);
|
|
1255
|
+
}
|
|
1256
|
+
async console(app) {
|
|
1257
|
+
await app.scanSync();
|
|
1258
|
+
await this.applicationRunner.runConsole(app);
|
|
1259
|
+
}
|
|
1260
|
+
async migrate(app, argv) {
|
|
1261
|
+
await app.scanSync();
|
|
1262
|
+
await this.applicationRunner.migrate(app, argv);
|
|
1263
|
+
}
|
|
1264
|
+
async createMigration(app, migrationName) {
|
|
1265
|
+
const migrationId = await this.applicationRunner.createMigration(app, migrationName);
|
|
1266
|
+
Logger3.rawLog(`Created apps/${app.name}/script/migration/${migrationId}.ts; plan it with \`akan migrate ${app.name} plan ${migrationId}\``);
|
|
1267
|
+
}
|
|
1268
|
+
async logs(app, options) {
|
|
1269
|
+
await this.applicationRunner.runLogs(app, options);
|
|
1270
|
+
}
|
|
1271
|
+
async preview(app, { format = "text", ...options }) {
|
|
1272
|
+
const report = await AppPreview.run(app, options);
|
|
1273
|
+
Logger3.rawLog(format === "json" ? JSON.stringify(report, null, 2) : AppPreview.render(report));
|
|
1274
|
+
if (!report.pages.some((page) => page.failed))
|
|
1275
|
+
return;
|
|
1276
|
+
const failure = new ExitCodeError("preview found broken pages", 1);
|
|
1277
|
+
markCliErrorPrinted(failure);
|
|
1278
|
+
throw failure;
|
|
1279
|
+
}
|
|
1280
|
+
async build(app, {
|
|
1281
|
+
write = true,
|
|
1282
|
+
fast = false,
|
|
1283
|
+
quiet = false,
|
|
1284
|
+
profile
|
|
1285
|
+
} = {}) {
|
|
1286
|
+
await app.scanSync({ write });
|
|
1287
|
+
if (!quiet)
|
|
1288
|
+
Logger3.rawLog(`Creating an optimized production build for ${app.name}...`);
|
|
1289
|
+
try {
|
|
1290
|
+
const result = await this.applicationRunner.build(app, { fast, spinner: !quiet, envProfile: profile });
|
|
1291
|
+
Logger3.rawLog(`${app.name} built in dist/apps/${app.name}`);
|
|
1292
|
+
if (!quiet)
|
|
1293
|
+
ApplicationBuildReporter.printSummary(result);
|
|
1294
|
+
} catch (error) {
|
|
1295
|
+
Logger3.rawLog(`${app.name} build failed in dist/apps/${app.name}`, undefined, "error");
|
|
1296
|
+
Logger3.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
|
|
1297
|
+
markCliErrorPrinted(error);
|
|
1298
|
+
throw error;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
async typecheck(exec, { write = true, clean = false, incremental = true, tests = false } = {}) {
|
|
1302
|
+
if (!(exec instanceof AppExecutor) && !(exec instanceof LibExecutor))
|
|
1303
|
+
throw new Error(`akan typecheck takes an app or a library; ${exec.name} is a package, checked by its own tsconfig.`);
|
|
1304
|
+
if (exec instanceof AppExecutor)
|
|
1305
|
+
await exec.scanSync({ write });
|
|
1306
|
+
else if (write)
|
|
1307
|
+
await this.libraryScript.syncLibrary(exec);
|
|
1308
|
+
else
|
|
1309
|
+
await exec.scan({ write: false });
|
|
1310
|
+
const spinner = exec.spinning(`Typechecking ${exec.name}${tests ? " with its tests" : ""}...`);
|
|
1311
|
+
try {
|
|
1312
|
+
if (exec instanceof LibExecutor)
|
|
1313
|
+
await this.applicationRunner.typecheckLibrary(exec, { clean, incremental, tests });
|
|
1314
|
+
else
|
|
1315
|
+
await this.applicationRunner.typecheck(exec, { clean, incremental, tests });
|
|
1316
|
+
spinner.succeed(`${exec.name} typechecked`);
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
spinner.fail(`${exec.name} typecheck failed`);
|
|
1319
|
+
Logger3.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
|
|
1320
|
+
markCliErrorPrinted(error);
|
|
1321
|
+
throw error;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async test(exec, { write = true, files = [] } = {}) {
|
|
1325
|
+
const testPaths = this.applicationRunner.resolveTestPaths(exec, files);
|
|
1326
|
+
if (exec instanceof LibExecutor) {
|
|
1327
|
+
if (write)
|
|
1328
|
+
await this.libraryScript.syncLibrary(exec);
|
|
1329
|
+
else
|
|
1330
|
+
await exec.scan({ write: false });
|
|
1331
|
+
exec.spinning(`Preparing ${exec.name}...`).succeed(`${exec.name} prepared`);
|
|
1332
|
+
await this.applicationRunner.test(exec, testPaths);
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
const spinner = exec.spinning(`Preparing ${exec.name}...`);
|
|
1336
|
+
try {
|
|
1337
|
+
if (exec instanceof PkgExecutor)
|
|
1338
|
+
await exec.scan({ refresh: true });
|
|
1339
|
+
else
|
|
1340
|
+
await exec.scanSync({ write });
|
|
1341
|
+
spinner.succeed(`${exec.name} prepared`);
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
spinner.fail(`${exec.name} prepare failed`);
|
|
1344
|
+
throw error;
|
|
1345
|
+
}
|
|
1346
|
+
await this.applicationRunner.test(exec, testPaths);
|
|
1347
|
+
}
|
|
1348
|
+
async start(apps, {
|
|
1349
|
+
open = false,
|
|
1350
|
+
dbup = true,
|
|
1351
|
+
write = true,
|
|
1352
|
+
plain = false,
|
|
1353
|
+
kill = false,
|
|
1354
|
+
share = false,
|
|
1355
|
+
concurrency = null
|
|
1356
|
+
} = {}) {
|
|
1357
|
+
const first = apps[0];
|
|
1358
|
+
if (!first)
|
|
1359
|
+
throw new Error("No app selected to start");
|
|
1360
|
+
const { mode, downgraded } = DevSupervisor.resolveDevUi(plain);
|
|
1361
|
+
if (downgraded)
|
|
1362
|
+
first.workspace.log("no sized terminal to draw on; printing prefixed lines instead");
|
|
1363
|
+
if (kill)
|
|
1364
|
+
await this.reclaimDevPorts(apps);
|
|
1365
|
+
const shares = share ? await this.#shareOnInterrupt(apps) : null;
|
|
1366
|
+
if (mode === "stream" && apps.length === 1)
|
|
1367
|
+
return await this.startOne(first, { open, dbup, write, ...DevSupervisor.childHooks() });
|
|
1368
|
+
this.#interrupt.ownsExit = false;
|
|
1369
|
+
await this.#startMany(apps, { open, dbup, write, mode, concurrency, shares });
|
|
1370
|
+
}
|
|
1371
|
+
async startOne(app, { open = false, dbup = true, stdio = "inherit", write = true, onDevEvent } = {}) {
|
|
1372
|
+
await app.scanSync({ write });
|
|
1373
|
+
const akanConfig = await app.getConfig();
|
|
1374
|
+
const databaseMode = akanConfig.resolveDatabaseMode();
|
|
1375
|
+
await this.syncDatabaseModeDependencies(app, akanConfig, databaseMode);
|
|
1376
|
+
if (app.getEnv() === "local" && dbup && databaseMode !== "single") {
|
|
1377
|
+
const wasDbAlreadyUp = await this.dbup(app.workspace, databaseMode);
|
|
1378
|
+
if (!wasDbAlreadyUp)
|
|
1379
|
+
this.#stopDatabaseOnInterrupt(app.workspace);
|
|
1380
|
+
}
|
|
1381
|
+
const spinner = app.spinning("Preparing backend...");
|
|
1382
|
+
return await this.applicationRunner.start(app, {
|
|
1383
|
+
open,
|
|
1384
|
+
onStart: () => spinner.succeed(`${app.name} prepared, ready to start`),
|
|
1385
|
+
onDevEvent,
|
|
1386
|
+
stdio
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
async reclaimDevPorts(apps) {
|
|
1390
|
+
const workspace = apps[0]?.workspace;
|
|
1391
|
+
if (!workspace)
|
|
1392
|
+
return;
|
|
1393
|
+
const ports = await Promise.all(apps.map(async (app) => await app.getDevPort()));
|
|
1394
|
+
const { killed, foreign } = await new DevPortReclaimer().reclaim(ports);
|
|
1395
|
+
for (const holder of killed)
|
|
1396
|
+
workspace.log(`freed port ${holder.port} \u2014 killed pid ${holder.pid} (${holder.command})`);
|
|
1397
|
+
for (const holder of foreign)
|
|
1398
|
+
Logger3.rawLog(`port ${holder.port} is held by pid ${holder.pid} and was left alone: ${holder.command}`, undefined, "error");
|
|
1399
|
+
if (killed.length === 0 && foreign.length === 0)
|
|
1400
|
+
workspace.log("dev ports are free; nothing to kill");
|
|
1401
|
+
}
|
|
1402
|
+
async#startMany(apps, {
|
|
1403
|
+
open,
|
|
1404
|
+
dbup,
|
|
1405
|
+
write,
|
|
1406
|
+
mode,
|
|
1407
|
+
concurrency,
|
|
1408
|
+
shares
|
|
1409
|
+
}) {
|
|
1410
|
+
const workspace = apps[0]?.workspace;
|
|
1411
|
+
if (!workspace)
|
|
1412
|
+
throw new Error("No app selected to start");
|
|
1413
|
+
const startedDatabase = dbup ? await this.#prepareSharedDatabase(apps) : false;
|
|
1414
|
+
const supervisor = new DevSupervisor({ apps, mode, concurrency, open, write, shares });
|
|
1415
|
+
const view = mode === "tui" ? new (await import("./devTui-evr3b35y.js")).DevTui(supervisor) : new DevStreamView(apps.map((app) => app.name));
|
|
1416
|
+
await supervisor.run(view);
|
|
1417
|
+
if (startedDatabase)
|
|
1418
|
+
await this.#stopDatabase(workspace);
|
|
1419
|
+
}
|
|
1420
|
+
async#prepareSharedDatabase(apps) {
|
|
1421
|
+
const workspace = apps[0]?.workspace;
|
|
1422
|
+
if (!workspace)
|
|
1423
|
+
return false;
|
|
1424
|
+
const modes = new Set;
|
|
1425
|
+
for (const app of apps) {
|
|
1426
|
+
if (app.getEnv() !== "local")
|
|
1427
|
+
continue;
|
|
1428
|
+
const akanConfig = await app.getConfig();
|
|
1429
|
+
const mode = akanConfig.resolveDatabaseMode();
|
|
1430
|
+
await this.syncDatabaseModeDependencies(app, akanConfig, mode);
|
|
1431
|
+
if (mode !== "single")
|
|
1432
|
+
modes.add(mode);
|
|
1433
|
+
}
|
|
1434
|
+
let started = false;
|
|
1435
|
+
for (const mode of modes)
|
|
1436
|
+
if (!await this.dbup(workspace, mode))
|
|
1437
|
+
started = true;
|
|
1438
|
+
return started;
|
|
1439
|
+
}
|
|
1440
|
+
async buildIos(app, { write = true, ...options } = {}) {
|
|
1441
|
+
await app.scanSync({ write });
|
|
1442
|
+
await this.applicationRunner.buildMobile(app, "ios", options);
|
|
1443
|
+
}
|
|
1444
|
+
async buildAndroid(app, { write = true, ...options } = {}) {
|
|
1445
|
+
await app.scanSync({ write });
|
|
1446
|
+
await this.applicationRunner.buildMobile(app, "android", options);
|
|
1447
|
+
}
|
|
1448
|
+
async buildDesktop(app, { write = true, ...options } = {}) {
|
|
1449
|
+
await app.scanSync({ write });
|
|
1450
|
+
await this.applicationRunner.buildDesktop(app, options);
|
|
1451
|
+
}
|
|
1452
|
+
async startIos(app, { write = true, ...options } = {}) {
|
|
1453
|
+
await app.scanSync({ write });
|
|
1454
|
+
await this.applicationRunner.startMobile(app, "ios", options);
|
|
1455
|
+
}
|
|
1456
|
+
async startAndroid(app, { write = true, ...options } = {}) {
|
|
1457
|
+
await app.scanSync({ write });
|
|
1458
|
+
await this.applicationRunner.startMobile(app, "android", options);
|
|
1459
|
+
}
|
|
1460
|
+
async startDesktop(app, { write = true, ...options } = {}) {
|
|
1461
|
+
await app.scanSync({ write });
|
|
1462
|
+
if (options.operation === "release")
|
|
1463
|
+
return await this.applicationRunner.startDesktop(app, options);
|
|
1464
|
+
const mobileTarget = await ApplicationRunner.startTarget(app, undefined, options.target);
|
|
1465
|
+
if (!ApplicationRunner.carriesServer(mobileTarget))
|
|
1466
|
+
return await this.applicationRunner.startDesktop(app, options);
|
|
1467
|
+
DesktopServerStage.assertCarriable(await app.getConfig());
|
|
1468
|
+
const upstream = `http://localhost:${await app.getDevPort()}`;
|
|
1469
|
+
try {
|
|
1470
|
+
if (await ApplicationRunner.answers(upstream, app.name, app.workspace.workspaceRoot))
|
|
1471
|
+
app.log(`The desktop app follows the dev server on ${upstream}.`);
|
|
1472
|
+
else
|
|
1473
|
+
await this.#startDevServerFor(app, upstream);
|
|
1474
|
+
await this.applicationRunner.startDesktop(app, { ...options, interrupt: this.#interrupt });
|
|
1475
|
+
} finally {
|
|
1476
|
+
await this.#interrupt.runAll();
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
async#startDevServerFor(app, upstream) {
|
|
1480
|
+
app.log(`No dev server answers on ${upstream}; starting \`akan start ${app.name}\` for the desktop app.`);
|
|
1481
|
+
let settle = () => {};
|
|
1482
|
+
const settled = new Promise((resolve) => settle = resolve);
|
|
1483
|
+
const appHost = await this.startOne(app, {
|
|
1484
|
+
write: false,
|
|
1485
|
+
onDevEvent: (event) => {
|
|
1486
|
+
if ("state" in event && (event.state === "ready" || event.state === "failed"))
|
|
1487
|
+
settle(event.state);
|
|
1488
|
+
}
|
|
1489
|
+
});
|
|
1490
|
+
this.#interrupt.add(async () => {
|
|
1491
|
+
await appHost.stop();
|
|
1492
|
+
}, "Abandoning the dev server shutdown; its processes may still be running.", 130);
|
|
1493
|
+
let state;
|
|
1494
|
+
const timedOut = await DevSupervisor.timesOut(settled.then((settledState) => state = settledState), ApplicationScript.devServerReadyTimeoutMs);
|
|
1495
|
+
if (state === "ready")
|
|
1496
|
+
return;
|
|
1497
|
+
await this.#interrupt.runAll();
|
|
1498
|
+
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.`);
|
|
1499
|
+
}
|
|
1500
|
+
async releaseIos(app, {
|
|
1501
|
+
write = true,
|
|
1502
|
+
allowLocalRelease = false,
|
|
1503
|
+
...options
|
|
1504
|
+
} = {}) {
|
|
1505
|
+
await app.scanSync({ write });
|
|
1506
|
+
ApplicationScript.#assertReleaseEnv("releaseIos", options.env ?? "main", allowLocalRelease);
|
|
1507
|
+
await this.applicationRunner.releaseIos(app, options);
|
|
1508
|
+
}
|
|
1509
|
+
async releaseAndroid(app, format, {
|
|
1510
|
+
write = true,
|
|
1511
|
+
allowLocalRelease = false,
|
|
1512
|
+
...options
|
|
1513
|
+
} = {}) {
|
|
1514
|
+
await app.scanSync({ write });
|
|
1515
|
+
ApplicationScript.#assertReleaseEnv("releaseAndroid", options.env ?? "main", allowLocalRelease);
|
|
1516
|
+
await this.applicationRunner.releaseAndroid(app, format, options);
|
|
1517
|
+
}
|
|
1518
|
+
async packUpdate(app, platform, {
|
|
1519
|
+
write = true,
|
|
1520
|
+
allowLocalRelease = false,
|
|
1521
|
+
...options
|
|
1522
|
+
} = {}) {
|
|
1523
|
+
await app.scanSync({ write });
|
|
1524
|
+
ApplicationScript.#assertReleaseEnv("packUpdate", options.env ?? "main", allowLocalRelease);
|
|
1525
|
+
return await this.applicationRunner.packUpdate(app, platform, options);
|
|
1526
|
+
}
|
|
1527
|
+
async updateKeygen(app, platform, { target } = {}) {
|
|
1528
|
+
await this.applicationRunner.updateKeygen(app, platform, target);
|
|
1529
|
+
}
|
|
1530
|
+
async publishUpdate(app, platform, {
|
|
1531
|
+
write = true,
|
|
1532
|
+
allowLocalRelease = false,
|
|
1533
|
+
...options
|
|
1534
|
+
} = {}) {
|
|
1535
|
+
await app.scanSync({ write });
|
|
1536
|
+
ApplicationScript.#assertReleaseEnv("publishUpdate", options.env ?? "main", allowLocalRelease);
|
|
1537
|
+
await this.applicationRunner.publishUpdate(app, platform, options);
|
|
1538
|
+
}
|
|
1539
|
+
static #assertReleaseEnv(command, env, allowLocalRelease) {
|
|
1540
|
+
if (env === "local" && !allowLocalRelease)
|
|
1541
|
+
throw new Error(`${command} --env local is blocked. Pass allowLocalRelease only for explicit local release testing.`);
|
|
1542
|
+
}
|
|
1543
|
+
async transferDatabase(app, direction, dir) {
|
|
1544
|
+
await this.applicationRunner.transferDatabase(app, direction, dir);
|
|
1545
|
+
}
|
|
1546
|
+
async dbupDeclared(workspace, mode) {
|
|
1547
|
+
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())]);
|
|
1548
|
+
const needing = declared.filter((each) => each !== "single");
|
|
1549
|
+
if (!needing.length) {
|
|
1550
|
+
workspace.log("No app here declares a database mode that runs on local services; single needs none.");
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
for (const each of needing)
|
|
1554
|
+
await this.dbup(workspace, each);
|
|
1555
|
+
}
|
|
1556
|
+
async dbup(workspace, mode = "multiple") {
|
|
1557
|
+
const spinner = workspace.spinning(`Starting local database (${mode})...`);
|
|
1558
|
+
const wasAlreadyUp = await this.applicationRunner.dbup(workspace, mode);
|
|
1559
|
+
spinner.succeed(wasAlreadyUp ? `Local database (${mode}) was already up` : `Local database (${mode}) is up`);
|
|
1560
|
+
return wasAlreadyUp;
|
|
1561
|
+
}
|
|
1562
|
+
async dbdown(workspace) {
|
|
1563
|
+
const spinner = workspace.spinning("Stopping local database...");
|
|
1564
|
+
try {
|
|
1565
|
+
await this.applicationRunner.dbdown(workspace);
|
|
1566
|
+
} catch (error) {
|
|
1567
|
+
spinner.fail("Local database failed to stop");
|
|
1568
|
+
throw error;
|
|
1569
|
+
}
|
|
1570
|
+
spinner.succeed("Local database (/local/docker-compose.yaml) is down");
|
|
1571
|
+
}
|
|
1572
|
+
async#shareOnInterrupt(apps) {
|
|
1573
|
+
const shares = [];
|
|
1574
|
+
const urls = new Map;
|
|
1575
|
+
this.#interrupt.add(async () => {
|
|
1576
|
+
await Promise.all(shares.map(async (share) => await share.close()));
|
|
1577
|
+
}, "Abandoning the tunnel release; the shares expire on their own.");
|
|
1578
|
+
await Promise.all(apps.map(async (app) => {
|
|
1579
|
+
const { TunnelShare } = await import("./TunnelShare-xyjpa7gx.js");
|
|
1580
|
+
const share = await TunnelShare.open(app, { workspace: app.workspace });
|
|
1581
|
+
shares.push(share);
|
|
1582
|
+
urls.set(app.name, share.url);
|
|
1583
|
+
Logger3.rawLog(`${app.name} is shared at ${share.url}`);
|
|
1584
|
+
})).catch((error) => {
|
|
1585
|
+
Logger3.rawLog(`Could not open the tunnel: ${toError(error).message}`, undefined, "error");
|
|
1586
|
+
});
|
|
1587
|
+
return urls;
|
|
1588
|
+
}
|
|
1589
|
+
#stopDatabaseOnInterrupt(workspace) {
|
|
1590
|
+
this.#interrupt.add(async () => {
|
|
1591
|
+
await this.#stopDatabase(workspace);
|
|
1592
|
+
}, "Abandoning the local database teardown; containers are left running.");
|
|
1593
|
+
}
|
|
1594
|
+
async#stopDatabase(workspace) {
|
|
1595
|
+
const stopped = this.dbdown(workspace).catch(() => {
|
|
1596
|
+
return;
|
|
1597
|
+
});
|
|
1598
|
+
if (!await DevSupervisor.timesOut(stopped, ApplicationScript.dbShutdownTimeoutMs))
|
|
1599
|
+
return;
|
|
1600
|
+
Logger3.rawLog(`Local database did not stop within ${ApplicationScript.dbShutdownTimeoutMs}ms; run \`akan dbdown\` once Docker responds.`, undefined, "error");
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
export { ApplicationScript };
|