@morlay/zephyr-desktop-bundle 0.0.0-stage → 0.2.0-alpha.0
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/LICENSE +21 -0
- package/README.md +78 -2
- package/dist/index.d.mts +84 -0
- package/dist/index.mjs +571 -0
- package/dist/packager-2pDsExRM.mjs +526 -0
- package/dist/packager-MGm6zQRf.d.mts +130 -0
- package/dist/testing.d.mts +18 -0
- package/dist/testing.mjs +27 -0
- package/package.json +60 -3
- package/src/commands/bundle.ts +124 -0
- package/src/commands/desktop.ts +27 -0
- package/src/commands/dev.ts +291 -0
- package/src/desktop-dirs.ts +89 -0
- package/src/electron-builder.ts +101 -0
- package/src/icons.ts +96 -0
- package/src/index.ts +7 -0
- package/src/packager.ts +396 -0
- package/src/page-port.ts +162 -0
- package/src/provide.ts +15 -0
- package/src/runtime-smoke.ts +306 -0
- package/src/testing/index.ts +32 -0
package/src/page-port.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// 页面端口:**origin 就是存储身份**,所以端口要粘住,而且**不许悄悄换**。
|
|
2
|
+
//
|
|
3
|
+
// 页面存储(`localStorage` 与页面 shim 的 IndexedDB)按 origin 分区:端口一换就是换一个浏览器。
|
|
4
|
+
// 因此规则是「记住的那个端口被外部进程占着 → 报错并给出口」,只有「第一次」与「记录损坏」才重新选。
|
|
5
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import { createServer } from "node:net";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
/** 端口文件名(在 `userData` 下)。 */
|
|
10
|
+
export const PAGE_PORT_FILE = "page-port";
|
|
11
|
+
|
|
12
|
+
/** 首次兜底的端口(与宿主 `WebServer` 的缺省一致)。 */
|
|
13
|
+
const DEFAULT_PORT = 3080;
|
|
14
|
+
|
|
15
|
+
/** 可用端口的下界:1024 以下是系统保留段。 */
|
|
16
|
+
const MIN_PORT = 1024;
|
|
17
|
+
|
|
18
|
+
/** 可用端口的上界。 */
|
|
19
|
+
const MAX_PORT = 65535;
|
|
20
|
+
|
|
21
|
+
/** 端口从哪来。 */
|
|
22
|
+
export type PortSource = "remembered" | "fresh" | "corrupt" | "explicit";
|
|
23
|
+
|
|
24
|
+
/** 端口选择的结果:要么定下端口,要么与外部占用冲突(冲突时**不自动换**)。 */
|
|
25
|
+
export type PortChoice =
|
|
26
|
+
| { readonly kind: "ok"; readonly port: number; readonly source: PortSource }
|
|
27
|
+
| { readonly kind: "conflict"; readonly port: number };
|
|
28
|
+
|
|
29
|
+
/** 选择端口的输入。 */
|
|
30
|
+
export interface PortInput {
|
|
31
|
+
/** `userData` 目录(端口文件在这里)。 */
|
|
32
|
+
readonly userData: string;
|
|
33
|
+
/** `--port` 的显式值:它就是新的 origin 归属,会被**写回**。 */
|
|
34
|
+
readonly explicit?: number | undefined;
|
|
35
|
+
/** 端口现在能不能绑(测试可换替身)。 */
|
|
36
|
+
readonly probe?: (port: number) => Promise<boolean>;
|
|
37
|
+
/** 重新探一个空闲端口(只在首次 / 记录损坏时用)。 */
|
|
38
|
+
readonly pick?: () => Promise<number>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 解析端口文件(坏内容当「没有」:文件是上一个进程写的,形状不可信)。
|
|
43
|
+
* @param raw - 文件内容。
|
|
44
|
+
* @returns 端口,或 `undefined`。
|
|
45
|
+
*/
|
|
46
|
+
export function parsePort(raw: string | undefined): number | undefined {
|
|
47
|
+
if (raw === undefined) return undefined;
|
|
48
|
+
const text = raw.trim();
|
|
49
|
+
if (!/^\d+$/u.test(text)) return undefined;
|
|
50
|
+
const value = Number(text);
|
|
51
|
+
return value >= MIN_PORT && value <= MAX_PORT ? value : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 读上次记下的端口。
|
|
56
|
+
* @param userData - `userData` 目录。
|
|
57
|
+
* @returns 端口,或 `undefined`(没有 / 坏内容)。
|
|
58
|
+
*/
|
|
59
|
+
export async function preferredPortOf(userData: string): Promise<number | undefined> {
|
|
60
|
+
return (await portRecordOf(userData)).port;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 记下这个端口(写不了就算了:下次重新探一个)。
|
|
65
|
+
* @param userData - `userData` 目录。
|
|
66
|
+
* @param port - 端口。
|
|
67
|
+
* @returns 写完成。
|
|
68
|
+
*/
|
|
69
|
+
export async function rememberPort(userData: string, port: number): Promise<void> {
|
|
70
|
+
await mkdir(userData, { recursive: true });
|
|
71
|
+
await writeFile(join(userData, PAGE_PORT_FILE), `${String(port)}\n`, "utf8").catch(
|
|
72
|
+
() => undefined,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 这次该用哪个端口。
|
|
78
|
+
*
|
|
79
|
+
* 三条规矩:① `--port` 显式值优先,**写回**(用户显式选的 origin 就是新的归属);② 记住的端口空着
|
|
80
|
+
* 就用它;③ 被外部进程占着就报冲突(返回 `conflict`,由调用方抛可操作的错误),**不自动换**——换了
|
|
81
|
+
* 等于把页面存储另起一份。只有「没有记录」与「记录损坏」才重新选并写回。
|
|
82
|
+
* @param input - `userData`、显式值与替身动作。
|
|
83
|
+
* @returns 选好的端口,或冲突。
|
|
84
|
+
*/
|
|
85
|
+
export async function portFor(input: PortInput): Promise<PortChoice> {
|
|
86
|
+
const probe = input.probe ?? isPortFree;
|
|
87
|
+
const pick = input.pick ?? freePort;
|
|
88
|
+
if (input.explicit !== undefined) {
|
|
89
|
+
await rememberPort(input.userData, input.explicit);
|
|
90
|
+
return { kind: "ok", port: input.explicit, source: "explicit" };
|
|
91
|
+
}
|
|
92
|
+
const record = await portRecordOf(input.userData);
|
|
93
|
+
if (record.port !== undefined) {
|
|
94
|
+
if (await probe(record.port)) return { kind: "ok", port: record.port, source: "remembered" };
|
|
95
|
+
return { kind: "conflict", port: record.port };
|
|
96
|
+
}
|
|
97
|
+
const port = await pick();
|
|
98
|
+
await rememberPort(input.userData, port);
|
|
99
|
+
return { kind: "ok", port, source: record.corrupt ? "corrupt" : "fresh" };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 端口冲突时给用户的可操作提示(三条出口,都写明代价)。
|
|
104
|
+
* @param input - 被占的端口与 `userData` 目录。
|
|
105
|
+
* @returns 多行提示。
|
|
106
|
+
*/
|
|
107
|
+
export function portConflictHint(input: {
|
|
108
|
+
readonly port: number;
|
|
109
|
+
readonly userData: string;
|
|
110
|
+
}): string {
|
|
111
|
+
const file = join(input.userData, PAGE_PORT_FILE);
|
|
112
|
+
return [
|
|
113
|
+
`页面端口 ${String(input.port)}(记在 ${file})被别的进程占着。`,
|
|
114
|
+
"不自动换端口:换了 origin,页面存储(localStorage / IndexedDB)会另起一份。三条出口:",
|
|
115
|
+
` · 关掉占用它的进程:lsof -nP -iTCP:${String(input.port)} -sTCP:LISTEN`,
|
|
116
|
+
` · 换端口重起:zephyr desktop dev --port <新端口>(origin 会变,页面存储另起一份)`,
|
|
117
|
+
` · 换一份 userData(并行多个工作区时就这么办):zephyr desktop dev --user-data-dir <目录>`,
|
|
118
|
+
].join("\n");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 端口能不能绑(能绑 = 现在没人占)。
|
|
123
|
+
* @param port - 端口。
|
|
124
|
+
* @returns 判断结果。
|
|
125
|
+
*/
|
|
126
|
+
export async function isPortFree(port: number): Promise<boolean> {
|
|
127
|
+
return new Promise((done) => {
|
|
128
|
+
const server = createServer();
|
|
129
|
+
server.once("error", () => done(false));
|
|
130
|
+
server.listen(port, "127.0.0.1", () => {
|
|
131
|
+
server.close(() => done(true));
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 探一个空闲端口(**只在首次 / 记录损坏时用**:它会让 origin 变化)。
|
|
138
|
+
* @returns 端口。
|
|
139
|
+
*/
|
|
140
|
+
export async function freePort(): Promise<number> {
|
|
141
|
+
return new Promise((resolvePort, reject) => {
|
|
142
|
+
const server = createServer();
|
|
143
|
+
server.once("error", reject);
|
|
144
|
+
server.listen(0, "127.0.0.1", () => {
|
|
145
|
+
const address = server.address();
|
|
146
|
+
const port = typeof address === "object" && address !== null ? address.port : DEFAULT_PORT;
|
|
147
|
+
server.close(() => resolvePort(port));
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 读端口记录:区分「没有文件」与「文件在但坏了」。
|
|
154
|
+
* @param userData - `userData` 目录。
|
|
155
|
+
* @returns 端口(可能没有)与「是否损坏」。
|
|
156
|
+
*/
|
|
157
|
+
async function portRecordOf(userData: string): Promise<{ port?: number; corrupt: boolean }> {
|
|
158
|
+
const raw = await readFile(join(userData, PAGE_PORT_FILE), "utf8").catch(() => undefined);
|
|
159
|
+
if (raw === undefined) return { corrupt: false };
|
|
160
|
+
const port = parsePort(raw);
|
|
161
|
+
return port === undefined ? { corrupt: true } : { port, corrupt: false };
|
|
162
|
+
}
|
package/src/provide.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// 桌面插件的装配清单:**一行就够**(面内多行都在里面),装配面只写
|
|
2
|
+
// `plugins: [...provideDesktopBundle()]`。
|
|
3
|
+
import { provide } from "@morlay/zephyr";
|
|
4
|
+
import { BundleCommand } from "./commands/bundle.ts";
|
|
5
|
+
import { DesktopCommand } from "./commands/desktop.ts";
|
|
6
|
+
import { DesktopDevCommand } from "./commands/dev.ts";
|
|
7
|
+
import { PackagerDefault } from "./packager.ts";
|
|
8
|
+
|
|
9
|
+
/** 桌面形态的清单。 */
|
|
10
|
+
export const provideDesktopBundle = provide([
|
|
11
|
+
DesktopCommand,
|
|
12
|
+
DesktopDevCommand,
|
|
13
|
+
BundleCommand,
|
|
14
|
+
PackagerDefault,
|
|
15
|
+
]);
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// 打包期冒烟:闭包复制进 `Resources/runtime` 之后,先证明它**自包含**,再让包出厂。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有它:deploy 出来的闭包曾经「看着像装好了、跑起来才 404」——某个上游包的链接整个缺失,
|
|
4
|
+
// 而 bundle 一路绿灯。三条判据前置:
|
|
5
|
+
// ① `node_modules/@morlay/*` 的 symlink **允许**(pnpm 的顶层本来就是相对链指进闭包内的 `.pnpm`),
|
|
6
|
+
// 但 realpath 必须落在 `Resources/runtime` 内——**逃逸的链接**(绝对路径 / 指回源码 / 出闭包)才红;
|
|
7
|
+
// ② 闭包清单里的依赖(加两项壳 / loader 必需)都能从闭包解析;
|
|
8
|
+
// ③ 装配文件 `bootstrap.mjs` 能在闭包自己的 loader 下被加载(静态缺链在这一步暴露)。
|
|
9
|
+
// 失败一律 `CliError`;**不在这里补装或逐个实体化**——那只会把 deploy 的问题盖住。
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { readFile, readdir, readlink, realpath, stat } from "node:fs/promises";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
import { join, sep } from "node:path";
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { CliError } from "@morlay/zephyr-cli";
|
|
16
|
+
|
|
17
|
+
/** 壳与 loader 必须能从闭包解析的两项(少了装出来的应用起不来)。 */
|
|
18
|
+
export const REQUIRED_MODULES = ["@morlay/zephyr", "@morlay/dsh-oxc-node"] as const;
|
|
19
|
+
|
|
20
|
+
/** `node_modules/@morlay/*` 下的一个 symlink。 */
|
|
21
|
+
export interface ClosureLink {
|
|
22
|
+
/** 条目名(`@morlay/<name>`)。 */
|
|
23
|
+
readonly name: string;
|
|
24
|
+
/** `readlink` 的原文(相对链就是相对路径)。 */
|
|
25
|
+
readonly target: string;
|
|
26
|
+
/** realpath 是否落在 `Resources/runtime` 内(相对 `.pnpm` 合法)。 */
|
|
27
|
+
readonly inside: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 一次冒烟的发现(没有逃逸链接、没有缺包、入口能加载 = 通过)。 */
|
|
31
|
+
export interface RuntimeSmokeReport {
|
|
32
|
+
/** `node_modules/@morlay/*` 下的全部 symlink(合法与逃逸都在这里,用 `inside` 区分)。 */
|
|
33
|
+
readonly links: readonly ClosureLink[];
|
|
34
|
+
/** 解析不到的依赖名。 */
|
|
35
|
+
readonly missing: readonly string[];
|
|
36
|
+
/** 入口加载失败的说明(`undefined` = 加载成功)。 */
|
|
37
|
+
readonly loadFailure?: string | undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 冒烟用到的两个外部动作(测试换替身)。 */
|
|
41
|
+
export interface RuntimeSmokeActions {
|
|
42
|
+
/** 从闭包解析一个包名(默认走 `createRequire` + 清单存在性)。 */
|
|
43
|
+
readonly resolve?: (runtimeDir: string, name: string) => Promise<string | undefined>;
|
|
44
|
+
/** 加载入口(默认起子进程 + 闭包自己的 loader);返回失败说明。 */
|
|
45
|
+
readonly load?: (runtimeDir: string, entry: string) => Promise<string | undefined>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 跑三条判据,返回发现(**不抛**,好让调用方拼一条完整的错误)。
|
|
50
|
+
* @param runtimeDir - `Resources/runtime`(复制后的真目录)。
|
|
51
|
+
* @param actions - 解析与加载动作(测试可换替身)。
|
|
52
|
+
* @returns 发现报告。
|
|
53
|
+
*/
|
|
54
|
+
export async function runtimeSmokeOf(
|
|
55
|
+
runtimeDir: string,
|
|
56
|
+
actions: RuntimeSmokeActions = {},
|
|
57
|
+
): Promise<RuntimeSmokeReport> {
|
|
58
|
+
const resolve = actions.resolve ?? resolveFrom;
|
|
59
|
+
const load = actions.load ?? loadEntry;
|
|
60
|
+
const links = await scopeLinksOf(runtimeDir);
|
|
61
|
+
const missing: string[] = [];
|
|
62
|
+
for (const name of [
|
|
63
|
+
...REQUIRED_MODULES,
|
|
64
|
+
...(await dependencyNamesOf(join(runtimeDir, "package.json"))),
|
|
65
|
+
]) {
|
|
66
|
+
if ((await resolve(runtimeDir, name)) === undefined) missing.push(name);
|
|
67
|
+
}
|
|
68
|
+
// 每个 `@morlay/*` 自己声明的依赖也要能从**它的真身**解析:懒加载的包(例如 storage-json 那种
|
|
69
|
+
// 「只有用到时才 import」)不会在入口加载里暴露,但装出来一样是缺包。
|
|
70
|
+
missing.push(...(await missingInScopedOf(runtimeDir)));
|
|
71
|
+
const loadFailure = await load(runtimeDir, join(runtimeDir, "bootstrap.mjs"));
|
|
72
|
+
return {
|
|
73
|
+
links,
|
|
74
|
+
missing: [...new Set(missing)],
|
|
75
|
+
...(loadFailure === undefined ? {} : { loadFailure }),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 三条判据有任一不成立就抛(装配链在打包这一步停下,而不是等到用户双击)。
|
|
81
|
+
*
|
|
82
|
+
* 链接分两类:realpath 在闭包内的是**合法**(pnpm 的正常形态),逃逸的才进错误。
|
|
83
|
+
* @param runtimeDir - `Resources/runtime`。
|
|
84
|
+
* @param actions - 解析与加载动作(测试可换替身)。
|
|
85
|
+
* @returns 通过时的报告(打包日志用它记「几个链接、几个逃逸」)。
|
|
86
|
+
* @throws CliError 有逃逸链接、缺包或入口加载失败。
|
|
87
|
+
*/
|
|
88
|
+
export async function assertRuntimeSmoke(
|
|
89
|
+
runtimeDir: string,
|
|
90
|
+
actions: RuntimeSmokeActions = {},
|
|
91
|
+
): Promise<RuntimeSmokeReport> {
|
|
92
|
+
const report = await runtimeSmokeOf(runtimeDir, actions);
|
|
93
|
+
const escaping = report.links.filter((link) => !link.inside);
|
|
94
|
+
const problems: string[] = [];
|
|
95
|
+
if (escaping.length > 0) {
|
|
96
|
+
problems.push(
|
|
97
|
+
`闭包里有逃逸链接(realpath 不在 ${runtimeDir} 内):${escaping
|
|
98
|
+
.map((link) => `${link.name} -> ${link.target}`)
|
|
99
|
+
.join("、")}`,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
if (report.missing.length > 0) {
|
|
103
|
+
problems.push(`从闭包解析不到:${report.missing.join("、")}`);
|
|
104
|
+
}
|
|
105
|
+
if (report.loadFailure !== undefined) {
|
|
106
|
+
problems.push(`装配文件 bootstrap.mjs 加载失败:${report.loadFailure}`);
|
|
107
|
+
}
|
|
108
|
+
if (problems.length === 0) return report;
|
|
109
|
+
throw new CliError(
|
|
110
|
+
[`运行时闭包不自包含(${runtimeDir}):`, ...problems.map((line) => ` · ${line}`)].join("\n"),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 打包产物里的 `Resources` 目录:mac 是 `<app>/Contents/Resources`,其它平台 `<app>/resources`。
|
|
116
|
+
* @param appDir - 打包产出的应用目录。
|
|
117
|
+
* @returns Resources 目录。
|
|
118
|
+
* @throws CliError 两种布局都不存在。
|
|
119
|
+
*/
|
|
120
|
+
export async function resourcesDirOf(appDir: string): Promise<string> {
|
|
121
|
+
const candidates = [join(appDir, "Contents", "Resources"), join(appDir, "resources")];
|
|
122
|
+
for (const candidate of candidates) {
|
|
123
|
+
try {
|
|
124
|
+
if ((await stat(candidate)).isDirectory()) return candidate;
|
|
125
|
+
} catch {
|
|
126
|
+
// 试下一种布局。
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw new CliError(`找不到打包产物里的 Resources 目录:试过 ${candidates.join("、")}。`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 打包产物里的宿主目录:`<Resources>/runtime`(真目录:壳要 `chdir` 进去)。
|
|
134
|
+
* @param appDir - 打包产出的应用目录。
|
|
135
|
+
* @returns 宿主目录。
|
|
136
|
+
* @throws CliError 两种布局都找不到 `bootstrap.mjs`。
|
|
137
|
+
*/
|
|
138
|
+
export async function runtimeDirInAppOf(appDir: string): Promise<string> {
|
|
139
|
+
const runtimeDir = join(await resourcesDirOf(appDir), "runtime");
|
|
140
|
+
try {
|
|
141
|
+
await readFile(join(runtimeDir, "bootstrap.mjs"));
|
|
142
|
+
return runtimeDir;
|
|
143
|
+
} catch {
|
|
144
|
+
throw new CliError(`打包产物里的宿主目录缺 bootstrap.mjs:${runtimeDir}。`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `node_modules/@morlay/*` 下的全部 symlink,并判断 realpath 是否仍在闭包内。
|
|
150
|
+
*
|
|
151
|
+
* 允许 symlink:pnpm 的顶层本来就是「相对链指进闭包内的 `.pnpm`」。判据是**落点**而不是形态——
|
|
152
|
+
* 绝对路径、指回源码、或干脆指向闭包外(含悬空)都算逃逸。
|
|
153
|
+
* @param runtimeDir - 闭包根。
|
|
154
|
+
* @returns 条目(按名字排序);没有 scope 目录就是空。
|
|
155
|
+
*/
|
|
156
|
+
async function scopeLinksOf(runtimeDir: string): Promise<readonly ClosureLink[]> {
|
|
157
|
+
const scope = join(runtimeDir, "node_modules", "@morlay");
|
|
158
|
+
const entries = await readdir(scope, { withFileTypes: true }).catch(() => []);
|
|
159
|
+
const root = await realpath(runtimeDir).catch(() => runtimeDir);
|
|
160
|
+
const links: ClosureLink[] = [];
|
|
161
|
+
for (const entry of entries) {
|
|
162
|
+
if (!entry.isSymbolicLink()) continue;
|
|
163
|
+
const path = join(scope, entry.name);
|
|
164
|
+
const target = await readlink(path).catch(() => "");
|
|
165
|
+
const resolved = await realpath(path).catch(() => undefined);
|
|
166
|
+
links.push({
|
|
167
|
+
name: entry.name,
|
|
168
|
+
target,
|
|
169
|
+
inside: resolved !== undefined && (resolved === root || resolved.startsWith(`${root}${sep}`)),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return links.sort((left, right) => left.name.localeCompare(right.name));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 一份清单里声明的依赖名。
|
|
177
|
+
* @param manifestPath - `package.json` 的绝对路径。
|
|
178
|
+
* @returns 依赖名(读不到清单就是空)。
|
|
179
|
+
*/
|
|
180
|
+
async function dependencyNamesOf(manifestPath: string): Promise<readonly string[]> {
|
|
181
|
+
const raw = await readFile(manifestPath, "utf8").catch(() => undefined);
|
|
182
|
+
if (raw === undefined) return [];
|
|
183
|
+
try {
|
|
184
|
+
const manifest = JSON.parse(raw) as { readonly dependencies?: Record<string, unknown> };
|
|
185
|
+
return Object.keys(manifest.dependencies ?? {});
|
|
186
|
+
} catch {
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* `@morlay/*` 各包自己声明的依赖里解析不到的那些(从**真身**解析:CJS 的 `createRequire` 对
|
|
193
|
+
* 符号链接路径按字面走,会误报 MODULE_NOT_FOUND——实测 `dsh-storage` 的 storage-json 就是这样)。
|
|
194
|
+
* @param runtimeDir - 闭包根。
|
|
195
|
+
* @returns `@morlay/<包> -> <缺的包>` 形式的条目。
|
|
196
|
+
*/
|
|
197
|
+
async function missingInScopedOf(runtimeDir: string): Promise<readonly string[]> {
|
|
198
|
+
const scope = join(runtimeDir, "node_modules", "@morlay");
|
|
199
|
+
const entries = await readdir(scope, { withFileTypes: true }).catch(() => []);
|
|
200
|
+
const missing: string[] = [];
|
|
201
|
+
for (const entry of entries) {
|
|
202
|
+
// 悬空链接由链接判据报,这里只查「装了的包自己的依赖」。
|
|
203
|
+
const real = await realpath(join(scope, entry.name, "package.json")).catch(() => undefined);
|
|
204
|
+
if (real === undefined) continue;
|
|
205
|
+
for (const name of await dependencyNamesOf(real)) {
|
|
206
|
+
if ((await resolveFromManifest(real, name)) === undefined) {
|
|
207
|
+
missing.push(`@morlay/${entry.name} -> ${name}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return missing;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 从子进程的 stderr 里挑出最像原因的那一行(栈第一行通常是 node 内部路径,读的人看不出问题)。
|
|
216
|
+
* @param stderr - 子进程的 stderr。
|
|
217
|
+
* @returns 一行说明(挑不到就给尾部 500 字)。
|
|
218
|
+
*/
|
|
219
|
+
function firstErrorLineOf(stderr: string): string {
|
|
220
|
+
const lines = stderr
|
|
221
|
+
.split("\n")
|
|
222
|
+
.map((line) => line.trim())
|
|
223
|
+
.filter((line) => line !== "");
|
|
224
|
+
const reason =
|
|
225
|
+
lines.find((line) => /^Error\b/u.test(line)) ??
|
|
226
|
+
lines.find((line) => /Cannot find|ERR_(MODULE|PACKAGE)_NOT_FOUND/u.test(line)) ??
|
|
227
|
+
lines.at(-1) ??
|
|
228
|
+
"";
|
|
229
|
+
return reason.slice(-500);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 从闭包里解析一个包:先按包名,再按它的 `package.json`。
|
|
234
|
+
*
|
|
235
|
+
* 为什么要退一步:只给子路径导出(没有 `.`)的包(例如 `@oxc-project/runtime`)按包名解析会报
|
|
236
|
+
* `ERR_PACKAGE_PATH_NOT_EXPORTED`——那是**包装好了**,不是缺包。缺包时两种解析都失败。
|
|
237
|
+
* @param runtimeDir - 闭包根。
|
|
238
|
+
* @param name - 包名。
|
|
239
|
+
* @returns 入口(或清单)路径,或 `undefined`(确实没有这个包)。
|
|
240
|
+
*/
|
|
241
|
+
function resolveFrom(runtimeDir: string, name: string): Promise<string | undefined> {
|
|
242
|
+
return resolveFromManifest(join(runtimeDir, "package.json"), name);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 从某份清单所在的位置解析一个包(先按包名,再按清单存在性)。
|
|
247
|
+
* @param manifestPath - 基准 `package.json`(用它的**真身**:符号链接路径会误报)。
|
|
248
|
+
* @param name - 包名。
|
|
249
|
+
* @returns 入口(或清单)路径,或 `undefined`。
|
|
250
|
+
*/
|
|
251
|
+
async function resolveFromManifest(
|
|
252
|
+
manifestPath: string,
|
|
253
|
+
name: string,
|
|
254
|
+
): Promise<string | undefined> {
|
|
255
|
+
const require = createRequire(manifestPath);
|
|
256
|
+
try {
|
|
257
|
+
return require.resolve(name);
|
|
258
|
+
} catch {
|
|
259
|
+
// 没有 "." 导出的包(例如 `@oxc-project/runtime`)走到这里:按「盘上有没有它」判。
|
|
260
|
+
}
|
|
261
|
+
for (const base of require.resolve.paths(name) ?? []) {
|
|
262
|
+
const manifest = join(base, name, "package.json");
|
|
263
|
+
try {
|
|
264
|
+
await readFile(manifest);
|
|
265
|
+
return manifest;
|
|
266
|
+
} catch {
|
|
267
|
+
// 这个解析根里没有,试下一个。
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 在闭包自己的 loader 下加载装配文件(子进程:不把宿主拖进打包进程)。
|
|
275
|
+
* @param runtimeDir - 宿主目录。
|
|
276
|
+
* @param entry - `bootstrap.mjs` 的绝对路径。
|
|
277
|
+
* @returns 失败说明,成功为 `undefined`。
|
|
278
|
+
*/
|
|
279
|
+
async function loadEntry(runtimeDir: string, entry: string): Promise<string | undefined> {
|
|
280
|
+
const loader = await resolveFrom(runtimeDir, "@morlay/dsh-oxc-node");
|
|
281
|
+
if (loader === undefined) return "闭包里没有 @morlay/dsh-oxc-node(loader)";
|
|
282
|
+
const script = `await import(${JSON.stringify(pathToFileURL(entry).href)});`;
|
|
283
|
+
const env: NodeJS.ProcessEnv = { ...process.env };
|
|
284
|
+
// 父进程的 NODE_OPTIONS 可能又挂一份 loader(pnpm 注入):这里只留闭包里的那一份。
|
|
285
|
+
delete env.NODE_OPTIONS;
|
|
286
|
+
delete env.ELECTRON_RUN_AS_NODE;
|
|
287
|
+
return new Promise((done) => {
|
|
288
|
+
const child = spawn(
|
|
289
|
+
process.execPath,
|
|
290
|
+
["--import", pathToFileURL(loader).href, "--eval", script],
|
|
291
|
+
{
|
|
292
|
+
cwd: runtimeDir,
|
|
293
|
+
env,
|
|
294
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
295
|
+
},
|
|
296
|
+
);
|
|
297
|
+
let stderr = "";
|
|
298
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
299
|
+
stderr += chunk.toString("utf8");
|
|
300
|
+
});
|
|
301
|
+
child.once("error", (error: Error) => done(error.message));
|
|
302
|
+
child.once("close", (code: number | null) => {
|
|
303
|
+
done(code === 0 ? undefined : `子进程退出码 ${String(code)}:${firstErrorLineOf(stderr)}`);
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// 测试辅助:打包这件事只测**编排**(构建了没、装到哪),不真产出一个 .app。
|
|
2
|
+
import { Injectable } from "@morlay/zephyr";
|
|
3
|
+
import type { ElectronBuilderConfig } from "../electron-builder.ts";
|
|
4
|
+
import { Packager, type PackInput, type PackResult } from "../packager.ts";
|
|
5
|
+
|
|
6
|
+
/** 记录调用、返回固定产物的打包器。 */
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class FakePackager extends Packager {
|
|
9
|
+
/** 每次打包收到的配置。 */
|
|
10
|
+
readonly packs: ElectronBuilderConfig[] = [];
|
|
11
|
+
|
|
12
|
+
/** 每次安装收到的产物。 */
|
|
13
|
+
readonly installs: PackResult[] = [];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param _config - 配置。
|
|
17
|
+
* @returns 一个假的应用目录。
|
|
18
|
+
*/
|
|
19
|
+
async pack(_config: ElectronBuilderConfig, _input: PackInput): Promise<PackResult> {
|
|
20
|
+
this.packs.push(_config);
|
|
21
|
+
return { appDir: "/tmp/fake.app" };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param result - 打包结果。
|
|
26
|
+
* @returns 装的路径。
|
|
27
|
+
*/
|
|
28
|
+
async install(result: PackResult): Promise<string> {
|
|
29
|
+
this.installs.push(result);
|
|
30
|
+
return "/Applications/fake.app";
|
|
31
|
+
}
|
|
32
|
+
}
|