@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,350 +1,350 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { watch } from "node:fs";
3
- import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
- import { assertExtensionRoot, assertProjectOutput, defaultDevUrl, devReloadClientFileName, devSidePanelReloadClientFileName, getArgValue, getProfileDirForExtensions, getProjectPaths, getRelevantExtensionFiles, getRelevantExtensionSourcePath, getRequestedAppUrl, getRequestedExtensions, parseAppUrl } from "./cli.mjs";
6
- import { buildChromeLaunchConfig, findLocalChromeForTesting } from "./chrome-discovery.mjs";
7
- import { installChromeForTestingForDev } from "./chrome-for-testing.mjs";
8
- import { ensureFreshChromeProfileForExtension, getExtensionLaunchSignature, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.mjs";
9
- import { createDevReloadServer } from "./reload-server.mjs";
10
- import { createExtensionFileWatcher } from "./watcher.mjs";
11
-
12
- export async function readFileIfExists(filePath) {
13
- try {
14
- const fileStats = await stat(filePath);
15
- if (fileStats.isDirectory()) {
16
- const entries = await readdir(filePath);
17
- const snapshots = await Promise.all(
18
- entries
19
- .toSorted()
20
- .map(async (entry) => `${entry}\0${await readFileIfExists(path.join(filePath, entry))}`),
21
- );
22
- return snapshots.join("\0");
23
- }
24
-
25
- return await readFile(filePath, "utf8");
26
- } catch (error) {
27
- if (error?.code === "ENOENT") {
28
- return "";
29
- }
30
- throw error;
31
- }
32
- }
33
-
34
- export async function copyExtensionEntry(sourcePath, targetPath) {
35
- try {
36
- const sourceStats = await stat(sourcePath);
37
- if (sourceStats.isDirectory()) {
38
- await cp(sourcePath, targetPath, { recursive: true });
39
- return;
40
- }
41
-
42
- await mkdir(path.dirname(targetPath), { recursive: true });
43
- await writeFile(targetPath, await readFile(sourcePath));
44
- } catch (error) {
45
- if (error?.code === "ENOENT") return;
46
- throw error;
47
- }
48
- }
49
-
50
- export function addUniqueItems(items, additions) {
51
- return [...new Set([...(items ?? []), ...additions])];
52
- }
53
-
54
- export function buildDevReloadClient({ appOrigin, reloadPort }) {
55
- return `(() => {
56
- const appTabUrlPattern = ${JSON.stringify(`${appOrigin}/*`)};
57
- const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
58
-
59
- async function injectPageBridgeIntoAppTabs() {
60
- if (!chrome.tabs?.query || !chrome.scripting?.executeScript) return;
61
- const tabs = await chrome.tabs.query({ url: appTabUrlPattern });
62
- await Promise.all(tabs.map(async (tab) => {
63
- if (!tab?.id) return;
64
- await chrome.scripting.executeScript({
65
- target: { tabId: tab.id },
66
- files: ["page-bridge.js"],
67
- }).catch(() => null);
68
- }));
69
- }
70
-
71
- function connect() {
72
- const socket = new WebSocket(reloadSocketUrl);
73
- socket.addEventListener("message", (event) => {
74
- try {
75
- const message = JSON.parse(event.data);
76
- if (message?.type !== "reload") return;
77
- chrome.runtime.reload();
78
- } catch {
79
- // Ignore malformed dev-server messages.
80
- }
81
- });
82
- socket.addEventListener("close", () => setTimeout(connect, 1000));
83
- socket.addEventListener("error", () => socket.close());
84
- }
85
-
86
- void injectPageBridgeIntoAppTabs();
87
- connect();
88
- })();
89
- `;
90
- }
91
-
92
- export function buildDevSidePanelReloadClient({ buildLabel, reloadPort }) {
93
- return `(() => {
94
- const marker = document.createElement("div");
95
- marker.id = "ll-dev-build-marker";
96
- marker.textContent = ${JSON.stringify(`Dev build ${buildLabel}`)};
97
- marker.style.cssText = "position:fixed;right:62px;bottom:8px;z-index:2147483647;border:1px solid #99f6e4;border-radius:6px;padding:2px 6px;background:#ecfeff;color:#0f766e;font:11px Arial,sans-serif;";
98
- document.addEventListener("DOMContentLoaded", () => document.body.append(marker), { once: true });
99
-
100
- const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
101
- function connect() {
102
- const socket = new WebSocket(reloadSocketUrl);
103
- socket.addEventListener("message", (event) => {
104
- try {
105
- const message = JSON.parse(event.data);
106
- if (message?.type !== "reload") return;
107
- location.reload();
108
- } catch {
109
- // Ignore malformed dev-server messages.
110
- }
111
- });
112
- socket.addEventListener("close", () => setTimeout(connect, 1000));
113
- socket.addEventListener("error", () => socket.close());
114
- }
115
-
116
- connect();
117
- })();
118
- `;
119
- }
120
-
121
- function injectDevSidePanelReloadClient(html) {
122
- const scriptTag = ` <script src="${devSidePanelReloadClientFileName}" defer></script>`;
123
- if (html.includes(devSidePanelReloadClientFileName)) return html;
124
- if (html.includes(" </body>")) return html.replace(" </body>", `${scriptTag}\n </body>`);
125
- return `${html}\n${scriptTag}\n`;
126
- }
127
-
128
- export async function prepareDevExtension({
129
- appUrl = defaultDevUrl,
130
- extensionName,
131
- extensionRoot,
132
- reloadPort,
133
- signal,
134
- rootDir = process.cwd(),
135
- }) {
136
- signal?.throwIfAborted();
137
- const { devExtensionDir, extensionDir } = getProjectPaths(rootDir, extensionName, extensionRoot);
138
- const relevantExtensionFiles = getRelevantExtensionFiles(rootDir, extensionName, extensionRoot);
139
- assertProjectOutput(rootDir, devExtensionDir);
140
- const appOrigin = parseAppUrl(appUrl);
141
- await rm(devExtensionDir, { recursive: true, force: true });
142
- await mkdir(devExtensionDir, { recursive: true });
143
-
144
- for (const fileName of relevantExtensionFiles) {
145
- signal?.throwIfAborted();
146
- if (fileName === "manifest.json") continue;
147
- await copyExtensionEntry(getRelevantExtensionSourcePath(rootDir, extensionName, fileName, extensionRoot), path.join(devExtensionDir, fileName));
148
- }
149
-
150
- signal?.throwIfAborted();
151
- const sourceManifest = JSON.parse(await readFile(path.join(extensionDir, "manifest.json"), "utf8"));
152
- const devManifest = {
153
- ...sourceManifest,
154
- permissions: addUniqueItems(sourceManifest.permissions, ["tabs"]),
155
- host_permissions: addUniqueItems(sourceManifest.host_permissions, ["<all_urls>", `${appOrigin}/*`]),
156
- optional_host_permissions: [],
157
- ...(reloadPort === undefined ? {} : { background: { service_worker: "custom-sidebar-background-dev.js" } }),
158
- };
159
-
160
- await writeFile(path.join(devExtensionDir, "manifest.json"), `${JSON.stringify(devManifest, null, 2)}\n`, "utf8");
161
- const copiedSidePanelPath = path.join(devExtensionDir, "side-panel.html");
162
- const copiedSidePanelHtml = await readFileIfExists(copiedSidePanelPath);
163
- if (copiedSidePanelHtml && reloadPort !== undefined) {
164
- await writeFile(copiedSidePanelPath, injectDevSidePanelReloadClient(copiedSidePanelHtml), "utf8");
165
- }
166
- await writeFile(
167
- path.join(devExtensionDir, "link-light-extension-config.js"),
168
- `globalThis.LINK_LIGHT_CONFIG = ${JSON.stringify({ origin: appOrigin })};\n`,
169
- "utf8",
170
- );
171
- const buildLabel = (await getExtensionLaunchSignature(rootDir, [extensionName], extensionRoot)).slice(0, 12);
172
- if (reloadPort !== undefined) {
173
- if (!Number.isInteger(reloadPort) || reloadPort < 1 || reloadPort > 65535) throw new Error("INVALID_EXTENSION_RELOAD_PORT");
174
- await writeFile(
175
- path.join(devExtensionDir, "custom-sidebar-background-dev.js"),
176
- `importScripts("link-light-extension-config.js", "custom-sidebar-background.js", "${devReloadClientFileName}");\n`,
177
- "utf8",
178
- );
179
- await writeFile(path.join(devExtensionDir, devReloadClientFileName), buildDevReloadClient({ appOrigin, reloadPort }), "utf8");
180
- await writeFile(
181
- path.join(devExtensionDir, devSidePanelReloadClientFileName),
182
- buildDevSidePanelReloadClient({ buildLabel, reloadPort }),
183
- "utf8",
184
- );
185
- }
186
- signal?.throwIfAborted();
187
- return { buildLabel, devExtensionDir };
188
- }
189
-
190
- export async function runChromeExtensionDev({
191
- argv = process.argv.slice(2),
192
- env = process.env,
193
- installRunner = spawnSync,
194
- chromeInstaller = installChromeForTestingForDev,
195
- reloadServerFactory = createDevReloadServer,
196
- signal,
197
- logger = console.log,
198
- runner = spawn,
199
- rootDir = process.cwd(),
200
- platform = process.platform,
201
- watcherFactory = watch,
202
- } = {}) {
203
- signal?.throwIfAborted();
204
- const withNext = argv.includes("--with-next") && !argv.includes("--no-next");
205
- const watchExtension = argv.includes("--watch-extension") && !argv.includes("--no-watch-extension");
206
- if (withNext) throw new Error("RETIRED_ROOT_EXTENSION_HOST");
207
- if (!getArgValue(argv, "--app-url") && !env.LINK_LIGHT_EXTENSION_APP_URL) {
208
- throw new Error("LEGACY_EXTENSION_BACKEND_REQUIRED");
209
- }
210
- const appUrl = getRequestedAppUrl(argv, env);
211
- const extensionRoot = assertExtensionRoot(rootDir, getArgValue(argv, "--extension-root"));
212
- const extensionNames = getRequestedExtensions(argv, rootDir);
213
- const profileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot);
214
-
215
- await mkdir(path.dirname(profileDir), { recursive: true });
216
-
217
- signal?.throwIfAborted();
218
- if (argv.includes("--reset-profile")) {
219
- await resetChromeProfile({ extensionNames, rootDir, extensionRoot });
220
- logger(`Reset Chrome extension debug profile: ${profileDir}`);
221
- }
222
-
223
- const preparedProfile = await ensureFreshChromeProfileForExtension({ extensionNames, logger, rootDir, extensionRoot });
224
- signal?.throwIfAborted();
225
- const closers = [];
226
- let closePromise;
227
- const close = () => closePromise ??= (async () => {
228
- const failures = [];
229
- for (const closer of closers.toReversed()) {
230
- try { await closer(); } catch (error) { failures.push(error); }
231
- }
232
- if (failures.length) throw new AggregateError(failures, "Extension companion cleanup failed.");
233
- })();
234
- try {
235
- if (watchExtension) {
236
- const reloadServer = await reloadServerFactory({ logger });
237
- closers.push(async () => reloadServer.close());
238
- signal?.throwIfAborted();
239
- logger(
240
- "Extension watch updates the explicit source root and regenerates dev wrappers; restart this companion after updating its installed tooling package.",
241
- );
242
- for (const extensionName of extensionNames) {
243
- await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
244
- signal?.throwIfAborted();
245
- const extensionWatcher = createExtensionFileWatcher({
246
- logger,
247
- rootDir,
248
- extensionName,
249
- extensionRoot,
250
- watcherFactory,
251
- onChange: async () => {
252
- const prepared = await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
253
- logger(`Regenerated Link Light dev wrapper for ${extensionName}: ${prepared.buildLabel}.`);
254
- reloadServer.broadcastReload();
255
- logger(`Notified Chrome to reload Link Light dev extension: ${extensionName}.`);
256
- },
257
- });
258
- closers.push(async () => extensionWatcher.close());
259
- }
260
- }
261
-
262
- if (!watchExtension) {
263
- for (const extensionName of extensionNames) await prepareDevExtension({ appUrl, extensionName, extensionRoot, rootDir, signal });
264
- }
265
- signal?.throwIfAborted();
266
- let config = buildChromeLaunchConfig({ appUrl, argv, env, extensionNames, extensionRoot, platform, profileDir: preparedProfile.profileDir, rootDir });
267
-
268
- if (!config.autoLoadSupported && !argv.includes("--no-auto-install")) {
269
- try {
270
- await chromeInstaller({ env, installRunner, logger, platform, rootDir, signal, stdio: "pipe" });
271
- signal?.throwIfAborted();
272
- const installedChromePath = findLocalChromeForTesting({ rootDir });
273
-
274
- if (installedChromePath) {
275
- config = buildChromeLaunchConfig({
276
- argv,
277
- appUrl,
278
- env: { ...env, CHROME_FOR_TESTING_PATH: installedChromePath },
279
- extensionNames,
280
- extensionRoot,
281
- platform,
282
- profileDir: preparedProfile.profileDir,
283
- rootDir,
284
- });
285
- }
286
- } catch (error) {
287
- if (signal?.aborted) throw error;
288
- logger(
289
- `Chrome for Testing auto-install failed; continuing with manual extension loading in branded Chrome. ${
290
- error instanceof Error ? error.message : String(error)
291
- }`,
292
- );
293
- }
294
- }
295
-
296
- logger(
297
- `Loading Link Light Chrome extension from: ${extensionNames
298
- .map((extensionName) => getProjectPaths(rootDir, extensionName, extensionRoot).extensionDir)
299
- .join(", ")}`,
300
- );
301
- logger(`Using isolated Chrome profile: ${preparedProfile.profileDir}`);
302
- const pinnedExtensionIds = await pinChromeExtensionsInProfile({
303
- extensionDirs: config.launchExtensionDirs,
304
- platform,
305
- profileDir: preparedProfile.profileDir,
306
- });
307
- signal?.throwIfAborted();
308
- logger(`Pinned Link Light extension toolbar ids in debug profile: ${pinnedExtensionIds.join(", ")}`);
309
-
310
- if (config.autoLoadSupported) {
311
- logger(`Using extension debug browser: ${config.chromePath}`);
312
- } else {
313
- logger("");
314
- logger("This Chrome build will not auto-load unpacked extensions from the command line.");
315
- logger("Chrome 137+ branded builds ignore --load-extension for unpacked extensions.");
316
- logger(`Open the Chrome window that just launched, click "Load unpacked", and select: ${config.manualLoadPath}`);
317
- logger("Automatic Chrome for Testing setup did not produce a usable chrome executable.");
318
- }
319
-
320
- signal?.throwIfAborted();
321
- const child = runner(config.chromePath, config.args, {
322
- detached: true,
323
- stdio: "ignore",
324
- windowsHide: false,
325
- });
326
-
327
- child.unref();
328
-
329
- return {
330
- close,
331
- keepAlive: withNext || watchExtension,
332
- waitForShutdown: () =>
333
- new Promise((resolve) => {
334
- const shutdown = async () => {
335
- process.off("SIGINT", shutdown);
336
- process.off("SIGTERM", shutdown);
337
- await close();
338
- resolve();
339
- };
340
- process.on("SIGINT", shutdown);
341
- process.on("SIGTERM", shutdown);
342
- }),
343
- };
344
- } catch (error) {
345
- try { await close(); } catch (cleanupError) {
346
- throw new AggregateError([error, cleanupError], "Extension startup and cleanup failed.");
347
- }
348
- throw error;
349
- }
350
- }
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { watch } from "node:fs";
3
+ import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { assertExtensionRoot, assertProjectOutput, defaultDevUrl, devReloadClientFileName, devSidePanelReloadClientFileName, getArgValue, getProfileDirForExtensions, getProjectPaths, getRelevantExtensionFiles, getRelevantExtensionSourcePath, getRequestedAppUrl, getRequestedExtensions, parseAppUrl } from "./cli.mjs";
6
+ import { buildChromeLaunchConfig, findLocalChromeForTesting } from "./chrome-discovery.mjs";
7
+ import { installChromeForTestingForDev } from "./chrome-for-testing.mjs";
8
+ import { ensureFreshChromeProfileForExtension, getExtensionLaunchSignature, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.mjs";
9
+ import { createDevReloadServer } from "./reload-server.mjs";
10
+ import { createExtensionFileWatcher } from "./watcher.mjs";
11
+
12
+ export async function readFileIfExists(filePath) {
13
+ try {
14
+ const fileStats = await stat(filePath);
15
+ if (fileStats.isDirectory()) {
16
+ const entries = await readdir(filePath);
17
+ const snapshots = await Promise.all(
18
+ entries
19
+ .toSorted()
20
+ .map(async (entry) => `${entry}\0${await readFileIfExists(path.join(filePath, entry))}`),
21
+ );
22
+ return snapshots.join("\0");
23
+ }
24
+
25
+ return await readFile(filePath, "utf8");
26
+ } catch (error) {
27
+ if (error?.code === "ENOENT") {
28
+ return "";
29
+ }
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ export async function copyExtensionEntry(sourcePath, targetPath) {
35
+ try {
36
+ const sourceStats = await stat(sourcePath);
37
+ if (sourceStats.isDirectory()) {
38
+ await cp(sourcePath, targetPath, { recursive: true });
39
+ return;
40
+ }
41
+
42
+ await mkdir(path.dirname(targetPath), { recursive: true });
43
+ await writeFile(targetPath, await readFile(sourcePath));
44
+ } catch (error) {
45
+ if (error?.code === "ENOENT") return;
46
+ throw error;
47
+ }
48
+ }
49
+
50
+ export function addUniqueItems(items, additions) {
51
+ return [...new Set([...(items ?? []), ...additions])];
52
+ }
53
+
54
+ export function buildDevReloadClient({ appOrigin, reloadPort }) {
55
+ return `(() => {
56
+ const appTabUrlPattern = ${JSON.stringify(`${appOrigin}/*`)};
57
+ const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
58
+
59
+ async function injectPageBridgeIntoAppTabs() {
60
+ if (!chrome.tabs?.query || !chrome.scripting?.executeScript) return;
61
+ const tabs = await chrome.tabs.query({ url: appTabUrlPattern });
62
+ await Promise.all(tabs.map(async (tab) => {
63
+ if (!tab?.id) return;
64
+ await chrome.scripting.executeScript({
65
+ target: { tabId: tab.id },
66
+ files: ["page-bridge.js"],
67
+ }).catch(() => null);
68
+ }));
69
+ }
70
+
71
+ function connect() {
72
+ const socket = new WebSocket(reloadSocketUrl);
73
+ socket.addEventListener("message", (event) => {
74
+ try {
75
+ const message = JSON.parse(event.data);
76
+ if (message?.type !== "reload") return;
77
+ chrome.runtime.reload();
78
+ } catch {
79
+ // Ignore malformed dev-server messages.
80
+ }
81
+ });
82
+ socket.addEventListener("close", () => setTimeout(connect, 1000));
83
+ socket.addEventListener("error", () => socket.close());
84
+ }
85
+
86
+ void injectPageBridgeIntoAppTabs();
87
+ connect();
88
+ })();
89
+ `;
90
+ }
91
+
92
+ export function buildDevSidePanelReloadClient({ buildLabel, reloadPort }) {
93
+ return `(() => {
94
+ const marker = document.createElement("div");
95
+ marker.id = "ll-dev-build-marker";
96
+ marker.textContent = ${JSON.stringify(`Dev build ${buildLabel}`)};
97
+ marker.style.cssText = "position:fixed;right:62px;bottom:8px;z-index:2147483647;border:1px solid #99f6e4;border-radius:6px;padding:2px 6px;background:#ecfeff;color:#0f766e;font:11px Arial,sans-serif;";
98
+ document.addEventListener("DOMContentLoaded", () => document.body.append(marker), { once: true });
99
+
100
+ const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
101
+ function connect() {
102
+ const socket = new WebSocket(reloadSocketUrl);
103
+ socket.addEventListener("message", (event) => {
104
+ try {
105
+ const message = JSON.parse(event.data);
106
+ if (message?.type !== "reload") return;
107
+ location.reload();
108
+ } catch {
109
+ // Ignore malformed dev-server messages.
110
+ }
111
+ });
112
+ socket.addEventListener("close", () => setTimeout(connect, 1000));
113
+ socket.addEventListener("error", () => socket.close());
114
+ }
115
+
116
+ connect();
117
+ })();
118
+ `;
119
+ }
120
+
121
+ function injectDevSidePanelReloadClient(html) {
122
+ const scriptTag = ` <script src="${devSidePanelReloadClientFileName}" defer></script>`;
123
+ if (html.includes(devSidePanelReloadClientFileName)) return html;
124
+ if (html.includes(" </body>")) return html.replace(" </body>", `${scriptTag}\n </body>`);
125
+ return `${html}\n${scriptTag}\n`;
126
+ }
127
+
128
+ export async function prepareDevExtension({
129
+ appUrl = defaultDevUrl,
130
+ extensionName,
131
+ extensionRoot,
132
+ reloadPort,
133
+ signal,
134
+ rootDir = process.cwd(),
135
+ }) {
136
+ signal?.throwIfAborted();
137
+ const { devExtensionDir, extensionDir } = getProjectPaths(rootDir, extensionName, extensionRoot);
138
+ const relevantExtensionFiles = getRelevantExtensionFiles(rootDir, extensionName, extensionRoot);
139
+ assertProjectOutput(rootDir, devExtensionDir);
140
+ const appOrigin = parseAppUrl(appUrl);
141
+ await rm(devExtensionDir, { recursive: true, force: true });
142
+ await mkdir(devExtensionDir, { recursive: true });
143
+
144
+ for (const fileName of relevantExtensionFiles) {
145
+ signal?.throwIfAborted();
146
+ if (fileName === "manifest.json") continue;
147
+ await copyExtensionEntry(getRelevantExtensionSourcePath(rootDir, extensionName, fileName, extensionRoot), path.join(devExtensionDir, fileName));
148
+ }
149
+
150
+ signal?.throwIfAborted();
151
+ const sourceManifest = JSON.parse(await readFile(path.join(extensionDir, "manifest.json"), "utf8"));
152
+ const devManifest = {
153
+ ...sourceManifest,
154
+ permissions: addUniqueItems(sourceManifest.permissions, ["tabs"]),
155
+ host_permissions: addUniqueItems(sourceManifest.host_permissions, ["<all_urls>", `${appOrigin}/*`]),
156
+ optional_host_permissions: [],
157
+ ...(reloadPort === undefined ? {} : { background: { service_worker: "custom-sidebar-background-dev.js" } }),
158
+ };
159
+
160
+ await writeFile(path.join(devExtensionDir, "manifest.json"), `${JSON.stringify(devManifest, null, 2)}\n`, "utf8");
161
+ const copiedSidePanelPath = path.join(devExtensionDir, "side-panel.html");
162
+ const copiedSidePanelHtml = await readFileIfExists(copiedSidePanelPath);
163
+ if (copiedSidePanelHtml && reloadPort !== undefined) {
164
+ await writeFile(copiedSidePanelPath, injectDevSidePanelReloadClient(copiedSidePanelHtml), "utf8");
165
+ }
166
+ await writeFile(
167
+ path.join(devExtensionDir, "link-light-extension-config.js"),
168
+ `globalThis.LINK_LIGHT_CONFIG = ${JSON.stringify({ origin: appOrigin })};\n`,
169
+ "utf8",
170
+ );
171
+ const buildLabel = (await getExtensionLaunchSignature(rootDir, [extensionName], extensionRoot)).slice(0, 12);
172
+ if (reloadPort !== undefined) {
173
+ if (!Number.isInteger(reloadPort) || reloadPort < 1 || reloadPort > 65535) throw new Error("INVALID_EXTENSION_RELOAD_PORT");
174
+ await writeFile(
175
+ path.join(devExtensionDir, "custom-sidebar-background-dev.js"),
176
+ `importScripts("link-light-extension-config.js", "custom-sidebar-background.js", "${devReloadClientFileName}");\n`,
177
+ "utf8",
178
+ );
179
+ await writeFile(path.join(devExtensionDir, devReloadClientFileName), buildDevReloadClient({ appOrigin, reloadPort }), "utf8");
180
+ await writeFile(
181
+ path.join(devExtensionDir, devSidePanelReloadClientFileName),
182
+ buildDevSidePanelReloadClient({ buildLabel, reloadPort }),
183
+ "utf8",
184
+ );
185
+ }
186
+ signal?.throwIfAborted();
187
+ return { buildLabel, devExtensionDir };
188
+ }
189
+
190
+ export async function runChromeExtensionDev({
191
+ argv = process.argv.slice(2),
192
+ env = process.env,
193
+ installRunner = spawnSync,
194
+ chromeInstaller = installChromeForTestingForDev,
195
+ reloadServerFactory = createDevReloadServer,
196
+ signal,
197
+ logger = console.log,
198
+ runner = spawn,
199
+ rootDir = process.cwd(),
200
+ platform = process.platform,
201
+ watcherFactory = watch,
202
+ } = {}) {
203
+ signal?.throwIfAborted();
204
+ const withNext = argv.includes("--with-next") && !argv.includes("--no-next");
205
+ const watchExtension = argv.includes("--watch-extension") && !argv.includes("--no-watch-extension");
206
+ if (withNext) throw new Error("RETIRED_ROOT_EXTENSION_HOST");
207
+ if (!getArgValue(argv, "--app-url") && !env.LINK_LIGHT_EXTENSION_APP_URL) {
208
+ throw new Error("LEGACY_EXTENSION_BACKEND_REQUIRED");
209
+ }
210
+ const appUrl = getRequestedAppUrl(argv, env);
211
+ const extensionRoot = assertExtensionRoot(rootDir, getArgValue(argv, "--extension-root"));
212
+ const extensionNames = getRequestedExtensions(argv, rootDir);
213
+ const profileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot);
214
+
215
+ await mkdir(path.dirname(profileDir), { recursive: true });
216
+
217
+ signal?.throwIfAborted();
218
+ if (argv.includes("--reset-profile")) {
219
+ await resetChromeProfile({ extensionNames, rootDir, extensionRoot });
220
+ logger(`Reset Chrome extension debug profile: ${profileDir}`);
221
+ }
222
+
223
+ const preparedProfile = await ensureFreshChromeProfileForExtension({ extensionNames, logger, rootDir, extensionRoot });
224
+ signal?.throwIfAborted();
225
+ const closers = [];
226
+ let closePromise;
227
+ const close = () => closePromise ??= (async () => {
228
+ const failures = [];
229
+ for (const closer of closers.toReversed()) {
230
+ try { await closer(); } catch (error) { failures.push(error); }
231
+ }
232
+ if (failures.length) throw new AggregateError(failures, "Extension companion cleanup failed.");
233
+ })();
234
+ try {
235
+ if (watchExtension) {
236
+ const reloadServer = await reloadServerFactory({ logger });
237
+ closers.push(async () => reloadServer.close());
238
+ signal?.throwIfAborted();
239
+ logger(
240
+ "Extension watch updates the explicit source root and regenerates dev wrappers; restart this companion after updating its installed tooling package.",
241
+ );
242
+ for (const extensionName of extensionNames) {
243
+ await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
244
+ signal?.throwIfAborted();
245
+ const extensionWatcher = createExtensionFileWatcher({
246
+ logger,
247
+ rootDir,
248
+ extensionName,
249
+ extensionRoot,
250
+ watcherFactory,
251
+ onChange: async () => {
252
+ const prepared = await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
253
+ logger(`Regenerated Link Light dev wrapper for ${extensionName}: ${prepared.buildLabel}.`);
254
+ reloadServer.broadcastReload();
255
+ logger(`Notified Chrome to reload Link Light dev extension: ${extensionName}.`);
256
+ },
257
+ });
258
+ closers.push(async () => extensionWatcher.close());
259
+ }
260
+ }
261
+
262
+ if (!watchExtension) {
263
+ for (const extensionName of extensionNames) await prepareDevExtension({ appUrl, extensionName, extensionRoot, rootDir, signal });
264
+ }
265
+ signal?.throwIfAborted();
266
+ let config = buildChromeLaunchConfig({ appUrl, argv, env, extensionNames, extensionRoot, platform, profileDir: preparedProfile.profileDir, rootDir });
267
+
268
+ if (!config.autoLoadSupported && !argv.includes("--no-auto-install")) {
269
+ try {
270
+ await chromeInstaller({ env, installRunner, logger, platform, rootDir, signal, stdio: "pipe" });
271
+ signal?.throwIfAborted();
272
+ const installedChromePath = findLocalChromeForTesting({ rootDir });
273
+
274
+ if (installedChromePath) {
275
+ config = buildChromeLaunchConfig({
276
+ argv,
277
+ appUrl,
278
+ env: { ...env, CHROME_FOR_TESTING_PATH: installedChromePath },
279
+ extensionNames,
280
+ extensionRoot,
281
+ platform,
282
+ profileDir: preparedProfile.profileDir,
283
+ rootDir,
284
+ });
285
+ }
286
+ } catch (error) {
287
+ if (signal?.aborted) throw error;
288
+ logger(
289
+ `Chrome for Testing auto-install failed; continuing with manual extension loading in branded Chrome. ${
290
+ error instanceof Error ? error.message : String(error)
291
+ }`,
292
+ );
293
+ }
294
+ }
295
+
296
+ logger(
297
+ `Loading Link Light Chrome extension from: ${extensionNames
298
+ .map((extensionName) => getProjectPaths(rootDir, extensionName, extensionRoot).extensionDir)
299
+ .join(", ")}`,
300
+ );
301
+ logger(`Using isolated Chrome profile: ${preparedProfile.profileDir}`);
302
+ const pinnedExtensionIds = await pinChromeExtensionsInProfile({
303
+ extensionDirs: config.launchExtensionDirs,
304
+ platform,
305
+ profileDir: preparedProfile.profileDir,
306
+ });
307
+ signal?.throwIfAborted();
308
+ logger(`Pinned Link Light extension toolbar ids in debug profile: ${pinnedExtensionIds.join(", ")}`);
309
+
310
+ if (config.autoLoadSupported) {
311
+ logger(`Using extension debug browser: ${config.chromePath}`);
312
+ } else {
313
+ logger("");
314
+ logger("This Chrome build will not auto-load unpacked extensions from the command line.");
315
+ logger("Chrome 137+ branded builds ignore --load-extension for unpacked extensions.");
316
+ logger(`Open the Chrome window that just launched, click "Load unpacked", and select: ${config.manualLoadPath}`);
317
+ logger("Automatic Chrome for Testing setup did not produce a usable chrome executable.");
318
+ }
319
+
320
+ signal?.throwIfAborted();
321
+ const child = runner(config.chromePath, config.args, {
322
+ detached: true,
323
+ stdio: "ignore",
324
+ windowsHide: false,
325
+ });
326
+
327
+ child.unref();
328
+
329
+ return {
330
+ close,
331
+ keepAlive: withNext || watchExtension,
332
+ waitForShutdown: () =>
333
+ new Promise((resolve) => {
334
+ const shutdown = async () => {
335
+ process.off("SIGINT", shutdown);
336
+ process.off("SIGTERM", shutdown);
337
+ await close();
338
+ resolve();
339
+ };
340
+ process.on("SIGINT", shutdown);
341
+ process.on("SIGTERM", shutdown);
342
+ }),
343
+ };
344
+ } catch (error) {
345
+ try { await close(); } catch (cleanupError) {
346
+ throw new AggregateError([error, cleanupError], "Extension startup and cleanup failed.");
347
+ }
348
+ throw error;
349
+ }
350
+ }