@xlinklight/browser-extension-tools 1.0.0-rc.0 → 1.0.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.
@@ -1,203 +1,203 @@
1
- import { spawnSync } from "node:child_process";
2
- import { fileURLToPath } from "node:url";
3
- import path from "node:path";
4
- import { createNodeCommandRunner } from "@openge/forge-command-runner/node";
5
- import { createPosixProcessControl, createWindowsProcessControl } from "@openge/forge-process-control-node";
6
- import { chromeForTestingOfficialBaseUrl, defaultChromeForTestingFallbackBuildId, getProjectPaths } from "./cli.mjs";
7
-
8
- function createInstallerCommandRunner(platform) {
9
- return createNodeCommandRunner({
10
- platform: platform === "win32" ? "win32" : "posix",
11
- processControl: platform === "win32" ? createWindowsProcessControl({ listenerBackend: "powershell" }) : createPosixProcessControl({ listenerBackend: "lsof" }),
12
- terminationPolicy: { mode: platform === "win32" ? "force" : "graceful" },
13
- identityAcquisition: { timeoutMs: platform === "win32" ? 8_000 : 2_000, pollIntervalMs: 20 },
14
- terminationTimeoutMs: platform === "win32" ? 15_000 : 5_000,
15
- });
16
- }
17
-
18
- export function trimOutput(value, maxLength = 2400) {
19
- const normalized = value.trim();
20
- if (normalized.length <= maxLength) return normalized;
21
- return normalized.slice(-maxLength);
22
- }
23
-
24
- export function stringifyProcessOutput(value) {
25
- if (!value) return "";
26
- return Buffer.isBuffer(value) ? value.toString("utf8") : String(value);
27
- }
28
-
29
- export function getProcessOutputErrorReason(result) {
30
- const output = [result.stderr, result.stdout].map(stringifyProcessOutput).filter(Boolean).join("\n");
31
- const errorMatch = output.match(/\bError:\s*([^\r\n]+)/);
32
- return errorMatch?.[1]?.trim() || "";
33
- }
34
-
35
- export function formatChromeForTestingInstallFailure(result) {
36
- if (result.error) return result.error.message;
37
-
38
- const reason = getProcessOutputErrorReason(result);
39
- if (typeof result.status === "number" && result.status !== 0) {
40
- return `exit code ${result.status}${reason ? `: ${reason}` : ""}`;
41
- }
42
-
43
- return reason || "unknown error";
44
- }
45
-
46
- export function getPackageRunner({ env, platform }) {
47
- const userAgent = env.npm_config_user_agent ?? "";
48
- const execPath = env.npm_execpath ?? "";
49
- const commandSuffix = platform === "win32" ? ".cmd" : "";
50
-
51
- if (userAgent.startsWith("pnpm/") || /[\\/]pnpm(?:\.cjs|\.js|\.cmd)?$/i.test(execPath)) {
52
- return { command: `pnpm${commandSuffix}`, argsPrefix: ["dlx"] };
53
- }
54
-
55
- return { command: `npx${commandSuffix}`, argsPrefix: [] };
56
- }
57
-
58
- export function getChromeForTestingInstallStep({
59
- env = process.env,
60
- platform = process.platform,
61
- rootDir = process.cwd(),
62
- } = {}) {
63
- const { chromeForTestingDir } = getProjectPaths(rootDir);
64
- const packageRunner = getPackageRunner({ env, platform });
65
-
66
- return {
67
- command: packageRunner.command,
68
- args: [
69
- ...packageRunner.argsPrefix,
70
- "@puppeteer/browsers",
71
- "install",
72
- "chrome@stable",
73
- "--path",
74
- chromeForTestingDir,
75
- ],
76
- };
77
- }
78
-
79
- export function getChromeForTestingFallbackBuildId(env = process.env) {
80
- return env.LINK_LIGHT_CHROME_FOR_TESTING_BUILD_ID?.trim() || defaultChromeForTestingFallbackBuildId;
81
- }
82
-
83
- export function getChromeForTestingDirectInstallStep({
84
- env = process.env,
85
- platform = process.platform,
86
- rootDir = process.cwd(),
87
- } = {}) {
88
- if (platform !== "win32") return null;
89
-
90
- const { chromeForTestingDir } = getProjectPaths(rootDir);
91
- const packageRunner = getPackageRunner({ env, platform });
92
- const buildId = getChromeForTestingFallbackBuildId(env);
93
-
94
- return {
95
- command: packageRunner.command,
96
- args: [
97
- ...packageRunner.argsPrefix,
98
- "@puppeteer/browsers",
99
- "install",
100
- `chrome@${buildId}`,
101
- "--platform",
102
- "win64",
103
- "--base-url",
104
- chromeForTestingOfficialBaseUrl,
105
- "--path",
106
- chromeForTestingDir,
107
- ],
108
- route: "official exact build fallback",
109
- };
110
- }
111
-
112
- export function getChromeForTestingInstallSteps({
113
- env = process.env,
114
- platform = process.platform,
115
- rootDir = process.cwd(),
116
- } = {}) {
117
- return [
118
- { ...getChromeForTestingInstallStep({ env, platform, rootDir }), route: "stable channel" },
119
- getChromeForTestingDirectInstallStep({ env, platform, rootDir }),
120
- ].filter(Boolean);
121
- }
122
-
123
- export function installChromeForTesting({
124
- env = process.env,
125
- installRunner = spawnSync,
126
- logger = console.log,
127
- maxAttempts = 3,
128
- platform = process.platform,
129
- rootDir = process.cwd(),
130
- stdio = "inherit",
131
- } = {}) {
132
- const steps = getChromeForTestingInstallSteps({ env, platform, rootDir });
133
- let lastFailure = null;
134
-
135
- for (const step of steps) {
136
- logger(`Using Chrome for Testing install route: ${step.route}.`);
137
-
138
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
139
- const attemptLabel = maxAttempts > 1 ? ` (${attempt}/${maxAttempts})` : "";
140
- logger(`Installing Chrome for Testing${attemptLabel} with: ${[step.command, ...step.args].join(" ")}`);
141
- const result = installRunner(step.command, step.args, {
142
- stdio,
143
- shell: platform === "win32",
144
- });
145
-
146
- if (result.error) {
147
- const failureMessage = formatChromeForTestingInstallFailure(result);
148
- lastFailure = failureMessage;
149
- if (attempt === maxAttempts) {
150
- logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
151
- break;
152
- }
153
- logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
154
- continue;
155
- }
156
- if (typeof result.status === "number" && result.status !== 0) {
157
- const failureMessage = formatChromeForTestingInstallFailure(result);
158
- lastFailure = failureMessage;
159
- if (attempt === maxAttempts) {
160
- logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
161
- break;
162
- }
163
- logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
164
- continue;
165
- }
166
-
167
- return;
168
- }
169
- }
170
-
171
- throw new Error(`Chrome for Testing install failed with ${lastFailure || "unknown error"}`);
172
- }
173
-
174
- // 同步安装器保留原有重试策略;主 dev 在独立 Node 进程中等待它,确保可以取消整个安装树。
175
- export async function installChromeForTestingForDev({
176
- env = process.env,
177
- logger = console.log,
178
- maxAttempts = 3,
179
- platform = process.platform,
180
- rootDir = process.cwd(),
181
- signal,
182
- commandRunner = createInstallerCommandRunner(platform),
183
- ...options
184
- } = {}) {
185
- if (!signal) return installChromeForTesting({ ...options, env, logger, maxAttempts, platform, rootDir });
186
- signal.throwIfAborted();
187
- const result = await commandRunner.run({
188
- command: process.execPath,
189
- args: [path.join(path.dirname(fileURLToPath(import.meta.url)), "chrome-install-worker.mjs"), String(maxAttempts)],
190
- cwd: rootDir,
191
- signal,
192
- environment: { mode: "replace", values: Object.fromEntries(Object.entries(env).filter(([, value]) => value !== undefined)) },
193
- output: { mode: "capture", maxBytesPerStream: 1024 * 1024, overflow: "truncate" },
194
- });
195
- for (const bytes of [result.stdout, result.stderr]) {
196
- if (bytes?.length) logger(Buffer.from(bytes).toString("utf8"));
197
- }
198
- if (result.diagnostics.length) throw new Error(result.diagnostics.map(item => item.code).join(", "));
199
- signal.throwIfAborted();
200
- if (result.terminationReason !== "exit" || result.exitCode !== 0) {
201
- throw new Error("Chrome for Testing install command ended: " + result.terminationReason + " (" + result.exitCode + ").");
202
- }
203
- }
1
+ import { spawnSync } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import path from "node:path";
4
+ import { createNodeCommandRunner } from "@openge/forge-command-runner/node";
5
+ import { createPosixProcessControl, createWindowsProcessControl } from "@openge/forge-process-control-node";
6
+ import { chromeForTestingOfficialBaseUrl, defaultChromeForTestingFallbackBuildId, getProjectPaths } from "./cli.mjs";
7
+
8
+ function createInstallerCommandRunner(platform) {
9
+ return createNodeCommandRunner({
10
+ platform: platform === "win32" ? "win32" : "posix",
11
+ processControl: platform === "win32" ? createWindowsProcessControl({ listenerBackend: "powershell" }) : createPosixProcessControl({ listenerBackend: "lsof" }),
12
+ terminationPolicy: { mode: platform === "win32" ? "force" : "graceful" },
13
+ identityAcquisition: { timeoutMs: platform === "win32" ? 8_000 : 2_000, pollIntervalMs: 20 },
14
+ terminationTimeoutMs: platform === "win32" ? 15_000 : 5_000,
15
+ });
16
+ }
17
+
18
+ export function trimOutput(value, maxLength = 2400) {
19
+ const normalized = value.trim();
20
+ if (normalized.length <= maxLength) return normalized;
21
+ return normalized.slice(-maxLength);
22
+ }
23
+
24
+ export function stringifyProcessOutput(value) {
25
+ if (!value) return "";
26
+ return Buffer.isBuffer(value) ? value.toString("utf8") : String(value);
27
+ }
28
+
29
+ export function getProcessOutputErrorReason(result) {
30
+ const output = [result.stderr, result.stdout].map(stringifyProcessOutput).filter(Boolean).join("\n");
31
+ const errorMatch = output.match(/\bError:\s*([^\r\n]+)/);
32
+ return errorMatch?.[1]?.trim() || "";
33
+ }
34
+
35
+ export function formatChromeForTestingInstallFailure(result) {
36
+ if (result.error) return result.error.message;
37
+
38
+ const reason = getProcessOutputErrorReason(result);
39
+ if (typeof result.status === "number" && result.status !== 0) {
40
+ return `exit code ${result.status}${reason ? `: ${reason}` : ""}`;
41
+ }
42
+
43
+ return reason || "unknown error";
44
+ }
45
+
46
+ export function getPackageRunner({ env, platform }) {
47
+ const userAgent = env.npm_config_user_agent ?? "";
48
+ const execPath = env.npm_execpath ?? "";
49
+ const commandSuffix = platform === "win32" ? ".cmd" : "";
50
+
51
+ if (userAgent.startsWith("pnpm/") || /[\\/]pnpm(?:\.cjs|\.js|\.cmd)?$/i.test(execPath)) {
52
+ return { command: `pnpm${commandSuffix}`, argsPrefix: ["dlx"] };
53
+ }
54
+
55
+ return { command: `npx${commandSuffix}`, argsPrefix: [] };
56
+ }
57
+
58
+ export function getChromeForTestingInstallStep({
59
+ env = process.env,
60
+ platform = process.platform,
61
+ rootDir = process.cwd(),
62
+ } = {}) {
63
+ const { chromeForTestingDir } = getProjectPaths(rootDir);
64
+ const packageRunner = getPackageRunner({ env, platform });
65
+
66
+ return {
67
+ command: packageRunner.command,
68
+ args: [
69
+ ...packageRunner.argsPrefix,
70
+ "@puppeteer/browsers",
71
+ "install",
72
+ "chrome@stable",
73
+ "--path",
74
+ chromeForTestingDir,
75
+ ],
76
+ };
77
+ }
78
+
79
+ export function getChromeForTestingFallbackBuildId(env = process.env) {
80
+ return env.LINK_LIGHT_CHROME_FOR_TESTING_BUILD_ID?.trim() || defaultChromeForTestingFallbackBuildId;
81
+ }
82
+
83
+ export function getChromeForTestingDirectInstallStep({
84
+ env = process.env,
85
+ platform = process.platform,
86
+ rootDir = process.cwd(),
87
+ } = {}) {
88
+ if (platform !== "win32") return null;
89
+
90
+ const { chromeForTestingDir } = getProjectPaths(rootDir);
91
+ const packageRunner = getPackageRunner({ env, platform });
92
+ const buildId = getChromeForTestingFallbackBuildId(env);
93
+
94
+ return {
95
+ command: packageRunner.command,
96
+ args: [
97
+ ...packageRunner.argsPrefix,
98
+ "@puppeteer/browsers",
99
+ "install",
100
+ `chrome@${buildId}`,
101
+ "--platform",
102
+ "win64",
103
+ "--base-url",
104
+ chromeForTestingOfficialBaseUrl,
105
+ "--path",
106
+ chromeForTestingDir,
107
+ ],
108
+ route: "official exact build fallback",
109
+ };
110
+ }
111
+
112
+ export function getChromeForTestingInstallSteps({
113
+ env = process.env,
114
+ platform = process.platform,
115
+ rootDir = process.cwd(),
116
+ } = {}) {
117
+ return [
118
+ { ...getChromeForTestingInstallStep({ env, platform, rootDir }), route: "stable channel" },
119
+ getChromeForTestingDirectInstallStep({ env, platform, rootDir }),
120
+ ].filter(Boolean);
121
+ }
122
+
123
+ export function installChromeForTesting({
124
+ env = process.env,
125
+ installRunner = spawnSync,
126
+ logger = console.log,
127
+ maxAttempts = 3,
128
+ platform = process.platform,
129
+ rootDir = process.cwd(),
130
+ stdio = "inherit",
131
+ } = {}) {
132
+ const steps = getChromeForTestingInstallSteps({ env, platform, rootDir });
133
+ let lastFailure = null;
134
+
135
+ for (const step of steps) {
136
+ logger(`Using Chrome for Testing install route: ${step.route}.`);
137
+
138
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
139
+ const attemptLabel = maxAttempts > 1 ? ` (${attempt}/${maxAttempts})` : "";
140
+ logger(`Installing Chrome for Testing${attemptLabel} with: ${[step.command, ...step.args].join(" ")}`);
141
+ const result = installRunner(step.command, step.args, {
142
+ stdio,
143
+ shell: platform === "win32",
144
+ });
145
+
146
+ if (result.error) {
147
+ const failureMessage = formatChromeForTestingInstallFailure(result);
148
+ lastFailure = failureMessage;
149
+ if (attempt === maxAttempts) {
150
+ logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
151
+ break;
152
+ }
153
+ logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
154
+ continue;
155
+ }
156
+ if (typeof result.status === "number" && result.status !== 0) {
157
+ const failureMessage = formatChromeForTestingInstallFailure(result);
158
+ lastFailure = failureMessage;
159
+ if (attempt === maxAttempts) {
160
+ logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
161
+ break;
162
+ }
163
+ logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
164
+ continue;
165
+ }
166
+
167
+ return;
168
+ }
169
+ }
170
+
171
+ throw new Error(`Chrome for Testing install failed with ${lastFailure || "unknown error"}`);
172
+ }
173
+
174
+ // 同步安装器保留原有重试策略;主 dev 在独立 Node 进程中等待它,确保可以取消整个安装树。
175
+ export async function installChromeForTestingForDev({
176
+ env = process.env,
177
+ logger = console.log,
178
+ maxAttempts = 3,
179
+ platform = process.platform,
180
+ rootDir = process.cwd(),
181
+ signal,
182
+ commandRunner = createInstallerCommandRunner(platform),
183
+ ...options
184
+ } = {}) {
185
+ if (!signal) return installChromeForTesting({ ...options, env, logger, maxAttempts, platform, rootDir });
186
+ signal.throwIfAborted();
187
+ const result = await commandRunner.run({
188
+ command: process.execPath,
189
+ args: [path.join(path.dirname(fileURLToPath(import.meta.url)), "chrome-install-worker.mjs"), String(maxAttempts)],
190
+ cwd: rootDir,
191
+ signal,
192
+ environment: { mode: "replace", values: Object.fromEntries(Object.entries(env).filter(([, value]) => value !== undefined)) },
193
+ output: { mode: "capture", maxBytesPerStream: 1024 * 1024, overflow: "truncate" },
194
+ });
195
+ for (const bytes of [result.stdout, result.stderr]) {
196
+ if (bytes?.length) logger(Buffer.from(bytes).toString("utf8"));
197
+ }
198
+ if (result.diagnostics.length) throw new Error(result.diagnostics.map(item => item.code).join(", "));
199
+ signal.throwIfAborted();
200
+ if (result.terminationReason !== "exit" || result.exitCode !== 0) {
201
+ throw new Error("Chrome for Testing install command ended: " + result.terminationReason + " (" + result.exitCode + ").");
202
+ }
203
+ }
@@ -1,8 +1,8 @@
1
- import { installChromeForTesting } from "./chrome-for-testing.mjs";
2
-
3
- try {
4
- installChromeForTesting({ maxAttempts: Number(process.argv[2]), stdio: "inherit" });
5
- } catch (error) {
6
- console.error(error instanceof Error ? error.message : String(error));
7
- process.exitCode = 1;
8
- }
1
+ import { installChromeForTesting } from "./chrome-for-testing.mjs";
2
+
3
+ try {
4
+ installChromeForTesting({ maxAttempts: Number(process.argv[2]), stdio: "inherit" });
5
+ } catch (error) {
6
+ console.error(error instanceof Error ? error.message : String(error));
7
+ process.exitCode = 1;
8
+ }