extension 3.12.0 → 3.12.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.
Files changed (86) hide show
  1. package/README.md +1 -1
  2. package/dist/656.cjs +2481 -0
  3. package/dist/859.cjs +1932 -0
  4. package/dist/browser/browsers-lib/banner.d.ts +37 -0
  5. package/dist/browser/browsers-lib/constants.d.ts +2 -0
  6. package/dist/browser/browsers-lib/content-script-contracts.d.ts +2 -0
  7. package/dist/browser/browsers-lib/content-script-targets.d.ts +33 -0
  8. package/dist/browser/browsers-lib/html-merge.d.ts +1 -0
  9. package/dist/browser/browsers-lib/instance-registry.d.ts +8 -0
  10. package/dist/browser/browsers-lib/messages.d.ts +208 -0
  11. package/dist/browser/browsers-lib/output-binaries-resolver.d.ts +5 -0
  12. package/dist/browser/browsers-lib/ready-message.d.ts +1 -0
  13. package/dist/browser/browsers-lib/runtime-options.d.ts +12 -0
  14. package/dist/browser/browsers-lib/shared-utils.d.ts +11 -0
  15. package/dist/browser/browsers-types.d.ts +270 -0
  16. package/dist/browser/index.d.ts +74 -0
  17. package/dist/browser/run-chromium/chromium-context/index.d.ts +20 -0
  18. package/dist/browser/run-chromium/chromium-launch/browser-config.d.ts +4 -0
  19. package/dist/browser/run-chromium/chromium-launch/dry-run.d.ts +1 -0
  20. package/dist/browser/run-chromium/chromium-launch/extension-output-path.d.ts +8 -0
  21. package/dist/browser/run-chromium/chromium-launch/index.d.ts +31 -0
  22. package/dist/browser/run-chromium/chromium-launch/master-preferences.d.ts +163 -0
  23. package/dist/browser/run-chromium/chromium-launch/process-handlers.d.ts +3 -0
  24. package/dist/browser/run-chromium/chromium-launch/setup-cdp-after-launch.d.ts +3 -0
  25. package/dist/browser/run-chromium/chromium-launch/wsl-support.d.ts +15 -0
  26. package/dist/browser/run-chromium/chromium-source-inspection/cdp-client.d.ts +57 -0
  27. package/dist/browser/run-chromium/chromium-source-inspection/cdp-extension-controller/connect.d.ts +2 -0
  28. package/dist/browser/run-chromium/chromium-source-inspection/cdp-extension-controller/derive-id.d.ts +2 -0
  29. package/dist/browser/run-chromium/chromium-source-inspection/cdp-extension-controller/ensure.d.ts +6 -0
  30. package/dist/browser/run-chromium/chromium-source-inspection/cdp-extension-controller/index.d.ts +58 -0
  31. package/dist/browser/run-chromium/chromium-source-inspection/cdp-extension-controller/logging.d.ts +7 -0
  32. package/dist/browser/run-chromium/chromium-source-inspection/discovery.d.ts +2 -0
  33. package/dist/browser/run-chromium/chromium-source-inspection/extensions.d.ts +9 -0
  34. package/dist/browser/run-chromium/chromium-source-inspection/page.d.ts +45 -0
  35. package/dist/browser/run-chromium/chromium-source-inspection/ws.d.ts +2 -0
  36. package/dist/browser/run-chromium/chromium-types.d.ts +65 -0
  37. package/dist/browser/run-chromium/manifest-readiness.d.ts +15 -0
  38. package/dist/browser/run-firefox/firefox-context/index.d.ts +24 -0
  39. package/dist/browser/run-firefox/firefox-launch/binary-detector.d.ts +10 -0
  40. package/dist/browser/run-firefox/firefox-launch/browser-config.d.ts +19 -0
  41. package/dist/browser/run-firefox/firefox-launch/dry-run.d.ts +1 -0
  42. package/dist/browser/run-firefox/firefox-launch/index.d.ts +37 -0
  43. package/dist/browser/run-firefox/firefox-launch/master-preferences.d.ts +137 -0
  44. package/dist/browser/run-firefox/firefox-launch/process-handlers.d.ts +2 -0
  45. package/dist/browser/run-firefox/firefox-launch/setup-rdp-after-launch.d.ts +6 -0
  46. package/dist/browser/run-firefox/firefox-launch/wsl-support.d.ts +15 -0
  47. package/dist/browser/run-firefox/firefox-source-inspection/rdp-extension-controller/index.d.ts +38 -0
  48. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/addons-install.d.ts +10 -0
  49. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/addons.d.ts +1 -0
  50. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/evaluate.d.ts +18 -0
  51. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/firefox-utils.d.ts +17 -0
  52. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/index.d.ts +38 -0
  53. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/logging.d.ts +11 -0
  54. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/message-utils.d.ts +2 -0
  55. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/messaging-client.d.ts +37 -0
  56. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/moz-id.d.ts +2 -0
  57. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/rdp-api.d.ts +29 -0
  58. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/rdp-wire.d.ts +8 -0
  59. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/source-inspect.d.ts +9 -0
  60. package/dist/browser/run-firefox/firefox-source-inspection/remote-firefox/transport.d.ts +20 -0
  61. package/dist/browser/run-firefox/firefox-types.d.ts +16 -0
  62. package/dist/browser/run-only.d.ts +22 -0
  63. package/dist/cli/cli-lib/extension-develop-runtime.d.ts +9 -0
  64. package/dist/{utils.d.ts → cli/utils.d.ts} +0 -1
  65. package/dist/cli.cjs +9943 -1964
  66. package/package.json +7 -8
  67. package/dist/cli-lib/extension-develop-runtime.d.ts +0 -3
  68. /package/dist/{check-updates.d.ts → cli/check-updates.d.ts} +0 -0
  69. /package/dist/{cli-lib → cli/cli-lib}/manifest-summary.d.ts +0 -0
  70. /package/dist/{cli-lib → cli/cli-lib}/messages.d.ts +0 -0
  71. /package/dist/{cli-lib → cli/cli-lib}/project-profile.d.ts +0 -0
  72. /package/dist/{cli-lib → cli/cli-lib}/telemetry-cli.d.ts +0 -0
  73. /package/dist/{cli-lib → cli/cli-lib}/telemetry.d.ts +0 -0
  74. /package/dist/{cli-lib → cli/cli-lib}/workflow-profile.d.ts +0 -0
  75. /package/dist/{cli-package-json.d.ts → cli/cli-package-json.d.ts} +0 -0
  76. /package/dist/{commands → cli/commands}/build.d.ts +0 -0
  77. /package/dist/{commands → cli/commands}/create.d.ts +0 -0
  78. /package/dist/{commands → cli/commands}/dev-wait.d.ts +0 -0
  79. /package/dist/{commands → cli/commands}/dev.d.ts +0 -0
  80. /package/dist/{commands → cli/commands}/install.d.ts +0 -0
  81. /package/dist/{commands → cli/commands}/preview.d.ts +0 -0
  82. /package/dist/{commands → cli/commands}/start.d.ts +0 -0
  83. /package/dist/{index.d.ts → cli/index.d.ts} +0 -0
  84. /package/dist/{rslib.config.d.ts → cli/rslib.config.d.ts} +0 -0
  85. /package/dist/{utils → cli/utils}/normalize-options.d.ts +0 -0
  86. /package/dist/{vitest.config.d.ts → cli/vitest.config.d.ts} +0 -0
package/dist/859.cjs ADDED
@@ -0,0 +1,1932 @@
1
+ "use strict";
2
+ exports.ids = [
3
+ "859"
4
+ ];
5
+ exports.modules = {
6
+ "../browser/run-chromium/chromium-launch/setup-cdp-after-launch.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
7
+ __webpack_require__.d(__webpack_exports__, {
8
+ setupCdpAfterLaunch: ()=>setupCdpAfterLaunch
9
+ });
10
+ var messages = __webpack_require__("../browser/browsers-lib/messages.ts");
11
+ var shared_utils = __webpack_require__("../browser/browsers-lib/shared-utils.ts");
12
+ var banner = __webpack_require__("../browser/browsers-lib/banner.ts");
13
+ var external_path_ = __webpack_require__("path");
14
+ var external_fs_ = __webpack_require__("fs");
15
+ var content_script_targets = __webpack_require__("../browser/browsers-lib/content-script-targets.ts");
16
+ var content_script_contracts = __webpack_require__("../browser/browsers-lib/content-script-contracts.ts");
17
+ async function deriveExtensionIdFromTargetsHelper(cdp, outPath, maxRetries = 6, backoffMs = 150, profilePath, extensionPaths) {
18
+ let expectedName;
19
+ let expectedVersion;
20
+ let expectedManifestVersion;
21
+ let expectedNameIsMsg = false;
22
+ try {
23
+ const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(outPath, 'manifest.json'), 'utf-8'));
24
+ expectedName = manifest?.name;
25
+ expectedVersion = manifest?.version;
26
+ expectedManifestVersion = manifest?.manifest_version;
27
+ expectedNameIsMsg = 'string' == typeof expectedName && /__MSG_/i.test(expectedName);
28
+ if (expectedNameIsMsg) {
29
+ const defaultLocale = String(manifest?.default_locale || '').trim();
30
+ const msgKeyMatch = String(expectedName || '').match(/__MSG_(.+)__/i);
31
+ const msgKey = msgKeyMatch ? msgKeyMatch[1] : '';
32
+ if (defaultLocale && msgKey) {
33
+ const messagesPath = external_path_.join(outPath, '_locales', defaultLocale, 'messages.json');
34
+ if (external_fs_.existsSync(messagesPath)) {
35
+ const messagesJson = JSON.parse(external_fs_.readFileSync(messagesPath, 'utf-8'));
36
+ const resolved = String(messagesJson?.[msgKey]?.message || '').trim();
37
+ if (resolved) {
38
+ expectedName = resolved;
39
+ expectedNameIsMsg = false;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ } catch {}
45
+ const trimTrailingSep = (p)=>{
46
+ let end = p.length;
47
+ while(end > 0 && ('/' === p[end - 1] || '\\' === p[end - 1]))end--;
48
+ return p.slice(0, end);
49
+ };
50
+ const normalizePath = (p)=>{
51
+ try {
52
+ const resolved = external_path_.resolve(p);
53
+ if (external_fs_.existsSync(resolved)) return trimTrailingSep(external_fs_.realpathSync(resolved));
54
+ return trimTrailingSep(resolved);
55
+ } catch {
56
+ return trimTrailingSep(external_path_.resolve(p));
57
+ }
58
+ };
59
+ const resolvedOutPath = normalizePath(outPath);
60
+ const normalizedCandidates = Array.isArray(extensionPaths) ? extensionPaths.map((p)=>p ? normalizePath(p) : '').filter(Boolean) : [];
61
+ const resolvedCandidates = normalizedCandidates.length ? normalizedCandidates : [
62
+ resolvedOutPath
63
+ ];
64
+ const platformIsCaseInsensitive = 'win32' === process.platform || 'darwin' === process.platform;
65
+ const normalizeForCompare = (p)=>platformIsCaseInsensitive ? p.toLowerCase() : p;
66
+ const matchesAnyCandidate = (p)=>{
67
+ const n = normalizeForCompare(p);
68
+ return resolvedCandidates.some((candidate)=>n === normalizeForCompare(candidate));
69
+ };
70
+ const deriveFromProfile = ()=>{
71
+ if (!profilePath) return null;
72
+ const candidates = [];
73
+ const pushPrefIfExists = (dir)=>{
74
+ const prefPath = external_path_.join(dir, 'Preferences');
75
+ if (external_fs_.existsSync(prefPath)) candidates.push(prefPath);
76
+ };
77
+ try {
78
+ pushPrefIfExists(profilePath);
79
+ pushPrefIfExists(external_path_.join(profilePath, 'Default'));
80
+ const entries = external_fs_.readdirSync(profilePath);
81
+ for (const entry of entries)if (/^Profile\s+\d+$/i.test(entry)) pushPrefIfExists(external_path_.join(profilePath, entry));
82
+ } catch {}
83
+ for (const prefPath of candidates)try {
84
+ if (!external_fs_.existsSync(prefPath)) continue;
85
+ const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
86
+ const settings = prefs?.extensions?.settings;
87
+ if (!settings || 'object' != typeof settings) continue;
88
+ const entries = Object.entries(settings);
89
+ let fallbackId = null;
90
+ for (const [id, info] of entries){
91
+ const storedPath = String(info?.path || '');
92
+ if (!storedPath) continue;
93
+ const normalized = normalizePath(storedPath);
94
+ if (!matchesAnyCandidate(normalized)) continue;
95
+ const manifestName = String(info?.manifest?.name || '');
96
+ const manifestVersion = String(info?.manifest?.version || '');
97
+ if (expectedName && manifestName === expectedName) return id;
98
+ if (expectedVersion && manifestVersion === expectedVersion) return id;
99
+ fallbackId = id;
100
+ }
101
+ if (fallbackId) return fallbackId;
102
+ } catch {}
103
+ return null;
104
+ };
105
+ let retries = 0;
106
+ let deferredFirstEvalId = null;
107
+ let deferredUrlDerivedId = null;
108
+ const hasExpectedManifestIdentity = Boolean(expectedName || expectedVersion || expectedManifestVersion);
109
+ while(retries <= maxRetries){
110
+ try {
111
+ const targets = await cdp.getTargets();
112
+ const profileCandidateId = deriveFromProfile();
113
+ let firstEvalId = null;
114
+ let evalIdCount = 0;
115
+ let urlDerivedId = null;
116
+ for (const t of targets || []){
117
+ const url = String(t?.url || '');
118
+ const type = String(t?.type || '');
119
+ const typeOk = [
120
+ 'service_worker',
121
+ 'background_page',
122
+ 'worker'
123
+ ].includes(type);
124
+ if (!typeOk) continue;
125
+ const urlMatch = url.match(/^chrome-extension:\/\/([^\/]+)/);
126
+ if (!urlDerivedId && urlMatch?.[1]) urlDerivedId = String(urlMatch[1]);
127
+ if (url && !url.startsWith('chrome-extension://')) continue;
128
+ const targetId = t?.targetId;
129
+ if (targetId) try {
130
+ const sessionId = await cdp.attachToTarget(targetId);
131
+ if (!sessionId) continue;
132
+ await cdp.sendCommand('Runtime.enable', {}, sessionId);
133
+ const info = await cdp.evaluate(sessionId, '(()=>{try{const m=chrome.runtime.getManifest?.();return {id:chrome.runtime?.id||"",name:m?.name||"",version:m?.version||"",manifestVersion:m?.manifest_version||0}}catch(_){return null}})()');
134
+ const id = String(info?.id || '').trim();
135
+ if (!id) continue;
136
+ evalIdCount += 1;
137
+ if (!firstEvalId) firstEvalId = id;
138
+ if (profileCandidateId && id === profileCandidateId) return id;
139
+ const gotName = String(info?.name || '');
140
+ const gotVersion = String(info?.version || '');
141
+ const gotManifestVersion = Number(info?.manifestVersion || 0);
142
+ const nameMatches = expectedName && !expectedNameIsMsg ? gotName === expectedName : false;
143
+ const versionMatches = expectedVersion ? gotVersion === expectedVersion : false;
144
+ const manifestVersionMatches = expectedManifestVersion ? gotManifestVersion === expectedManifestVersion : false;
145
+ if (nameMatches && (!profileCandidateId || id === profileCandidateId)) return id;
146
+ if (expectedVersion && versionMatches && (expectedManifestVersion ? manifestVersionMatches : true) && (!profileCandidateId || id === profileCandidateId)) return id;
147
+ } catch {}
148
+ }
149
+ if (1 === evalIdCount && firstEvalId) {
150
+ if (!hasExpectedManifestIdentity) return firstEvalId;
151
+ deferredFirstEvalId = deferredFirstEvalId || firstEvalId;
152
+ }
153
+ if (profileCandidateId) return profileCandidateId;
154
+ if (urlDerivedId) {
155
+ if (!hasExpectedManifestIdentity) return urlDerivedId;
156
+ deferredUrlDerivedId = deferredUrlDerivedId || urlDerivedId;
157
+ }
158
+ } catch {}
159
+ await new Promise((r)=>setTimeout(r, backoffMs));
160
+ retries++;
161
+ }
162
+ return deriveFromProfile() || deferredFirstEvalId || deferredUrlDerivedId;
163
+ }
164
+ var wrapper = __webpack_require__("../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs");
165
+ var external_http_ = __webpack_require__("http");
166
+ var external_net_ = __webpack_require__("net");
167
+ const CDP_HTTP_REQUEST_TIMEOUT_MS = 1200;
168
+ async function getJson(host, port, path) {
169
+ return new Promise((resolve, reject)=>{
170
+ const req = external_http_.request({
171
+ hostname: host,
172
+ port,
173
+ path,
174
+ method: 'GET'
175
+ }, (res)=>{
176
+ let data = '';
177
+ res.on('data', (chunk)=>data += chunk);
178
+ res.on('end', ()=>{
179
+ try {
180
+ resolve(JSON.parse(data));
181
+ } catch (e) {
182
+ reject(new Error(`Failed to parse ${path}: ${e}`));
183
+ }
184
+ });
185
+ });
186
+ req.on('error', (err)=>reject(err));
187
+ req.setTimeout(CDP_HTTP_REQUEST_TIMEOUT_MS, ()=>{
188
+ req.destroy(new Error(`CDP endpoint timed out: ${path}`));
189
+ });
190
+ req.end();
191
+ });
192
+ }
193
+ async function discoverWebSocketDebuggerUrl(host, port, isDev) {
194
+ try {
195
+ const version = await getJson(host, port, '/json/version');
196
+ const wsUrl = 'string' == typeof version?.webSocketDebuggerUrl ? version.webSocketDebuggerUrl : void 0;
197
+ if (wsUrl) {
198
+ if (isDev) console.log(messages.Ter());
199
+ return wsUrl;
200
+ }
201
+ } catch (error) {
202
+ if (isDev) console.warn('[CDP] Failed to read /json/version:', String(error?.message || error));
203
+ }
204
+ const targets = await getJson(host, port, '/json');
205
+ if (isDev) console.log(messages.FFz((targets || []).length || 0));
206
+ const pageTarget = (targets || []).find((target)=>{
207
+ const type = String(target?.type || '');
208
+ const ws = 'string' == typeof target?.webSocketDebuggerUrl ? target.webSocketDebuggerUrl : '';
209
+ return 'page' === type && ws;
210
+ });
211
+ const pageWs = 'string' == typeof pageTarget?.webSocketDebuggerUrl ? pageTarget.webSocketDebuggerUrl : '';
212
+ if (pageWs) {
213
+ if (isDev) console.log(messages.Ter());
214
+ return pageWs;
215
+ }
216
+ throw new Error('No CDP WebSocket URL available');
217
+ }
218
+ async function checkChromeRemoteDebugging(port = 9222) {
219
+ return new Promise((resolve)=>{
220
+ const socket = new external_net_.Socket();
221
+ socket.on('connect', ()=>{
222
+ socket.destroy();
223
+ resolve(true);
224
+ });
225
+ socket.on('error', ()=>{
226
+ resolve(false);
227
+ });
228
+ socket.on('timeout', ()=>{
229
+ socket.destroy();
230
+ resolve(false);
231
+ });
232
+ socket.setTimeout(2000);
233
+ socket.connect(port, 'localhost');
234
+ });
235
+ }
236
+ async function getExtensionInfo(cdp, extensionId) {
237
+ return await cdp.sendCommand('Extensions.getExtensionInfo', {
238
+ extensionId
239
+ });
240
+ }
241
+ async function loadUnpackedExtension(cdp, absPath) {
242
+ const response = await cdp.sendCommand('Extensions.loadUnpacked', {
243
+ extensionPath: absPath,
244
+ options: {
245
+ failOnError: false
246
+ }
247
+ });
248
+ return String(response?.extensionId || '');
249
+ }
250
+ async function unloadExtension(cdp, extensionId) {
251
+ try {
252
+ await cdp.sendCommand('Extensions.unload', {
253
+ extensionId
254
+ });
255
+ return true;
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+ function mergeShadowIntoDocument(mainHTML, shadowContent) {
261
+ try {
262
+ if (!mainHTML) return '';
263
+ const hasRoot = /<div id=(["'])extension-root\1/i.test(mainHTML);
264
+ if (hasRoot) {
265
+ const emptyRoot = /<div id=(["'])extension-root\1[^>]*><\/div>/i;
266
+ const replacedEmpty = mainHTML.replace(emptyRoot, `<div id="extension-root">${shadowContent}</div>`);
267
+ if (replacedEmpty !== mainHTML) return replacedEmpty;
268
+ return mainHTML.replace(/<div id=(["'])extension-root\1[^>]*>[\s\S]*?<\/div>/i, `<div id="extension-root">${shadowContent}</div>`);
269
+ }
270
+ const hostOpen = /(<[^>]*data-extension-root=(["'])true\2[^>]*>)/i;
271
+ if (hostOpen.test(mainHTML)) return mainHTML.replace(hostOpen, `$1<div id="extension-root">${shadowContent}</div>`);
272
+ return mainHTML;
273
+ } catch {
274
+ return mainHTML;
275
+ }
276
+ }
277
+ const CONTENT_ROOT_SELECTOR = '#extension-root,[data-extension-root]:not([data-extension-root="extension-js-devtools"])';
278
+ const NON_DEVTOOLS_CONTENT_ROOT_SELECTOR = '#extension-root,[data-extension-root]:not([data-extension-root="extension-js-devtools"])';
279
+ const EXTENSION_ROOT_META_EXPRESSION = `(() => {
280
+ const readGeneration = (node) => {
281
+ try {
282
+ const raw = node && node.getAttribute
283
+ ? node.getAttribute('data-extjs-reinject-generation')
284
+ : '';
285
+ const parsed = Number(raw);
286
+ return Number.isFinite(parsed) ? parsed : undefined;
287
+ } catch (error) {
288
+ return undefined;
289
+ }
290
+ };
291
+ const normalize = (node) => ({
292
+ tag: node && node.tagName ? String(node.tagName).toLowerCase() : 'unknown',
293
+ id: node && node.id ? String(node.id) : undefined,
294
+ key: node && node.getAttribute ? node.getAttribute('data-extjs-reinject-key') || undefined : undefined,
295
+ generation: readGeneration(node),
296
+ status: node && node.getAttribute ? node.getAttribute('data-extjs-reinject-status') || undefined : undefined,
297
+ build: node && node.getAttribute ? node.getAttribute('data-extjs-reinject-build') || undefined : undefined,
298
+ hasShadowRoot: !!(node && node.shadowRoot),
299
+ hasShadowContent: !!(node && node.shadowRoot && String(node.shadowRoot.innerHTML || '').trim())
300
+ });
301
+ const registry = (typeof globalThis === 'object' && globalThis)
302
+ ? (globalThis.__EXTENSIONJS_DEV_REINJECT__ || {})
303
+ : {};
304
+ const registries = Object.entries(registry)
305
+ .slice(0, 10)
306
+ .map(([key, entry]) => {
307
+ const candidate = entry && typeof entry === 'object' ? entry : {};
308
+ const cleanup = candidate && typeof candidate.cleanup === 'function'
309
+ ? candidate.cleanup
310
+ : (typeof entry === 'function' ? entry : undefined);
311
+ return {
312
+ key,
313
+ generation: typeof candidate.generation === 'number'
314
+ ? candidate.generation
315
+ : (cleanup && typeof cleanup.__extjsGeneration === 'number'
316
+ ? cleanup.__extjsGeneration
317
+ : undefined),
318
+ hasCleanup: typeof cleanup === 'function',
319
+ build: typeof candidate.build === 'string'
320
+ ? candidate.build
321
+ : (cleanup && typeof cleanup.__extjsBuild === 'string'
322
+ ? cleanup.__extjsBuild
323
+ : undefined)
324
+ };
325
+ });
326
+ const pageCandidate = {
327
+ key: document.documentElement.getAttribute('data-extjs-last-reinject-key') || undefined,
328
+ generation: (() => {
329
+ const parsed = Number(document.documentElement.getAttribute('data-extjs-last-reinject-generation') || '');
330
+ return Number.isFinite(parsed) ? parsed : undefined;
331
+ })(),
332
+ status: document.documentElement.getAttribute('data-extjs-last-reinject-status') || undefined,
333
+ build: document.documentElement.getAttribute('data-extjs-last-reinject-build') || undefined
334
+ };
335
+ const roots = Array.from(
336
+ document.querySelectorAll('#extension-root,[data-extension-root]:not([data-extension-root="extension-js-devtools"])')
337
+ )
338
+ .slice(0, 10)
339
+ .map(normalize)
340
+ .filter((entry) =>
341
+ entry.hasShadowRoot ||
342
+ entry.hasShadowContent ||
343
+ typeof entry.key === 'string' ||
344
+ typeof entry.generation === 'number' ||
345
+ typeof entry.status === 'string' ||
346
+ typeof entry.build === 'string'
347
+ )
348
+ .map(({hasShadowRoot, hasShadowContent, ...entry}) => entry);
349
+ const markers = Array.from(
350
+ document.querySelectorAll('[data-extjs-reinject-marker="true"]')
351
+ )
352
+ .slice(0, 10)
353
+ .map(normalize);
354
+ const pageHasBackingEvidence =
355
+ roots.length > 0 ||
356
+ markers.length > 0 ||
357
+ registries.some((entry) =>
358
+ entry.key === pageCandidate.key ||
359
+ typeof entry.generation === 'number' ||
360
+ !!entry.hasCleanup ||
361
+ typeof entry.build === 'string'
362
+ );
363
+ const page = pageHasBackingEvidence ? pageCandidate : undefined;
364
+ const generations = roots
365
+ .concat(markers)
366
+ .map((entry) => entry.generation)
367
+ .concat(typeof page.generation === 'number' ? [page.generation] : [])
368
+ .concat(
369
+ registries
370
+ .map((entry) => entry.generation)
371
+ .filter((value) => typeof value === 'number')
372
+ )
373
+ .filter((value) => typeof value === 'number');
374
+ return {
375
+ rootCount: roots.length,
376
+ markerCount: markers.length,
377
+ latestGeneration: generations.length ? Math.max(...generations) : 0,
378
+ roots,
379
+ markers,
380
+ registries,
381
+ page
382
+ };
383
+ })()`;
384
+ const SHADOW_STYLE_SNAPSHOT_EXPRESSION = `(() => {
385
+ try {
386
+ const hosts = Array.from(document.querySelectorAll('#extension-root,[data-extension-root]:not([data-extension-root="extension-js-devtools"])'));
387
+ if (!hosts.length) return null;
388
+ for (const host of hosts) {
389
+ const sr = host && host.shadowRoot;
390
+ if (!sr) continue;
391
+ const styles = Array.from(sr.querySelectorAll('style')).map((styleEl) => {
392
+ const html = String(styleEl.outerHTML || '');
393
+ const text = String(styleEl.textContent || '');
394
+ return {
395
+ html,
396
+ textLength: text.length,
397
+ textSnippet: text.trim().slice(0, 200)
398
+ };
399
+ });
400
+ return {
401
+ rootMode: 'shadow',
402
+ count: styles.length,
403
+ styles
404
+ };
405
+ }
406
+ return null;
407
+ } catch {
408
+ return null;
409
+ }
410
+ })()`;
411
+ const HAS_VISIBLE_SHADOW_HOST_EXPRESSION = `(() => { try {
412
+ const hosts = Array.from(document.querySelectorAll('#extension-root,[data-extension-root]:not([data-extension-root="extension-js-devtools"])'));
413
+ if (!hosts.length) return false;
414
+ for (const h of hosts) {
415
+ try {
416
+ const sr = h && h.shadowRoot;
417
+ if (sr && (String(sr.innerHTML||'').length > 0)) return true;
418
+ } catch { /* ignore */ }
419
+ }
420
+ return false;
421
+ } catch { return false } })()`;
422
+ async function collectExecutionContexts(cdp, sessionId) {
423
+ const rawCdp = cdp;
424
+ if ('function' != typeof rawCdp.sendCommand || 'function' != typeof rawCdp.onProtocolEvent) return [];
425
+ const contextsById = new Map();
426
+ const unsubscribe = rawCdp.onProtocolEvent((message)=>{
427
+ if (String(message.sessionId || '') !== sessionId) return;
428
+ if ('Runtime.executionContextCreated' !== String(message.method || '')) return;
429
+ const context = message.params?.context;
430
+ const contextId = context?.id;
431
+ if ('number' == typeof contextId) contextsById.set(contextId, context);
432
+ });
433
+ try {
434
+ await rawCdp.sendCommand('Runtime.enable', {}, sessionId, 3000);
435
+ await new Promise((resolve)=>setTimeout(resolve, 100));
436
+ } catch {
437
+ return [];
438
+ } finally{
439
+ unsubscribe();
440
+ }
441
+ return Array.from(contextsById.values());
442
+ }
443
+ async function getIsolatedContextId(cdp, sessionId) {
444
+ const contexts = await collectExecutionContexts(cdp, sessionId);
445
+ const preferredContext = contexts.find((context)=>{
446
+ const auxData = context?.auxData || {};
447
+ return 'isolated' === auxData.type && String(context?.origin || '').startsWith('chrome-extension://');
448
+ });
449
+ if ('number' == typeof preferredContext?.id) return preferredContext.id;
450
+ const fallbackContext = contexts.find((context)=>context?.auxData?.type === 'isolated');
451
+ return 'number' == typeof fallbackContext?.id ? fallbackContext.id : void 0;
452
+ }
453
+ async function evaluateWithContentContext(cdp, sessionId, expression, shouldAccept) {
454
+ let pageResult;
455
+ try {
456
+ pageResult = await cdp.evaluate(sessionId, expression);
457
+ if (shouldAccept(pageResult)) return pageResult;
458
+ } catch {}
459
+ try {
460
+ const isolatedContextId = await getIsolatedContextId(cdp, sessionId);
461
+ if ('number' == typeof isolatedContextId) {
462
+ const isolatedResult = await cdp.evaluateInContext(sessionId, expression, isolatedContextId);
463
+ if (shouldAccept(isolatedResult)) return isolatedResult;
464
+ if (void 0 !== pageResult) return pageResult;
465
+ return isolatedResult;
466
+ }
467
+ } catch {}
468
+ return pageResult;
469
+ }
470
+ function isExtensionRootMetaPayload(value) {
471
+ if (!value || 'object' != typeof value) return false;
472
+ const v = value;
473
+ return 'number' == typeof v.rootCount && 'number' == typeof v.markerCount && 'number' == typeof v.latestGeneration && Array.isArray(v.roots) && Array.isArray(v.markers) && Array.isArray(v.registries);
474
+ }
475
+ async function evaluateExtensionRootMeta(cdp, sessionId) {
476
+ try {
477
+ const payload = await evaluateWithContentContext(cdp, sessionId, EXTENSION_ROOT_META_EXPRESSION, isExtensionRootMetaPayload);
478
+ return payload;
479
+ } catch {
480
+ return;
481
+ }
482
+ }
483
+ async function evaluateShadowStyleSnapshot(cdp, sessionId) {
484
+ try {
485
+ const payload = await evaluateWithContentContext(cdp, sessionId, SHADOW_STYLE_SNAPSHOT_EXPRESSION, (value)=>null === value || 'object' == typeof value && null !== value);
486
+ if (null == payload) return;
487
+ return payload;
488
+ } catch {
489
+ return;
490
+ }
491
+ }
492
+ async function pollForVisibleShadowHostContent(cdp, sessionId, deadlineMs = 4000) {
493
+ const deadline = Date.now() + deadlineMs;
494
+ const started = Date.now();
495
+ while(Date.now() < deadline){
496
+ try {
497
+ const hasRoot = await hasVisibleShadowHostContent(cdp, sessionId);
498
+ if (hasRoot) return;
499
+ } catch {}
500
+ const elapsed = Date.now() - started;
501
+ const delay = elapsed < 1000 ? 150 : 350;
502
+ await new Promise((r)=>setTimeout(r, delay));
503
+ }
504
+ }
505
+ async function hasVisibleShadowHostContent(cdp, sessionId) {
506
+ try {
507
+ const v = await evaluateWithContentContext(cdp, sessionId, HAS_VISIBLE_SHADOW_HOST_EXPRESSION, (value)=>true === value || false === value);
508
+ return true === v;
509
+ } catch {
510
+ return false;
511
+ }
512
+ }
513
+ async function getPageHTML(cdp, sessionId, includeShadow = 'open-only') {
514
+ try {
515
+ await cdp.evaluate(sessionId, 'document.title');
516
+ } catch {}
517
+ const mainHTMLRaw = await cdp.evaluate(sessionId, `(() => {
518
+ try {
519
+ const serialize = () => {
520
+ const doctype = document.doctype
521
+ const dt = doctype
522
+ ? '<!DOCTYPE '
523
+ + doctype.name
524
+ + (doctype.publicId ? ' PUBLIC "' + doctype.publicId + '"' : '')
525
+ + (doctype.systemId ? ' "' + doctype.systemId + '"' : '')
526
+ + '>'
527
+ : ''
528
+ return dt + '\n' + document.documentElement.outerHTML
529
+ }
530
+ return serialize()
531
+ } catch (e) {
532
+ return ''
533
+ }
534
+ })()`);
535
+ const mainHTML = 'string' == typeof mainHTMLRaw ? mainHTMLRaw : String(mainHTMLRaw || '');
536
+ if ('off' === includeShadow) return mainHTML;
537
+ const hasVisibleContentRoot = await evaluateWithContentContext(cdp, sessionId, `(() => {
538
+ try {
539
+ return !!document.querySelector(${JSON.stringify(NON_DEVTOOLS_CONTENT_ROOT_SELECTOR)})
540
+ } catch {
541
+ return false
542
+ }
543
+ })()`, (value)=>'boolean' == typeof value);
544
+ if (!hasVisibleContentRoot) return mainHTML;
545
+ try {
546
+ const mergedHtmlRaw = await evaluateWithContentContext(cdp, sessionId, `(() => { try {
547
+ var cloned = document.documentElement.cloneNode(true);
548
+ var selector = ${JSON.stringify(NON_DEVTOOLS_CONTENT_ROOT_SELECTOR)};
549
+ var s = new XMLSerializer();
550
+ try {
551
+ var liveHosts = Array.from(document.querySelectorAll(selector));
552
+ if (!liveHosts.length) return '';
553
+ var clonedHosts = Array.from(cloned.querySelectorAll(selector));
554
+ if (clonedHosts.length < liveHosts.length) {
555
+ var cloneDoc = cloned.ownerDocument || document;
556
+ var cloneBody = cloned.querySelector('body') || cloned;
557
+ for (var missingIndex = clonedHosts.length; missingIndex < liveHosts.length; missingIndex++) {
558
+ var missingLiveHost = liveHosts[missingIndex];
559
+ if (!missingLiveHost || !missingLiveHost.tagName || !cloneBody || typeof cloneBody.appendChild !== 'function') continue;
560
+ var shell = cloneDoc.createElement(String(missingLiveHost.tagName || 'div').toLowerCase());
561
+ try {
562
+ Array.from(missingLiveHost.attributes || []).forEach(function(attr){
563
+ try { shell.setAttribute(attr.name, attr.value); } catch(_) {}
564
+ });
565
+ } catch(_) {}
566
+ try { cloneBody.appendChild(shell); } catch(_) {}
567
+ clonedHosts.push(shell);
568
+ }
569
+ }
570
+ for (var index = 0; index < liveHosts.length; index++) {
571
+ var host = clonedHosts[index];
572
+ var liveHost = liveHosts[index];
573
+ if (!host || !liveHost || !liveHost.shadowRoot) continue;
574
+ var shadow = Array.from(liveHost.shadowRoot.childNodes).map(function(n){
575
+ try { return s.serializeToString(n) } catch(e){ return '' }
576
+ }).join('');
577
+ if (!shadow) continue;
578
+ try { host.innerHTML = shadow; } catch(e) {}
579
+ }
580
+ } catch(e) {}
581
+ var doctype = document.doctype;
582
+ var dt = doctype ? '<!DOCTYPE ' + doctype.name + (doctype.publicId ? ' PUBLIC \"' + doctype.publicId + '\"' : '') + (doctype.systemId ? ' \"' + doctype.systemId + '\"' : '') + '>' : '';
583
+ return String(dt + '\\n' + (cloned.outerHTML || document.documentElement.outerHTML));
584
+ } catch(e) { try { return String(document.documentElement.outerHTML); } catch(_) { return '' } } })()`, (value)=>'string' == typeof value && /<html[\s>]/i.test(value));
585
+ const mergedHtml = 'string' == typeof mergedHtmlRaw ? mergedHtmlRaw : String(mergedHtmlRaw || '');
586
+ if (mergedHtml && /<html[\s>]/i.test(mergedHtml)) return mergedHtml;
587
+ } catch {}
588
+ let shadowContent = '';
589
+ try {
590
+ shadowContent = await evaluateWithContentContext(cdp, sessionId, `(() => {
591
+ try {
592
+ const hosts = Array.from(document.querySelectorAll(${JSON.stringify(CONTENT_ROOT_SELECTOR)}));
593
+ if (!hosts.length) return '';
594
+ const preferMarkers = ['iskilar_box','content_script','content_title','js-probe'];
595
+ let firstNonEmpty = '';
596
+ for (const host of hosts) {
597
+ try {
598
+ const sr = host && host.shadowRoot;
599
+ if (!sr) continue;
600
+ const html = String(sr.innerHTML || '');
601
+ if (html && html.length) {
602
+ if (preferMarkers.some((m) => html.includes(m))) return html;
603
+ if (!firstNonEmpty) firstNonEmpty = html;
604
+ continue;
605
+ }
606
+ try {
607
+ const parts = Array.from(sr.children)
608
+ .map((n) => (n && n.outerHTML) ? String(n.outerHTML) : '')
609
+ .join('');
610
+ if (parts && parts.length) {
611
+ if (preferMarkers.some((m) => parts.includes(m))) return parts;
612
+ if (!firstNonEmpty) firstNonEmpty = parts;
613
+ }
614
+ } catch { /* ignore */ }
615
+ } catch { /* ignore */ }
616
+ }
617
+ return firstNonEmpty || '';
618
+ } catch { return '' }
619
+ })()`, (value)=>'string' == typeof value && value.trim().length > 0);
620
+ } catch {}
621
+ if (shadowContent) try {
622
+ const sc = 'string' == typeof shadowContent ? shadowContent : String(shadowContent || '');
623
+ return mergeShadowIntoDocument(mainHTML, sc);
624
+ } catch {}
625
+ return mainHTML;
626
+ }
627
+ async function waitForLoadEvent(cdp, sessionId) {
628
+ return new Promise((resolve)=>{
629
+ let resolved = false;
630
+ const listener = (data)=>{
631
+ try {
632
+ const message = JSON.parse(data);
633
+ if ('Page.loadEventFired' === message.method && message.sessionId === sessionId && !resolved) {
634
+ resolved = true;
635
+ resolve();
636
+ }
637
+ } catch {}
638
+ };
639
+ const clientWithHandle = cdp;
640
+ const original = clientWithHandle.handleMessage.bind(cdp);
641
+ clientWithHandle.handleMessage = (data)=>{
642
+ original(data);
643
+ listener(data);
644
+ };
645
+ setTimeout(()=>{
646
+ if (!resolved) {
647
+ resolved = true;
648
+ console.log(messages.Qiq());
649
+ resolve();
650
+ }
651
+ clientWithHandle.handleMessage = original;
652
+ }, 2000);
653
+ });
654
+ }
655
+ async function waitForContentScriptInjection(cdp, sessionId) {
656
+ const deadline = Date.now() + 30000;
657
+ const started = Date.now();
658
+ while(Date.now() < deadline){
659
+ try {
660
+ const injected = await evaluateWithContentContext(cdp, sessionId, `(() => { try {
661
+ const hosts = Array.from(document.querySelectorAll(${JSON.stringify(CONTENT_ROOT_SELECTOR)}));
662
+ if (!hosts.length) return false;
663
+ const markers = ['iskilar_box','content_script','content_title','js-probe'];
664
+ for (const h of hosts) {
665
+ try {
666
+ const sr = h && h.shadowRoot;
667
+ if (!sr) continue;
668
+ const html = String(sr.innerHTML||'');
669
+ if (html.length > 0) return true;
670
+ if (markers.some((m) => html.includes(m))) return true;
671
+ try {
672
+ const parts = Array.from(sr.children).map((n) => (n && n.outerHTML) ? String(n.outerHTML) : '').join('');
673
+ if (parts && parts.length) return true;
674
+ if (markers.some((m) => parts.includes(m))) return true;
675
+ } catch { /* ignore */ }
676
+ } catch { /* ignore */ }
677
+ }
678
+ return false;
679
+ } catch { return false } })()`, (value)=>Boolean(value));
680
+ if (Boolean(injected)) return true;
681
+ } catch {}
682
+ const elapsed = Date.now() - started;
683
+ const delay = elapsed < 2000 ? 150 : 500;
684
+ await new Promise((r)=>setTimeout(r, delay));
685
+ }
686
+ return false;
687
+ }
688
+ function establishBrowserConnection(url, isDev, onMessage, onRejectPending) {
689
+ return new Promise((resolve, reject)=>{
690
+ const ws = new wrapper.Ay(url);
691
+ ws.on('open', ()=>{
692
+ if (isDev) console.log(messages.F1E());
693
+ resolve(ws);
694
+ });
695
+ ws.on('message', (data)=>{
696
+ onMessage(data.toString());
697
+ });
698
+ ws.on('error', (error)=>{
699
+ if (isDev) console.error(messages.fRy(error.message));
700
+ onRejectPending(error.message);
701
+ reject(error);
702
+ });
703
+ ws.on('close', ()=>{
704
+ if (isDev) console.log(messages.hE8());
705
+ onRejectPending('CDP connection closed');
706
+ });
707
+ });
708
+ }
709
+ function _define_property(obj, key, value) {
710
+ if (key in obj) Object.defineProperty(obj, key, {
711
+ value: value,
712
+ enumerable: true,
713
+ configurable: true,
714
+ writable: true
715
+ });
716
+ else obj[key] = value;
717
+ return obj;
718
+ }
719
+ class CDPClient {
720
+ isDev() {
721
+ return 'true' === process.env.EXTENSION_AUTHOR_MODE;
722
+ }
723
+ async connect() {
724
+ return new Promise(async (resolve, reject)=>{
725
+ try {
726
+ this.targetWebSocketUrl = await discoverWebSocketDebuggerUrl(this.host, this.port, this.isDev());
727
+ this.ws = await establishBrowserConnection(this.targetWebSocketUrl, this.isDev(), (data)=>this.handleMessage(data), (reason)=>{
728
+ this.pendingRequests.forEach(({ reject, timeout }, id)=>{
729
+ try {
730
+ reject(new Error(reason));
731
+ } catch (error) {
732
+ if (this.isDev()) {
733
+ const err = error;
734
+ console.warn(messages.r0s(String(err.message || err)));
735
+ }
736
+ }
737
+ if (timeout) clearTimeout(timeout);
738
+ this.pendingRequests.delete(id);
739
+ });
740
+ });
741
+ if (this.isDev()) console.log(messages.M3V(this.host, this.port));
742
+ resolve();
743
+ } catch (error) {
744
+ const err = error;
745
+ reject(new Error(`Failed to connect to CDP: ${err.message || err}`));
746
+ }
747
+ });
748
+ }
749
+ disconnect() {
750
+ if (this.ws) {
751
+ try {
752
+ this.ws.close();
753
+ } catch {}
754
+ this.ws = null;
755
+ }
756
+ }
757
+ isConnected() {
758
+ return !!this.ws && this.ws.readyState === wrapper.Ay.OPEN;
759
+ }
760
+ onProtocolEvent(handler) {
761
+ this.eventCallbacks.add(handler);
762
+ return ()=>{
763
+ this.eventCallbacks.delete(handler);
764
+ };
765
+ }
766
+ handleMessage(data) {
767
+ try {
768
+ const message = JSON.parse(data);
769
+ if (message.id) {
770
+ const pending = this.pendingRequests.get(message.id);
771
+ if (pending) {
772
+ if (pending.timeout) clearTimeout(pending.timeout);
773
+ this.pendingRequests.delete(message.id);
774
+ if (message.error) pending.reject(new Error(JSON.stringify(message.error)));
775
+ else pending.resolve(message.result);
776
+ }
777
+ return;
778
+ }
779
+ if ('Target.attachedToTarget' === message.method) {
780
+ const params = message.params || {};
781
+ if (this.isDev()) console.log(messages.p8m(String(params.sessionId || ''), String(params.targetInfo?.type || '')));
782
+ }
783
+ for (const eventCallback of this.eventCallbacks)eventCallback(message);
784
+ } catch (error) {
785
+ if (this.isDev()) {
786
+ const err = error;
787
+ console.warn(messages.xxG(String(err.message || err)));
788
+ }
789
+ }
790
+ }
791
+ async sendCommand(method, params = {}, sessionId, timeoutMs = 12000) {
792
+ return new Promise((resolve, reject)=>{
793
+ if (!this.ws || this.ws.readyState !== wrapper.Ay.OPEN) return reject(new Error('WebSocket is not open'));
794
+ const id = ++this.messageId;
795
+ const message = {
796
+ id,
797
+ method,
798
+ params
799
+ };
800
+ if (sessionId) message.sessionId = sessionId;
801
+ try {
802
+ const timeout = setTimeout(()=>{
803
+ const pending = this.pendingRequests.get(id);
804
+ if (!pending) return;
805
+ this.pendingRequests.delete(id);
806
+ pending.reject(new Error(`CDP command timed out (${timeoutMs}ms): ${String(pending.method || method)}`));
807
+ }, timeoutMs);
808
+ this.pendingRequests.set(id, {
809
+ resolve,
810
+ reject,
811
+ timeout,
812
+ method
813
+ });
814
+ this.ws.send(JSON.stringify(message));
815
+ } catch (error) {
816
+ const pending = this.pendingRequests.get(id);
817
+ if (pending?.timeout) clearTimeout(pending.timeout);
818
+ this.pendingRequests.delete(id);
819
+ reject(error);
820
+ }
821
+ });
822
+ }
823
+ async getTargets() {
824
+ const response = await this.sendCommand('Target.getTargets');
825
+ return response?.targetInfos || [];
826
+ }
827
+ async getBrowserVersion() {
828
+ const response = await this.sendCommand('Browser.getVersion');
829
+ return response || {};
830
+ }
831
+ async attachToTarget(targetId) {
832
+ const response = await this.sendCommand('Target.attachToTarget', {
833
+ targetId,
834
+ flatten: true
835
+ });
836
+ return response.sessionId || '';
837
+ }
838
+ async enableAutoAttach() {
839
+ await this.sendCommand('Target.setAutoAttach', {
840
+ autoAttach: true,
841
+ waitForDebuggerOnStart: false,
842
+ flatten: true
843
+ });
844
+ }
845
+ async enableRuntimeAndLog(sessionId) {
846
+ await this.sendCommand('Log.enable', {}, sessionId);
847
+ if (sessionId) await this.sendCommand('Runtime.enable', {}, sessionId);
848
+ }
849
+ async navigate(sessionId, url) {
850
+ await this.sendCommand('Page.navigate', {
851
+ url
852
+ }, sessionId);
853
+ }
854
+ async createTarget(url) {
855
+ const res = await this.sendCommand('Target.createTarget', {
856
+ url
857
+ });
858
+ return String(res?.targetId || '');
859
+ }
860
+ async activateTarget(targetId) {
861
+ await this.sendCommand('Target.activateTarget', {
862
+ targetId
863
+ });
864
+ }
865
+ async waitForLoadEvent(sessionId) {
866
+ return waitForLoadEvent(this, sessionId);
867
+ }
868
+ async waitForContentScriptInjection(sessionId) {
869
+ return waitForContentScriptInjection(this, sessionId);
870
+ }
871
+ async getExtensionRootMeta(sessionId) {
872
+ return evaluateExtensionRootMeta(this, sessionId);
873
+ }
874
+ async getShadowStyleSnapshot(sessionId) {
875
+ return evaluateShadowStyleSnapshot(this, sessionId);
876
+ }
877
+ async pollForVisibleShadowHostContent(sessionId, deadlineMs) {
878
+ return pollForVisibleShadowHostContent(this, sessionId, deadlineMs);
879
+ }
880
+ async hasVisibleShadowHostContent(sessionId) {
881
+ return hasVisibleShadowHostContent(this, sessionId);
882
+ }
883
+ async evaluate(sessionId, expression, options) {
884
+ const response = await this.sendCommand('Runtime.evaluate', {
885
+ expression,
886
+ returnByValue: true,
887
+ awaitPromise: options?.awaitPromise === true
888
+ }, sessionId);
889
+ return response.result?.value;
890
+ }
891
+ async evaluateInContext(sessionId, expression, contextId, options) {
892
+ const response = await this.sendCommand('Runtime.evaluate', {
893
+ expression,
894
+ contextId,
895
+ returnByValue: true,
896
+ awaitPromise: options?.awaitPromise === true
897
+ }, sessionId);
898
+ return response.result?.value;
899
+ }
900
+ async getPageHTML(sessionId, includeShadow = 'open-only') {
901
+ return getPageHTML(this, sessionId, includeShadow);
902
+ }
903
+ async closeTarget(targetId) {
904
+ await this.sendCommand('Target.closeTarget', {
905
+ targetId
906
+ });
907
+ }
908
+ async forceReloadExtension(extensionId) {
909
+ const attempts = 8;
910
+ let lastError = null;
911
+ for(let i = 0; i < attempts; i++){
912
+ try {
913
+ const ok = await this.reloadExtensionViaTargetEval(extensionId);
914
+ if (ok) return true;
915
+ } catch (error) {
916
+ lastError = error;
917
+ }
918
+ const backoffMs = Math.min(1200, 150 * (i + 1));
919
+ await new Promise((r)=>setTimeout(r, backoffMs));
920
+ }
921
+ console.warn(messages.ccn(extensionId, lastError?.message || String(lastError || 'runtime.reload failed')));
922
+ return false;
923
+ }
924
+ async getExtensionInfo(extensionId) {
925
+ try {
926
+ return await getExtensionInfo(this, extensionId);
927
+ } catch (error) {
928
+ throw new Error(messages.Z5i(extensionId, error.message));
929
+ }
930
+ }
931
+ async reloadExtensionViaTargetEval(extensionId) {
932
+ try {
933
+ const targets = await this.getTargets();
934
+ const preferredOrder = [
935
+ 'service_worker',
936
+ 'background_page',
937
+ 'worker',
938
+ 'page'
939
+ ];
940
+ for (const type of preferredOrder){
941
+ const matchingTargets = (targets || []).filter((t)=>{
942
+ const url = String(t?.url || '');
943
+ const tt = String(t?.type || '');
944
+ const inExtensionScope = url.startsWith(`chrome-extension://${extensionId}/`);
945
+ return tt === type && inExtensionScope;
946
+ });
947
+ for (const target of matchingTargets){
948
+ const targetId = target?.targetId;
949
+ if (targetId) try {
950
+ const sessionId = await this.attachToTarget(targetId);
951
+ await this.sendCommand('Runtime.enable', {}, sessionId);
952
+ await this.sendCommand('Runtime.evaluate', {
953
+ expression: '(function(){ try { if (!chrome || !chrome.runtime || !chrome.runtime.reload) return false; chrome.runtime.reload(); return true; } catch (error) { return false; } })()',
954
+ returnByValue: true
955
+ }, sessionId);
956
+ return true;
957
+ } catch {}
958
+ }
959
+ }
960
+ return false;
961
+ } catch {
962
+ return false;
963
+ }
964
+ }
965
+ async loadUnpackedExtension(path) {
966
+ try {
967
+ return await loadUnpackedExtension(this, path);
968
+ } catch (error) {
969
+ throw new Error(messages.xlM(path, error.message));
970
+ }
971
+ }
972
+ async unloadExtension(extensionId) {
973
+ try {
974
+ return await unloadExtension(this, extensionId);
975
+ } catch (error) {
976
+ console.error(messages.yEr(extensionId, error.message));
977
+ return false;
978
+ }
979
+ }
980
+ constructor(port = 9222, host = '127.0.0.1'){
981
+ _define_property(this, "port", void 0);
982
+ _define_property(this, "host", void 0);
983
+ _define_property(this, "ws", null);
984
+ _define_property(this, "targetWebSocketUrl", null);
985
+ _define_property(this, "eventCallbacks", new Set());
986
+ _define_property(this, "messageId", 0);
987
+ _define_property(this, "pendingRequests", new Map());
988
+ this.port = port;
989
+ this.host = host;
990
+ }
991
+ }
992
+ function isRecoverableBootstrapError(error) {
993
+ const msg = String(error?.message || error || '').toLowerCase();
994
+ return msg.includes('econnreset') || msg.includes('websocket is not open') || msg.includes('cdp connection closed') || msg.includes('socket hang up') || msg.includes('timed out') || msg.includes('no cdp websocket url');
995
+ }
996
+ async function connectToChromeCdp(cdpPort) {
997
+ let retries = 0;
998
+ const maxRetries = 60;
999
+ const backoffMs = 250;
1000
+ while(retries < maxRetries){
1001
+ const ready = await checkChromeRemoteDebugging(cdpPort);
1002
+ if (ready) break;
1003
+ retries++;
1004
+ await new Promise((r)=>setTimeout(r, backoffMs));
1005
+ }
1006
+ const maxBootstrapAttempts = 4;
1007
+ let lastError = null;
1008
+ for(let attempt = 1; attempt <= maxBootstrapAttempts; attempt++){
1009
+ const cdp = new CDPClient(cdpPort, '127.0.0.1');
1010
+ try {
1011
+ await cdp.connect();
1012
+ await cdp.sendCommand('Target.setDiscoverTargets', {
1013
+ discover: true
1014
+ });
1015
+ await cdp.sendCommand('Target.setAutoAttach', {
1016
+ autoAttach: true,
1017
+ waitForDebuggerOnStart: false,
1018
+ flatten: true
1019
+ });
1020
+ return cdp;
1021
+ } catch (error) {
1022
+ lastError = error;
1023
+ cdp.disconnect();
1024
+ const retryable = isRecoverableBootstrapError(error);
1025
+ const hasMoreAttempts = attempt < maxBootstrapAttempts;
1026
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
1027
+ const base = String(error?.message || error);
1028
+ console.warn(`[CDP] bootstrap attempt ${attempt}/${maxBootstrapAttempts} failed: ${base}`);
1029
+ }
1030
+ if (!retryable || !hasMoreAttempts) throw error;
1031
+ const delayMs = 120 * attempt;
1032
+ await new Promise((r)=>setTimeout(r, delayMs));
1033
+ }
1034
+ }
1035
+ throw lastError instanceof Error ? lastError : new Error('Failed to bootstrap CDP connection');
1036
+ }
1037
+ function readManifestInfo(outPath) {
1038
+ try {
1039
+ const manifestPath = external_path_.join(outPath, 'manifest.json');
1040
+ const manifest = JSON.parse(external_fs_.readFileSync(manifestPath, 'utf-8'));
1041
+ return {
1042
+ name: manifest?.name,
1043
+ version: manifest?.version
1044
+ };
1045
+ } catch {
1046
+ return null;
1047
+ }
1048
+ }
1049
+ function registerAutoEnableLogging(cdp, getExtensionId) {
1050
+ cdp.onProtocolEvent((message)=>{
1051
+ try {
1052
+ if (!message || !message.method) return;
1053
+ if ('Target.attachedToTarget' === message.method) {
1054
+ const params = message.params || {};
1055
+ const targetInfo = params.targetInfo || {};
1056
+ const sessionId = params.sessionId;
1057
+ const url = String(targetInfo.url || '');
1058
+ const type = String(targetInfo.type || '');
1059
+ const extId = getExtensionId();
1060
+ const matchesExtension = !!(extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
1061
+ if (sessionId && matchesExtension) {
1062
+ cdp.sendCommand('Runtime.enable', {}, sessionId).catch(()=>{});
1063
+ cdp.sendCommand('Log.enable', {}, sessionId).catch(()=>{});
1064
+ }
1065
+ } else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
1066
+ if ('1' === String(process.env.EXTENSION_VERBOSE || '').trim()) {
1067
+ const ts = new Date().toISOString();
1068
+ console.log(messages.bvI(ts, message.params));
1069
+ }
1070
+ }
1071
+ } catch (error) {
1072
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.KK1(String(error?.message || error)));
1073
+ }
1074
+ });
1075
+ }
1076
+ function cdp_extension_controller_define_property(obj, key, value) {
1077
+ if (key in obj) Object.defineProperty(obj, key, {
1078
+ value: value,
1079
+ enumerable: true,
1080
+ configurable: true,
1081
+ writable: true
1082
+ });
1083
+ else obj[key] = value;
1084
+ return obj;
1085
+ }
1086
+ class CDPExtensionController {
1087
+ async connect() {
1088
+ if (this.cdp) return;
1089
+ await this.connectFreshClient();
1090
+ }
1091
+ async ensureLoaded() {
1092
+ if (!this.cdp) throw new Error('CDP not connected');
1093
+ const exists = external_fs_.existsSync(this.outPath);
1094
+ if (!exists) throw new Error(`Output path not found: ${this.outPath}`);
1095
+ if (!this.extensionId) {
1096
+ const id = await this.deriveExtensionIdFromTargets();
1097
+ if (id) this.extensionId = id;
1098
+ }
1099
+ if (this.extensionId) {
1100
+ const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
1101
+ if (false === belongsToOutPath) this.extensionId = null;
1102
+ }
1103
+ if (this.extensionId) try {
1104
+ let info = null;
1105
+ try {
1106
+ info = await this.cdp.getExtensionInfo(this.extensionId);
1107
+ } catch {}
1108
+ if (!info) {
1109
+ const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
1110
+ return {
1111
+ extensionId: this.extensionId,
1112
+ name: manifest.name,
1113
+ version: manifest.version
1114
+ };
1115
+ }
1116
+ return {
1117
+ extensionId: this.extensionId,
1118
+ name: info?.extensionInfo?.name,
1119
+ version: info?.extensionInfo?.version
1120
+ };
1121
+ } catch {}
1122
+ try {
1123
+ if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(20, 200);
1124
+ if (!this.extensionId) throw new Error('Failed to determine extension ID via CDP');
1125
+ await this.enableLogging();
1126
+ let name;
1127
+ let version;
1128
+ try {
1129
+ const info = await this.cdp.getExtensionInfo(this.extensionId);
1130
+ name = info?.extensionInfo?.name;
1131
+ version = info?.extensionInfo?.version;
1132
+ } catch (error) {
1133
+ try {
1134
+ const manifest = readManifestInfo(this.outPath);
1135
+ name = String(manifest?.name || '') || void 0;
1136
+ version = String(manifest?.version || '') || void 0;
1137
+ } catch (e2) {
1138
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] Fallback manifest read failed:', String(e2?.message || e2));
1139
+ }
1140
+ }
1141
+ return {
1142
+ extensionId: this.extensionId,
1143
+ name,
1144
+ version
1145
+ };
1146
+ } catch (error) {
1147
+ throw new Error(`Failed to load extension from ${external_path_.resolve(this.outPath)}: ${String(error.message || error)}`);
1148
+ }
1149
+ }
1150
+ async deriveExtensionIdFromTargets(maxRetries = 20, backoffMs = 200) {
1151
+ if (!this.cdp) return null;
1152
+ return await deriveExtensionIdFromTargetsHelper(this.cdp, this.outPath, maxRetries, backoffMs, this.profilePath, this.extensionPaths);
1153
+ }
1154
+ normalizePath(input) {
1155
+ try {
1156
+ return external_fs_.realpathSync(external_path_.resolve(input));
1157
+ } catch {
1158
+ return external_path_.resolve(input);
1159
+ }
1160
+ }
1161
+ extensionIdBelongsToOutPath(extensionId) {
1162
+ if (!this.profilePath || !extensionId) return null;
1163
+ const prefCandidates = [];
1164
+ const addPrefCandidate = (dir)=>{
1165
+ const prefPath = external_path_.join(dir, 'Preferences');
1166
+ if (external_fs_.existsSync(prefPath)) prefCandidates.push(prefPath);
1167
+ };
1168
+ try {
1169
+ addPrefCandidate(this.profilePath);
1170
+ addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
1171
+ for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
1172
+ } catch {}
1173
+ if (0 === prefCandidates.length) return null;
1174
+ const normalizedOutPath = this.normalizePath(this.outPath);
1175
+ for (const prefPath of prefCandidates)try {
1176
+ const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
1177
+ const settings = prefs?.extensions?.settings;
1178
+ const info = settings?.[extensionId];
1179
+ const storedPath = String(info?.path || '');
1180
+ if (!storedPath) continue;
1181
+ return this.normalizePath(storedPath) === normalizedOutPath;
1182
+ } catch {}
1183
+ return null;
1184
+ }
1185
+ getDeveloperModeStatus() {
1186
+ if (!this.profilePath) return 'unknown';
1187
+ const prefCandidates = [];
1188
+ const seen = new Set();
1189
+ const addPrefCandidate = (dir)=>{
1190
+ const prefPath = external_path_.join(dir, 'Preferences');
1191
+ if (!external_fs_.existsSync(prefPath)) return;
1192
+ const dedupeKey = external_path_.resolve(prefPath);
1193
+ if (seen.has(dedupeKey)) return;
1194
+ seen.add(dedupeKey);
1195
+ prefCandidates.push(prefPath);
1196
+ };
1197
+ try {
1198
+ addPrefCandidate(this.profilePath);
1199
+ addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
1200
+ for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
1201
+ } catch {}
1202
+ for (const prefPath of prefCandidates)try {
1203
+ const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
1204
+ const uiFlag = prefs?.extensions?.ui?.developer_mode;
1205
+ if ('boolean' == typeof uiFlag) return uiFlag ? 'enabled' : 'disabled';
1206
+ const legacyFlag = prefs?.extensions?.developer_mode;
1207
+ if ('boolean' == typeof legacyFlag) return legacyFlag ? 'enabled' : 'disabled';
1208
+ } catch {}
1209
+ return 'unknown';
1210
+ }
1211
+ getLastRuntimeReinjectionReport() {
1212
+ return this.lastRuntimeReinjectionReport;
1213
+ }
1214
+ async reloadMatchingTabsForContentScripts(rules, options = {}) {
1215
+ if (!this.cdp || 0 === rules.length) return 0;
1216
+ let reinjectedTabs = 0;
1217
+ const targets = await this.cdp.getTargets();
1218
+ for (const target of targets || []){
1219
+ const targetType = String(target?.type || '');
1220
+ const targetId = String(target?.targetId || '');
1221
+ const targetUrl = String(target?.url || '');
1222
+ if ('page' !== targetType || !targetId || !targetUrl) continue;
1223
+ const matchingRules = rules.filter((rule)=>(0, content_script_targets.lM)(targetUrl, [
1224
+ rule
1225
+ ]));
1226
+ if (0 !== matchingRules.length) try {
1227
+ const sessionId = await this.cdp.attachToTarget(targetId);
1228
+ let reinjected = false;
1229
+ if (options.preferPageReload) reinjected = await this.reloadPageTarget(sessionId);
1230
+ else {
1231
+ for (const [index, rule] of matchingRules.entries()){
1232
+ const didReinject = await this.reinjectContentScriptRule(sessionId, rule, options.allowCoarseCleanup ?? 0 === index, options.sourceOverridesByBundleId);
1233
+ reinjected = reinjected || didReinject;
1234
+ }
1235
+ if (!reinjected) reinjected = await this.reloadPageTarget(sessionId);
1236
+ }
1237
+ if (reinjected) reinjectedTabs += 1;
1238
+ } catch (error) {
1239
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] Failed to reinject content scripts into ${targetUrl}: ${String(error?.message || error)}`);
1240
+ }
1241
+ }
1242
+ return reinjectedTabs;
1243
+ }
1244
+ async reinjectMatchingTabsViaExtensionRuntime(rules) {
1245
+ if (!this.cdp || 0 === rules.length) {
1246
+ this.lastRuntimeReinjectionReport = {
1247
+ phase: 'skipped',
1248
+ reason: 'missing_cdp_or_rules',
1249
+ hasCdp: !!this.cdp,
1250
+ ruleCount: rules.length
1251
+ };
1252
+ return 0;
1253
+ }
1254
+ const targets = await this.cdp.getTargets();
1255
+ const matchingUrlsByRule = new Map();
1256
+ for (const target of targets || []){
1257
+ const targetType = String(target?.type || '');
1258
+ const targetUrl = String(target?.url || '');
1259
+ if ('page' === targetType && targetUrl) for (const rule of rules){
1260
+ if (!(0, content_script_targets.lM)(targetUrl, [
1261
+ rule
1262
+ ])) continue;
1263
+ const urls = matchingUrlsByRule.get(rule.index) || new Set();
1264
+ urls.add(targetUrl);
1265
+ matchingUrlsByRule.set(rule.index, urls);
1266
+ }
1267
+ }
1268
+ const payload = rules.map((rule)=>{
1269
+ const jsPath = (0, content_script_targets.nG)(this.outPath, rule.index, 'js');
1270
+ const cssPath = (0, content_script_targets.nG)(this.outPath, rule.index, 'css');
1271
+ if (!jsPath || !external_fs_.existsSync(jsPath)) return null;
1272
+ const jsFile = external_path_.relative(this.outPath, jsPath).replace(/\\/g, '/');
1273
+ const cssFile = cssPath && external_fs_.existsSync(cssPath) ? external_path_.relative(this.outPath, cssPath).replace(/\\/g, '/') : null;
1274
+ const jsSource = external_fs_.readFileSync(jsPath, 'utf-8');
1275
+ const buildTokenMatch = jsSource.match(/__EXTENSIONJS_REINJECT_BUILD_TOKEN\s*=\s*"([^"]+)"/);
1276
+ const proofMatch = jsSource.match(/extjs-chromium-live-content-css-modules:script-primary-\d+/) || jsSource.match(/Live Update Proof [A-Za-z0-9_-]+/);
1277
+ return {
1278
+ index: rule.index,
1279
+ world: rule.world,
1280
+ matches: [
1281
+ ...rule.matches
1282
+ ],
1283
+ urls: Array.from(matchingUrlsByRule.get(rule.index) || []).sort(),
1284
+ jsFile,
1285
+ cssFile,
1286
+ buildToken: buildTokenMatch?.[1] || null,
1287
+ proofMarker: proofMatch?.[0] || null
1288
+ };
1289
+ }).filter((entry)=>!!entry && entry.urls.length > 0);
1290
+ if (0 === payload.length) {
1291
+ this.lastRuntimeReinjectionReport = {
1292
+ phase: 'skipped',
1293
+ reason: 'no_payload',
1294
+ ruleCount: rules.length
1295
+ };
1296
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log('[CDP] extension-runtime reinjection skipped: no payload');
1297
+ return 0;
1298
+ }
1299
+ const runtimeTarget = await this.attachToExtensionRuntimeTarget();
1300
+ if (!runtimeTarget) {
1301
+ const targetSummary = (targets || []).map((target)=>({
1302
+ type: String(target?.type || ''),
1303
+ url: String(target?.url || '')
1304
+ })).filter((entry)=>entry.type || entry.url);
1305
+ this.lastRuntimeReinjectionReport = {
1306
+ phase: 'unavailable',
1307
+ reason: 'no_runtime_target',
1308
+ extensionId: this.extensionId,
1309
+ targets: targetSummary
1310
+ };
1311
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] extension-runtime reinjection unavailable: ${JSON.stringify({
1312
+ extensionId: this.extensionId,
1313
+ targets: targetSummary
1314
+ })}`);
1315
+ return 0;
1316
+ }
1317
+ const result = await this.cdp.evaluate(runtimeTarget.sessionId, `(() => (async () => {
1318
+ const payload = ${JSON.stringify(payload)};
1319
+ const chromeRuntime =
1320
+ typeof globalThis === 'object' && globalThis && globalThis.chrome
1321
+ ? globalThis.chrome
1322
+ : null;
1323
+ const runtimeChrome =
1324
+ chromeRuntime &&
1325
+ chromeRuntime.scripting &&
1326
+ chromeRuntime.tabs
1327
+ ? chromeRuntime
1328
+ : null;
1329
+ if (!runtimeChrome) {
1330
+ return {
1331
+ reinjectedTabs: 0,
1332
+ hasRuntime: false,
1333
+ hasChrome: !!chromeRuntime,
1334
+ hasScripting: !!(chromeRuntime && chromeRuntime.scripting),
1335
+ hasTabs: !!(chromeRuntime && chromeRuntime.tabs),
1336
+ entries: payload.length,
1337
+ matches: []
1338
+ };
1339
+ }
1340
+ let reinjectedTabs = 0;
1341
+ const matches = [];
1342
+ for (const entry of payload) {
1343
+ const queriedTabs = await runtimeChrome.tabs.query(
1344
+ entry.matches.length > 0 ? { url: entry.matches } : {}
1345
+ );
1346
+ const matchingTabs = queriedTabs.filter((tab) => {
1347
+ if (!tab || typeof tab.id !== 'number') return false;
1348
+ if (typeof tab.url !== 'string' || !tab.url) return true;
1349
+ return entry.urls.length === 0 || entry.urls.includes(tab.url);
1350
+ });
1351
+ matches.push({
1352
+ index: entry.index,
1353
+ queriedTabs: queriedTabs.length,
1354
+ matchingTabs: matchingTabs.length
1355
+ });
1356
+ for (const tab of matchingTabs) {
1357
+ const target = { tabId: tab.id, allFrames: false };
1358
+ if (entry.cssFile) {
1359
+ try {
1360
+ await runtimeChrome.scripting.insertCSS({
1361
+ target,
1362
+ files: [entry.cssFile]
1363
+ });
1364
+ } catch (error) {}
1365
+ }
1366
+ await runtimeChrome.scripting.executeScript({
1367
+ target,
1368
+ files: [entry.jsFile],
1369
+ world: entry.world === 'main' ? 'MAIN' : 'ISOLATED'
1370
+ });
1371
+ reinjectedTabs += 1;
1372
+ }
1373
+ }
1374
+ return {
1375
+ reinjectedTabs,
1376
+ hasRuntime: true,
1377
+ entries: payload.length,
1378
+ matches
1379
+ };
1380
+ })())()`, {
1381
+ awaitPromise: true
1382
+ });
1383
+ this.lastRuntimeReinjectionReport = {
1384
+ phase: 'evaluated',
1385
+ targetType: runtimeTarget.targetType,
1386
+ targetUrl: runtimeTarget.targetUrl,
1387
+ result: result && 'object' == typeof result ? JSON.parse(JSON.stringify(result)) : result
1388
+ };
1389
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] extension-runtime reinjection result: ${JSON.stringify({
1390
+ targetType: runtimeTarget.targetType,
1391
+ targetUrl: runtimeTarget.targetUrl,
1392
+ result
1393
+ })}`);
1394
+ if ('number' == typeof result) return result;
1395
+ if (result && 'object' == typeof result) {
1396
+ const reinjectedTabs = Number(result.reinjectedTabs);
1397
+ return Number.isFinite(reinjectedTabs) ? reinjectedTabs : 0;
1398
+ }
1399
+ return 0;
1400
+ }
1401
+ async reloadPageTarget(sessionId) {
1402
+ if (!this.cdp) return false;
1403
+ try {
1404
+ await this.cdp.sendCommand('Page.reload', {
1405
+ ignoreCache: true
1406
+ }, sessionId);
1407
+ return true;
1408
+ } catch {
1409
+ return false;
1410
+ }
1411
+ }
1412
+ async hardReload() {
1413
+ if (!this.extensionId) return false;
1414
+ try {
1415
+ if (!this.cdp) await this.connectFreshClient();
1416
+ if (this.cdp && await this.cdp.forceReloadExtension(this.extensionId)) return true;
1417
+ } catch {}
1418
+ try {
1419
+ await this.reconnectForReload();
1420
+ return Boolean(this.cdp && this.extensionId && await this.cdp.forceReloadExtension(this.extensionId));
1421
+ } catch {
1422
+ return false;
1423
+ }
1424
+ }
1425
+ async attachToExtensionRuntimeTarget() {
1426
+ if (!this.cdp) return;
1427
+ if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
1428
+ if (!this.extensionId) return;
1429
+ const extensionOrigin = `chrome-extension://${this.extensionId}/`;
1430
+ for(let attempt = 0; attempt < 20; attempt++){
1431
+ const targets = await this.cdp.getTargets();
1432
+ const runtimeTargets = (targets || []).filter((target)=>{
1433
+ const targetType = String(target?.type || '');
1434
+ const targetId = String(target?.targetId || '');
1435
+ return ('service_worker' === targetType || 'background_page' === targetType || 'worker' === targetType) && !!targetId;
1436
+ });
1437
+ const runtimeTarget = runtimeTargets.find((target)=>String(target?.url || '').startsWith(extensionOrigin)) || runtimeTargets.find((target)=>String(target?.url || '').startsWith('chrome-extension://'));
1438
+ if (runtimeTarget) try {
1439
+ const sessionId = await this.cdp.attachToTarget(String(runtimeTarget.targetId));
1440
+ await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
1441
+ return {
1442
+ sessionId,
1443
+ targetType: String(runtimeTarget?.type || ''),
1444
+ targetUrl: String(runtimeTarget?.url || '')
1445
+ };
1446
+ } catch {}
1447
+ this.extensionId = await this.deriveExtensionIdFromTargets(4, 100) || this.extensionId;
1448
+ await new Promise((resolve)=>setTimeout(resolve, 250));
1449
+ }
1450
+ }
1451
+ async connectFreshClient() {
1452
+ this.cdp = await connectToChromeCdp(this.cdpPort);
1453
+ try {
1454
+ await this.cdp.sendCommand('Target.setDiscoverTargets', {
1455
+ discover: true
1456
+ });
1457
+ await this.cdp.sendCommand('Target.setAutoAttach', {
1458
+ autoAttach: true,
1459
+ waitForDebuggerOnStart: false,
1460
+ flatten: true
1461
+ });
1462
+ } catch (error) {
1463
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.wXK(String(error?.message || error)));
1464
+ }
1465
+ registerAutoEnableLogging(this.cdp, ()=>this.extensionId);
1466
+ }
1467
+ async reconnectForReload() {
1468
+ try {
1469
+ this.cdp?.disconnect?.();
1470
+ } catch {}
1471
+ this.cdp = null;
1472
+ await this.connectFreshClient();
1473
+ try {
1474
+ const derivedExtensionId = await this.deriveExtensionIdFromTargets(10, 150);
1475
+ if (derivedExtensionId) this.extensionId = derivedExtensionId;
1476
+ } catch {}
1477
+ }
1478
+ onProtocolEvent(cb) {
1479
+ if (!this.cdp) throw new Error('CDP not connected');
1480
+ this.cdp.onProtocolEvent((raw)=>{
1481
+ const evt = raw;
1482
+ cb(evt);
1483
+ });
1484
+ }
1485
+ clearProtocolEventHandler() {
1486
+ if (!this.cdp) return;
1487
+ }
1488
+ async enableUnifiedLogging() {
1489
+ if (!this.cdp) return;
1490
+ try {
1491
+ await this.cdp.enableAutoAttach();
1492
+ await this.cdp.enableRuntimeAndLog();
1493
+ try {
1494
+ const targets = await this.cdp.getTargets();
1495
+ for (const t of targets || []){
1496
+ const type = String(t?.type || '');
1497
+ if ('page' === type || 'service_worker' === type || 'background_page' === type || 'worker' === type) {
1498
+ const targetId = String(t?.targetId || '');
1499
+ if (!targetId) continue;
1500
+ const sessionId = await this.cdp.attachToTarget(targetId);
1501
+ await this.cdp.enableRuntimeAndLog(sessionId);
1502
+ }
1503
+ }
1504
+ } catch {}
1505
+ } catch {}
1506
+ }
1507
+ async enableRuntimeForSession(sessionId) {
1508
+ if (!this.cdp) return;
1509
+ try {
1510
+ await this.cdp.enableRuntimeAndLog(sessionId);
1511
+ } catch {}
1512
+ }
1513
+ async enableLogging() {
1514
+ if (!this.cdp) return;
1515
+ try {
1516
+ const extId = this.extensionId;
1517
+ this.onProtocolEvent(async (message)=>{
1518
+ try {
1519
+ if (!message || !message.method) return;
1520
+ if ('Target.attachedToTarget' === message.method) {
1521
+ const params = message.params || {};
1522
+ const targetInfo = params.targetInfo || {
1523
+ url: '',
1524
+ type: ''
1525
+ };
1526
+ const sessionId = params.sessionId;
1527
+ const url = String(targetInfo.url || '');
1528
+ const type = String(targetInfo.type || '');
1529
+ const matchesExtension = !!(this.extensionId && url.includes(`chrome-extension://${this.extensionId}/`) || extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
1530
+ if (sessionId && matchesExtension) {
1531
+ await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
1532
+ await this.cdp.sendCommand('Log.enable', {}, sessionId);
1533
+ }
1534
+ } else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
1535
+ if ('1' === String(process.env.EXTENSION_VERBOSE || '').trim()) {
1536
+ const ts = new Date().toISOString();
1537
+ console.log(messages.bvI(ts, message.params));
1538
+ }
1539
+ }
1540
+ } catch {}
1541
+ });
1542
+ } catch (e) {
1543
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] enableLogging failed:', String(e));
1544
+ }
1545
+ }
1546
+ async getInfoBestEffort() {
1547
+ try {
1548
+ if (!this.cdp) return null;
1549
+ if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(6, 150);
1550
+ if (this.extensionId) {
1551
+ const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
1552
+ if (false === belongsToOutPath) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
1553
+ }
1554
+ if (!this.extensionId) return null;
1555
+ let name;
1556
+ let version;
1557
+ try {
1558
+ const info = await this.cdp.getExtensionInfo(this.extensionId);
1559
+ name = info?.extensionInfo?.name;
1560
+ version = info?.extensionInfo?.version;
1561
+ } catch {
1562
+ try {
1563
+ const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
1564
+ name = manifest?.name;
1565
+ version = manifest?.version;
1566
+ } catch {}
1567
+ }
1568
+ return {
1569
+ extensionId: this.extensionId,
1570
+ name,
1571
+ version
1572
+ };
1573
+ } catch (error) {
1574
+ return null;
1575
+ }
1576
+ }
1577
+ async reinjectContentScriptRule(sessionId, rule, allowCoarseCleanup, sourceOverridesByBundleId) {
1578
+ if (!this.cdp) return false;
1579
+ const bundleId = (0, content_script_contracts.Y)(rule.index);
1580
+ const bundlePath = (0, content_script_targets.nG)(this.outPath, rule.index, 'js');
1581
+ if (!bundlePath || !external_fs_.existsSync(bundlePath)) return false;
1582
+ const sourceOverride = sourceOverridesByBundleId && 'object' == typeof sourceOverridesByBundleId ? sourceOverridesByBundleId[bundleId] : void 0;
1583
+ const source = this.patchReinjectSourceForInvalidatedRuntime('string' == typeof sourceOverride ? sourceOverride : external_fs_.readFileSync(bundlePath, 'utf-8'));
1584
+ const buildTokenMatch = source.match(/__EXTENSIONJS_REINJECT_BUILD_TOKEN\s*=\s*"([^"]+)"/);
1585
+ const proofMatch = source.match(/extjs-chromium-live-content-css-modules:script-primary-\d+/) || source.match(/Live Update Proof [A-Za-z0-9_-]+/);
1586
+ if (!source.trim()) return false;
1587
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] reinject bundle ${bundleId} from ${bundlePath}${proofMatch ? ` (${proofMatch[0]})` : ''} build=${buildTokenMatch?.[1] || '<none>'} sourceOverride=${'string' == typeof sourceOverride}`);
1588
+ const contextId = await this.resolveExecutionContextId(sessionId, rule);
1589
+ if (!contextId) {
1590
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] No execution context found for ${bundleId} (${rule.world})`);
1591
+ return false;
1592
+ }
1593
+ const result = await this.cdp.evaluateInContext(sessionId, this.buildReinjectExpression(bundleId, source, allowCoarseCleanup), contextId);
1594
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] reinject result ${bundleId}: ${JSON.stringify(result)}`);
1595
+ if (result && 'object' == typeof result && 'ok' in result) return false !== result.ok;
1596
+ return true;
1597
+ }
1598
+ buildReinjectExpression(bundleId, source, allowCoarseCleanup) {
1599
+ const annotatedSource = `${source}\n//# sourceURL=extension.js-reinject://${bundleId}.js`;
1600
+ const extensionBase = this.extensionId ? `chrome-extension://${this.extensionId}/` : '';
1601
+ return `(() => {
1602
+ const bundleId = ${JSON.stringify(bundleId)};
1603
+ const source = ${JSON.stringify(annotatedSource)};
1604
+ const extensionBase = ${JSON.stringify(extensionBase)};
1605
+ const rootSelector = '[data-extension-root], #extension-root';
1606
+ const keyedSelector = '[data-extjs-reinject-key="${bundleId}"]';
1607
+ const registry = (typeof globalThis === 'object' && globalThis)
1608
+ ? (globalThis.__EXTENSIONJS_DEV_REINJECT__ || (globalThis.__EXTENSIONJS_DEV_REINJECT__ = {}))
1609
+ : {};
1610
+ const existing = registry[bundleId];
1611
+ const readGeneration = (entry) => {
1612
+ try {
1613
+ if (!entry) return 0;
1614
+ if (typeof entry === 'function' && typeof entry.__extjsGeneration === 'number') {
1615
+ return entry.__extjsGeneration;
1616
+ }
1617
+ if (typeof entry === 'object') {
1618
+ if (typeof entry.__extjsGeneration === 'number') return entry.__extjsGeneration;
1619
+ if (typeof entry.generation === 'number') return entry.generation;
1620
+ if (typeof entry.cleanup === 'function' && typeof entry.cleanup.__extjsGeneration === 'number') {
1621
+ return entry.cleanup.__extjsGeneration;
1622
+ }
1623
+ }
1624
+ } catch (error) {}
1625
+ return 0;
1626
+ };
1627
+ const previousGeneration = readGeneration(existing);
1628
+ try {
1629
+ if (typeof existing === 'function') existing();
1630
+ if (existing && typeof existing.cleanup === 'function') existing.cleanup();
1631
+ } catch (error) {}
1632
+ if (${allowCoarseCleanup ? 'true' : 'false'}) {
1633
+ try {
1634
+ const staleRoots = Array.from(document.querySelectorAll(rootSelector));
1635
+ for (const root of staleRoots) {
1636
+ if (root && typeof root.remove === 'function') root.remove();
1637
+ }
1638
+ } catch (error) {}
1639
+ }
1640
+ const trackedNodes = new Set();
1641
+ const trackNode = (node) => {
1642
+ try {
1643
+ if (!node || typeof Element !== 'function' || !(node instanceof Element)) return;
1644
+ const matchesRoot = typeof node.matches === 'function' && node.matches(rootSelector);
1645
+ if (!matchesRoot) return;
1646
+ trackedNodes.add(node);
1647
+ if (typeof node.setAttribute === 'function') {
1648
+ node.setAttribute('data-extjs-reinject-key', bundleId);
1649
+ }
1650
+ } catch (error) {}
1651
+ };
1652
+ const trackTree = (node) => {
1653
+ trackNode(node);
1654
+ try {
1655
+ if (!node || typeof node.querySelectorAll !== 'function') return;
1656
+ const nested = node.querySelectorAll(rootSelector);
1657
+ for (const nestedNode of nested) trackNode(nestedNode);
1658
+ } catch (error) {}
1659
+ };
1660
+ const observer = typeof MutationObserver === 'function'
1661
+ ? new MutationObserver((mutations) => {
1662
+ for (const mutation of mutations) {
1663
+ const addedNodes = Array.from(mutation.addedNodes || []);
1664
+ for (const addedNode of addedNodes) {
1665
+ trackTree(addedNode);
1666
+ }
1667
+ }
1668
+ })
1669
+ : null;
1670
+ try {
1671
+ if (observer && document && document.documentElement) {
1672
+ observer.observe(document.documentElement, {childList: true, subtree: true});
1673
+ }
1674
+ } catch (error) {}
1675
+ const cleanupTrackedNodes = () => {
1676
+ try {
1677
+ if (observer) observer.disconnect();
1678
+ } catch (error) {}
1679
+ try {
1680
+ const keyedNodes = Array.from(document.querySelectorAll(keyedSelector));
1681
+ for (const keyedNode of keyedNodes) {
1682
+ if (keyedNode && typeof keyedNode.remove === 'function') keyedNode.remove();
1683
+ }
1684
+ } catch (error) {}
1685
+ try {
1686
+ for (const trackedNode of trackedNodes) {
1687
+ if (trackedNode && trackedNode.isConnected && typeof trackedNode.remove === 'function') {
1688
+ trackedNode.remove();
1689
+ }
1690
+ }
1691
+ } catch (error) {}
1692
+ };
1693
+ registry[bundleId] = {
1694
+ cleanup: cleanupTrackedNodes,
1695
+ generation: previousGeneration,
1696
+ __extjsGeneration: previousGeneration
1697
+ };
1698
+ try {
1699
+ if (typeof globalThis === 'object' && globalThis && extensionBase) {
1700
+ globalThis.__EXTJS_EXTENSION_BASE__ = extensionBase;
1701
+ }
1702
+ if (typeof document === 'object' && document && document.documentElement && extensionBase) {
1703
+ document.documentElement.setAttribute('data-extjs-extension-base', extensionBase);
1704
+ }
1705
+ (0, eval)(source);
1706
+ } catch (error) {
1707
+ return {
1708
+ ok: false,
1709
+ error: String((error && error.stack) || (error && error.message) || error || 'unknown'),
1710
+ trackedRoots: trackedNodes.size,
1711
+ existingRootCount: (() => {
1712
+ try { return document.querySelectorAll(rootSelector).length; } catch (innerError) { return -1; }
1713
+ })()
1714
+ };
1715
+ }
1716
+ setTimeout(() => {
1717
+ try {
1718
+ const keyedNodes = Array.from(document.querySelectorAll(keyedSelector));
1719
+ for (const keyedNode of keyedNodes) trackedNodes.add(keyedNode);
1720
+ } catch (error) {}
1721
+ }, 0);
1722
+ setTimeout(() => {
1723
+ try {
1724
+ if (observer) observer.disconnect();
1725
+ } catch (error) {}
1726
+ }, 2000);
1727
+ return {
1728
+ ok: true,
1729
+ trackedRoots: trackedNodes.size,
1730
+ existingRootCount: (() => {
1731
+ try { return document.querySelectorAll(rootSelector).length; } catch (innerError) { return -1; }
1732
+ })(),
1733
+ liveRoots: (() => {
1734
+ try {
1735
+ return Array.from(document.querySelectorAll(rootSelector)).map((node) => ({
1736
+ key: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extjs-reinject-key') || null : null,
1737
+ root: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extension-root') || null : null,
1738
+ build: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extjs-reinject-build') || null : null,
1739
+ text: String(node && node.textContent || '').slice(0, 120)
1740
+ }));
1741
+ } catch (error) {
1742
+ return [];
1743
+ }
1744
+ })(),
1745
+ hasChromeRuntime: (() => {
1746
+ try { return !!(globalThis && globalThis.chrome && globalThis.chrome.runtime); } catch (error) { return false; }
1747
+ })()
1748
+ };
1749
+ })()`;
1750
+ }
1751
+ patchReinjectSourceForInvalidatedRuntime(source) {
1752
+ return source.replace('__webpack_require__.p = __webpack_require__.webExtRt.runtime.getURL("/");', 'try {\n __webpack_require__.p = __webpack_require__.webExtRt.runtime.getURL("/");\n} catch (_extjsRuntimeError) {\n if (__extjsBase) {\n __webpack_require__.p = __extjsBase.replace(/\\/+$/, "/") + String("/").replace(/^\\/+/, "");\n } else {\n __webpack_require__.p = "";\n }\n}');
1753
+ }
1754
+ async resolveExecutionContextId(sessionId, rule) {
1755
+ if (!this.cdp) return;
1756
+ const frameId = await this.getTopFrameId(sessionId);
1757
+ const contexts = await this.collectExecutionContexts(sessionId);
1758
+ if ('main' === rule.world) {
1759
+ const defaultContext = contexts.find((context)=>{
1760
+ const auxData = context?.auxData || {};
1761
+ return 'default' === auxData.type && true === auxData.isDefault && (!frameId || !auxData.frameId || String(auxData.frameId) === frameId);
1762
+ });
1763
+ return 'number' == typeof defaultContext?.id ? defaultContext.id : void 0;
1764
+ }
1765
+ const extensionId = this.extensionId || await this.deriveExtensionIdFromTargets();
1766
+ if (!extensionId) return;
1767
+ const extensionOrigin = `chrome-extension://${extensionId}`;
1768
+ const isolatedContext = contexts.find((context)=>{
1769
+ const auxData = context?.auxData || {};
1770
+ return 'isolated' === auxData.type && String(context?.origin || '') === extensionOrigin && (!frameId || !auxData.frameId || String(auxData.frameId) === frameId);
1771
+ });
1772
+ return 'number' == typeof isolatedContext?.id ? isolatedContext.id : void 0;
1773
+ }
1774
+ async getTopFrameId(sessionId) {
1775
+ if (!this.cdp) return;
1776
+ try {
1777
+ const frameTree = await this.cdp.sendCommand('Page.getFrameTree', {}, sessionId);
1778
+ const frameId = frameTree?.frameTree?.frame?.id;
1779
+ return 'string' == typeof frameId && frameId ? frameId : void 0;
1780
+ } catch {
1781
+ return;
1782
+ }
1783
+ }
1784
+ async collectExecutionContexts(sessionId) {
1785
+ if (!this.cdp) return [];
1786
+ const contextsById = new Map();
1787
+ const unsubscribe = this.cdp.onProtocolEvent((message)=>{
1788
+ if (String(message.sessionId || '') !== sessionId) return;
1789
+ if ('Runtime.executionContextCreated' !== String(message.method || '')) return;
1790
+ const context = message.params?.context;
1791
+ const contextId = context?.id;
1792
+ if ('number' == typeof contextId) contextsById.set(contextId, context);
1793
+ });
1794
+ try {
1795
+ await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
1796
+ await new Promise((resolve)=>setTimeout(resolve, 100));
1797
+ } finally{
1798
+ unsubscribe();
1799
+ }
1800
+ return Array.from(contextsById.values());
1801
+ }
1802
+ constructor(args){
1803
+ cdp_extension_controller_define_property(this, "outPath", void 0);
1804
+ cdp_extension_controller_define_property(this, "browser", void 0);
1805
+ cdp_extension_controller_define_property(this, "cdpPort", void 0);
1806
+ cdp_extension_controller_define_property(this, "profilePath", void 0);
1807
+ cdp_extension_controller_define_property(this, "extensionPaths", void 0);
1808
+ cdp_extension_controller_define_property(this, "cdp", null);
1809
+ cdp_extension_controller_define_property(this, "extensionId", null);
1810
+ cdp_extension_controller_define_property(this, "lastRuntimeReinjectionReport", null);
1811
+ this.outPath = args.outPath;
1812
+ this.browser = args.browser;
1813
+ this.cdpPort = args.cdpPort;
1814
+ this.profilePath = args.profilePath;
1815
+ this.extensionPaths = args.extensionPaths;
1816
+ }
1817
+ }
1818
+ var extension_output_path = __webpack_require__("../browser/run-chromium/chromium-launch/extension-output-path.ts");
1819
+ async function setupCdpAfterLaunch(compilation, plugin, chromiumArgs) {
1820
+ const loadExtensionFlag = chromiumArgs.find((flag)=>flag.startsWith('--load-extension='));
1821
+ const extensionOutputPath = (0, extension_output_path.W)(compilation, loadExtensionFlag);
1822
+ const extensionPaths = loadExtensionFlag ? loadExtensionFlag.replace('--load-extension=', '').split(',').map((s)=>s.trim()).filter(Boolean) : [];
1823
+ const selectedExtensionPaths = extensionOutputPath && extensionOutputPath.length > 0 ? [
1824
+ extensionOutputPath
1825
+ ] : extensionPaths;
1826
+ const remoteDebugPortFlag = chromiumArgs.find((flag)=>flag.startsWith('--remote-debugging-port='));
1827
+ const chromeRemoteDebugPort = remoteDebugPortFlag ? parseInt(remoteDebugPortFlag.split('=')[1], 10) : (0, shared_utils.jl)(plugin.port, plugin.instanceId);
1828
+ const userDataDirFlag = chromiumArgs.find((flag)=>flag.startsWith('--user-data-dir='));
1829
+ const userDataDir = userDataDirFlag ? userDataDirFlag.replace('--user-data-dir=', '').replace(/^"|"$/g, '') : '';
1830
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
1831
+ if (userDataDir) console.log(messages.aIt(userDataDir));
1832
+ console.log(messages.CYH(chromeRemoteDebugPort, chromeRemoteDebugPort));
1833
+ }
1834
+ const cdpExtensionController = new CDPExtensionController({
1835
+ outPath: extensionOutputPath,
1836
+ browser: 'chromium-based' === plugin.browser ? 'chrome' : plugin.browser,
1837
+ cdpPort: chromeRemoteDebugPort,
1838
+ profilePath: userDataDir || void 0,
1839
+ extensionPaths: selectedExtensionPaths
1840
+ });
1841
+ await cdpExtensionController.connect();
1842
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(messages.M3V('127.0.0.1', chromeRemoteDebugPort));
1843
+ const mode = compilation?.options?.mode || 'development';
1844
+ let earlyBannerPrinted = false;
1845
+ if ('development' === mode) try {
1846
+ earlyBannerPrinted = await (0, banner.ai)({
1847
+ outPath: extensionOutputPath,
1848
+ browser: plugin.browser,
1849
+ hostPort: {
1850
+ host: '127.0.0.1',
1851
+ port: chromeRemoteDebugPort
1852
+ },
1853
+ getInfo: async ()=>null,
1854
+ browserVersionLine: plugin.browserVersionLine
1855
+ });
1856
+ } catch {}
1857
+ if ('development' === mode) try {
1858
+ earlyBannerPrinted = await (0, banner.ai)({
1859
+ outPath: extensionOutputPath,
1860
+ browser: plugin.browser,
1861
+ hostPort: {
1862
+ host: '127.0.0.1',
1863
+ port: chromeRemoteDebugPort
1864
+ },
1865
+ getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
1866
+ browserVersionLine: plugin.browserVersionLine
1867
+ });
1868
+ } catch {}
1869
+ let extensionControllerInfo = null;
1870
+ try {
1871
+ const ensureLoadedTimeoutMs = 10000;
1872
+ extensionControllerInfo = await Promise.race([
1873
+ cdpExtensionController.ensureLoaded(),
1874
+ new Promise((_, reject)=>{
1875
+ setTimeout(()=>reject(new Error(`ensureLoaded timeout (${ensureLoadedTimeoutMs}ms)`)), ensureLoadedTimeoutMs);
1876
+ })
1877
+ ]);
1878
+ } catch (error) {
1879
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] ensureLoaded failed: ${String(error?.message || error)}`);
1880
+ }
1881
+ try {
1882
+ if ('development' === mode) {
1883
+ if (!earlyBannerPrinted) {
1884
+ const bannerPrinted = await (0, banner.ai)({
1885
+ outPath: extensionOutputPath,
1886
+ browser: plugin.browser,
1887
+ hostPort: {
1888
+ host: '127.0.0.1',
1889
+ port: chromeRemoteDebugPort
1890
+ },
1891
+ getInfo: async ()=>extensionControllerInfo,
1892
+ browserVersionLine: plugin.browserVersionLine
1893
+ });
1894
+ if (!bannerPrinted) await (0, banner.ai)({
1895
+ outPath: extensionOutputPath,
1896
+ browser: plugin.browser,
1897
+ hostPort: {
1898
+ host: '127.0.0.1',
1899
+ port: chromeRemoteDebugPort
1900
+ },
1901
+ getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
1902
+ browserVersionLine: plugin.browserVersionLine
1903
+ });
1904
+ }
1905
+ } else if ('production' === mode) {
1906
+ const runtime = extensionControllerInfo ? {
1907
+ extensionId: extensionControllerInfo.extensionId,
1908
+ name: extensionControllerInfo.name,
1909
+ version: extensionControllerInfo.version
1910
+ } : void 0;
1911
+ await (0, banner.MK)({
1912
+ browser: plugin.browser,
1913
+ outPath: extensionOutputPath,
1914
+ browserVersionLine: plugin.browserVersionLine,
1915
+ runtime
1916
+ });
1917
+ }
1918
+ } catch (bannerErr) {
1919
+ if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.$wD(String(bannerErr)));
1920
+ try {
1921
+ const mode = compilation?.options?.mode || 'development';
1922
+ if ('production' === mode) await (0, banner.MK)({
1923
+ browser: plugin.browser,
1924
+ outPath: extensionOutputPath,
1925
+ browserVersionLine: plugin.browserVersionLine
1926
+ });
1927
+ } catch {}
1928
+ }
1929
+ plugin.cdpController = cdpExtensionController;
1930
+ }
1931
+ }
1932
+ };