extension-develop 4.1.39 → 4.1.40-canary.459.2c1ba7b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/dist/{771~0.mjs → 5h~0.mjs} +13 -3
- package/dist/{273~0.mjs → 6l~0.mjs} +1 -1
- package/dist/{524~0.mjs → 9~0.mjs} +18 -2
- package/dist/{640~0.mjs → bh~0.mjs} +6 -1
- package/dist/bridge.mjs +14 -8
- package/dist/b~0.mjs +8644 -0
- package/dist/command-dev.d.ts +2 -0
- package/dist/command-preview.d.ts +2 -0
- package/dist/contracts.mjs +2 -1
- package/dist/{469~0.mjs → cp~0.mjs} +66 -17
- package/dist/css-parse-guard-loader.mjs +2 -2
- package/dist/c~0.mjs +56 -0
- package/dist/dead-css-url-loader.mjs +20 -119
- package/dist/dev-server/control-bridge/actions-file.d.ts +7 -0
- package/dist/dev-server/control-bridge/broker.d.ts +42 -2
- package/dist/dev-server/control-bridge/consumer-client.d.ts +7 -0
- package/dist/dev-server/control-bridge/contracts.d.ts +29 -1
- package/dist/dev-server/control-bridge/logs-file.d.ts +6 -0
- package/dist/dev-server/control-bridge/loopback.d.ts +1 -0
- package/dist/dev-server/control-bridge/producer-runtime.d.ts +5 -2
- package/dist/dev-server/control-bridge/production-control.d.ts +1 -0
- package/dist/dev-server/control-bridge/session-token.d.ts +5 -2
- package/dist/dev-server/cors.d.ts +4 -2
- package/dist/dev-server/messages.d.ts +6 -0
- package/dist/dev-server/session-restart.d.ts +3 -1
- package/dist/dev-server~0.mjs +71 -129
- package/dist/df~0.mjs +197 -0
- package/dist/{846~0.mjs → d~0.mjs} +4 -3
- package/dist/ensure-hmr-for-scripts.js +3 -3
- package/dist/ensure-hmr-for-scripts.mjs +3 -3
- package/dist/extension-js-devtools/build-stamp.json +2 -2
- package/dist/extension-js-devtools/chrome/background/service_worker.js +2 -2
- package/dist/extension-js-devtools/chrome/pages/welcome.js +2 -2
- package/dist/extension-js-devtools/chromium/background/service_worker.js +2 -2
- package/dist/extension-js-devtools/chromium/pages/welcome.js +2 -2
- package/dist/extension-js-devtools/edge/background/service_worker.js +2 -2
- package/dist/extension-js-devtools/edge/pages/welcome.js +2 -2
- package/dist/extension-js-devtools/firefox/background/scripts.js +2 -2
- package/dist/extension-js-devtools/firefox/pages/welcome.js +2 -2
- package/dist/extension-js-theme/build-stamp.json +2 -2
- package/dist/{143~0.mjs → ey~0.mjs} +2 -2
- package/dist/e~0.mjs +33 -0
- package/dist/feature-scripts-classic-traced-globals-loader.mjs +7 -2
- package/dist/feature-scripts-content-script-wrapper.js +56 -18
- package/dist/feature-scripts-content-script-wrapper.mjs +56 -18
- package/dist/feature-scripts-native-geturl-import-loader.mjs +1 -1
- package/dist/{105~0.mjs → g0~0.mjs} +1 -1
- package/dist/{88~0.mjs → j6~0.mjs} +9 -1
- package/dist/{731~0.mjs → j~0.mjs} +2 -2
- package/dist/{712~0.mjs → ka~0.mjs} +18 -2
- package/dist/{852~0.mjs → k~0.mjs} +4 -2
- package/dist/late-css-import-loader.mjs +1 -1
- package/dist/lib/addon-lint.d.ts +6 -0
- package/dist/lib/build-summary.d.ts +6 -0
- package/dist/lib/dev-additions.d.ts +12 -0
- package/dist/lib/extension-base-from-stack.d.ts +16 -0
- package/dist/lib/localized-manifest-name.d.ts +9 -0
- package/dist/lib/manifest-types.d.ts +276 -0
- package/dist/lib/messages.d.ts +6 -2
- package/dist/lib/process-started-at.d.ts +1 -0
- package/dist/lib/real-path.d.ts +8 -0
- package/dist/lib/resource-path.d.ts +1 -0
- package/dist/lib/session-paths.d.ts +2 -0
- package/dist/lib/split-chunks.d.ts +2 -1
- package/dist/lib/stats-handler.d.ts +1 -0
- package/dist/lib/tsconfig-includes-file.d.ts +1 -0
- package/dist/l~0.mjs +2290 -0
- package/dist/main-world-bridge.js +92 -23
- package/dist/main-world-bridge.mjs +92 -23
- package/dist/manifest-entry.d.ts +2 -0
- package/dist/manifest.mjs +3 -1
- package/dist/module.mjs +3 -3
- package/dist/{832~0.mjs → m~0.mjs} +2244 -288
- package/dist/o~0.mjs +47 -0
- package/dist/plugin-browsers/index.d.ts +7 -0
- package/dist/plugin-browsers/safari-dev-plugin.d.ts +2 -0
- package/dist/plugin-compatibility/compatibility-lib/messages.d.ts +5 -1
- package/dist/plugin-compatibility/compatibility-lib/native-browser-namespace.d.ts +5 -0
- package/dist/plugin-compatibility/feature-browser-global.d.ts +11 -1
- package/dist/plugin-compatibility/index.d.ts +2 -0
- package/dist/plugin-compilation/compilation-lib/messages.d.ts +4 -1
- package/dist/plugin-compilation/env.d.ts +1 -0
- package/dist/plugin-compilation/index.d.ts +2 -0
- package/dist/plugin-compilation/node-builtins.d.ts +5 -0
- package/dist/plugin-compilation/one-diagnostic-per-location.d.ts +13 -0
- package/dist/plugin-compilation/resolve-file-requests.d.ts +16 -0
- package/dist/plugin-compilation/warm-ancestor-watchers.d.ts +19 -0
- package/dist/plugin-compilation/watch-real-project-path.d.ts +27 -0
- package/dist/plugin-compilation/zip.d.ts +2 -0
- package/dist/plugin-css/css-in-content-script-loader.d.ts +1 -1
- package/dist/plugin-css/css-lib/build-css-rules.d.ts +3 -0
- package/dist/plugin-css/css-lib/inline-content-script-css.d.ts +3 -1
- package/dist/plugin-css/css-lib/messages.d.ts +4 -0
- package/dist/plugin-css/css-lib/sfc-style-block.d.ts +26 -0
- package/dist/plugin-css/css-lib/unplaced-style-imports.d.ts +7 -0
- package/dist/plugin-css/css-lib/verbatim-css.d.ts +1 -0
- package/dist/plugin-css/dead-css-url-loader.d.ts +9 -1
- package/dist/plugin-css/index.d.ts +1 -0
- package/dist/plugin-css/sfc-style-block-loader.d.ts +18 -0
- package/dist/plugin-css/unplaced-style-import-loader.d.ts +16 -0
- package/dist/plugin-playwright/index.d.ts +22 -0
- package/dist/plugin-reload/classify-reload.d.ts +20 -0
- package/dist/plugin-reload/index.d.ts +4 -2
- package/dist/plugin-reload/messages.d.ts +1 -0
- package/dist/plugin-reload/reload-dispatch.d.ts +21 -2
- package/dist/plugin-reload/reload-lib/dev-content-scripts.d.ts +6 -0
- package/dist/plugin-reload/reload-lib/scripts-replay-shim.d.ts +1 -1
- package/dist/plugin-reload/steps/inject-bridge-producer.d.ts +6 -0
- package/dist/plugin-reload/steps/setup-reload-strategy/webpack-target-webextension-fork/lib/webpack5/ChunkLoader.d.ts +3 -0
- package/dist/plugin-reload/steps/setup-reload-strategy/webpack-target-webextension-fork/lib/webpack5/RuntimeModules/AutoPublicPath.d.ts +1 -1
- package/dist/plugin-reload/steps/setup-reload-strategy/webpack-target-webextension-fork/lib/webpack5/RuntimeModules/BaseUri.d.ts +1 -1
- package/dist/plugin-reload/steps/setup-reload-strategy/webpack-target-webextension-fork/lib/webpack5/RuntimeModules/LoadScript.d.ts +1 -1
- package/dist/plugin-reload/steps/setup-reload-strategy/webpack-target-webextension-fork/lib/webpack5/RuntimeModules/PublicPath.d.ts +1 -1
- package/dist/plugin-special-folders/get-data.d.ts +2 -0
- package/dist/plugin-special-folders/hint-import-only-scripts.d.ts +4 -0
- package/dist/plugin-special-folders/include-files.d.ts +2 -0
- package/dist/plugin-special-folders/messages.d.ts +1 -0
- package/dist/plugin-web-extension/feature-html/html-lib/inject.d.ts +1 -1
- package/dist/plugin-web-extension/feature-html/html-lib/patch-html.d.ts +1 -0
- package/dist/plugin-web-extension/feature-html/steps/update-html-file.d.ts +1 -0
- package/dist/plugin-web-extension/feature-icons/extract-action-theme-icons.d.ts +1 -0
- package/dist/plugin-web-extension/feature-icons/extract-icon-variants.d.ts +2 -0
- package/dist/plugin-web-extension/feature-json/json-validation.d.ts +2 -1
- package/dist/plugin-web-extension/feature-json/messages.d.ts +2 -0
- package/dist/plugin-web-extension/feature-json/process-assets.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-lib/filter-keys-gecko.d.ts +21 -0
- package/dist/plugin-web-extension/feature-manifest/manifest-lib/filter-keys-safari.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-lib/icon-variants-fallback.d.ts +15 -0
- package/dist/plugin-web-extension/feature-manifest/manifest-lib/sanitize-fatal-shapes.d.ts +2 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-lib/webkit-unsupported-keys.d.ts +15 -0
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/content_scripts.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/icons.d.ts +3 -2
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/omnibox.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/page_action.d.ts +2 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/permissions.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/common/sandbox.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/mv2/browser_action.d.ts +4 -3
- package/dist/plugin-web-extension/feature-manifest/manifest-overrides/mv3/action.d.ts +3 -2
- package/dist/plugin-web-extension/feature-manifest/messages.d.ts +15 -1
- package/dist/plugin-web-extension/feature-manifest/normalize-manifest-path.d.ts +2 -0
- package/dist/plugin-web-extension/feature-manifest/steps/apply-dev-defaults-lib/dev-additions.d.ts +8 -0
- package/dist/plugin-web-extension/feature-manifest/steps/apply-dev-defaults-lib/patch-background.d.ts +2 -2
- package/dist/plugin-web-extension/feature-manifest/steps/apply-dev-defaults-lib/patch-externally-connectable.d.ts +1 -1
- package/dist/plugin-web-extension/feature-manifest/steps/patch-gecko-background.d.ts +1 -0
- package/dist/plugin-web-extension/feature-manifest/steps/warn-content-script-host-access.d.ts +17 -0
- package/dist/plugin-web-extension/feature-manifest/steps/warn-description-length.d.ts +26 -0
- package/dist/plugin-web-extension/feature-manifest/steps/warn-gecko-unsupported-apis.d.ts +37 -2
- package/dist/plugin-web-extension/feature-scripts/contracts.d.ts +3 -0
- package/dist/plugin-web-extension/feature-scripts/index.d.ts +1 -0
- package/dist/plugin-web-extension/feature-scripts/messages.d.ts +10 -1
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/completion-value.d.ts +13 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/injected-sheet-urls.d.ts +5 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/main-world-bridge-pairing.d.ts +5 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/main-world-copy-routing.d.ts +2 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/registration-worlds.d.ts +10 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/runtime-main-world-scripts.d.ts +25 -2
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/runtime-script-sheet.d.ts +14 -0
- package/dist/plugin-web-extension/feature-scripts/scripts-lib/taken-extension-base.d.ts +10 -0
- package/dist/plugin-web-extension/feature-scripts/steps/add-base-uri-runtime-module.d.ts +7 -1
- package/dist/plugin-web-extension/feature-scripts/steps/add-content-script-wrapper/content-script-wrapper.d.ts +2 -0
- package/dist/plugin-web-extension/feature-scripts/steps/add-content-script-wrapper/index.d.ts +2 -0
- package/dist/plugin-web-extension/feature-scripts/steps/add-public-path-runtime-module.d.ts +6 -0
- package/dist/plugin-web-extension/feature-scripts/steps/classic-traced-globals-loader.d.ts +1 -0
- package/dist/plugin-web-extension/feature-scripts/steps/compile-main-world-scripts.d.ts +4 -0
- package/dist/plugin-web-extension/feature-scripts/steps/keep-completion-value.d.ts +6 -0
- package/dist/plugin-web-extension/feature-scripts/steps/pair-runtime-main-world-bridges.d.ts +12 -0
- package/dist/plugin-web-extension/feature-scripts/steps/place-runtime-script-sheets.d.ts +12 -0
- package/dist/plugin-web-extension/feature-scripts/steps/prune-main-world-bridges.d.ts +1 -0
- package/dist/plugin-web-extension/feature-scripts/steps/root-injected-sheet-urls.d.ts +9 -0
- package/dist/plugin-web-extension/feature-scripts/steps/route-main-world-copies.d.ts +10 -0
- package/dist/plugin-web-extension/feature-scripts/steps/source-literals.d.ts +24 -0
- package/dist/plugin-web-extension/feature-scripts/steps/take-extension-base.d.ts +11 -0
- package/dist/plugin-web-extension/feature-scripts/steps/trace-runtime-loaded-files.d.ts +18 -3
- package/dist/plugin-web-extension/feature-scripts/steps/warn-main-world-registration-changed.d.ts +12 -0
- package/dist/plugin-web-extension/feature-scripts/steps/warn-moved-page-relative-urls.d.ts +30 -0
- package/dist/plugin-web-extension/feature-scripts/steps/warn-page-relative-script-path.d.ts +10 -0
- package/dist/plugin-web-extension/feature-scripts/steps/warn-unknown-registration-world.d.ts +10 -0
- package/dist/plugin-web-extension/feature-web-resources/collect-entry-imports.d.ts +1 -0
- package/dist/plugin-web-extension/feature-web-resources/web-resources-lib/messages.d.ts +2 -0
- package/dist/plugin-web-extension/feature-web-resources/web-resources-lib/page-requests.d.ts +5 -0
- package/dist/plugin-web-extension/feature-web-resources/web-resources-lib/resolve-war.d.ts +1 -0
- package/dist/plugin-web-extension/feature-web-resources/web-resources-lib/unreachable-resources.d.ts +1 -0
- package/dist/plugin-web-extension/shared/script-graph.d.ts +12 -0
- package/dist/preprocessor-passthrough-loader.mjs +1 -1
- package/dist/preview.mjs +1 -1
- package/dist/public-css-url-loader.mjs +1 -1
- package/dist/{331~0.mjs → q~0.mjs} +2 -2
- package/dist/rj~0.mjs +125 -0
- package/dist/{519~0.mjs → rl~0.mjs} +56 -5
- package/dist/rspack-config~0.mjs +3140 -3302
- package/dist/{177~0.mjs → r~0.mjs} +2 -2
- package/dist/sfc-style-block-loader.mjs +49 -0
- package/dist/stats-handler~0.mjs +15 -7
- package/dist/tm~0.mjs +71 -0
- package/dist/types.d.ts +46 -5
- package/dist/{285~0.mjs → t~0.mjs} +41 -26
- package/dist/unplaced-style-import-loader.mjs +131 -0
- package/dist/x~0.mjs +3 -0
- package/dist/y~0.mjs +234 -0
- package/dist/zip~0.mjs +5 -4
- package/dist/{363~0.mjs → z~0.mjs} +563 -281
- package/package.json +6 -6
- package/dist/527~0.mjs +0 -3
- package/dist/840~0.mjs +0 -5635
- /package/dist/{895~0.mjs → 3~0.mjs} +0 -0
- /package/dist/{374~0.mjs → 5~0.mjs} +0 -0
- /package/dist/{206~0.mjs → 6~0.mjs} +0 -0
- /package/dist/{471~0.mjs → g~0.mjs} +0 -0
- /package/dist/{117~0.mjs → w~0.mjs} +0 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const CONTROL_PORT_ASSET_NAME = "extension-js-control.json";
|
|
2
|
-
export declare const BRIDGE_PRODUCER_SOURCE = ";(function () {\n try {\n var g = (typeof globalThis === \"object\" && globalThis) ? globalThis : this;\n if (!g || g.__extjsBridgeProducerInstalled) return;\n\n var PORT = parseInt(\"__EXTJS_CONTROL_PORT__\", 10);\n var INSTANCE_ID = \"__EXTJS_INSTANCE_ID__\";\n var CONTEXT = \"__EXTJS_CONTEXT__\";\n // Connectable host of the dev-server control WS. Baked from the resolved\n // connectable host (loopback locally; the public host for remote/devcontainer).\n var HOST = \"__EXTJS_CONTROL_HOST__\";\n if (!HOST || HOST.indexOf(\"__EXTJS\") === 0) HOST = \"127.0.0.1\";\n if (!PORT || PORT < 1) return;\n\n var WS = g.WebSocket;\n if (typeof WS !== \"function\") return;\n\n var consoleRef = g.console || {};\n g.__extjsBridgeProducerInstalled = true;\n\n // Capture extension event listeners at install time: these wraps run\n // BEFORE user code, and no platform API exists to dispatch these events.\n function captureEvent(event, sink) {\n try {\n if (!event || typeof event.addListener !== \"function\") return;\n var origAdd = event.addListener.bind(event);\n event.addListener = function (cb) {\n if (typeof cb === \"function\" && sink.indexOf(cb) === -1) sink.push(cb);\n return origAdd(cb);\n };\n if (typeof event.removeListener === \"function\") {\n var origRemove = event.removeListener.bind(event);\n event.removeListener = function (cb) {\n var i = sink.indexOf(cb);\n if (i !== -1) sink.splice(i, 1);\n return origRemove(cb);\n };\n }\n } catch (e) { /* non-fatal: trigger falls back to its no-listener reply */ }\n }\n\n // Use the raw globals (not the hoisted chrome var below). This runs first.\n // On Gecko browser.* is a DISTINCT wrapper object: hook BOTH namespaces.\n // One sink per manifest key, so a replay fires only the entry it clicks.\n var ACTION_KEYS = [\"action\", \"browser_action\", \"page_action\"];\n var ACTION_NAMESPACES = {action: \"action\", browser_action: \"browserAction\", page_action: \"pageAction\"};\n var actionClickedListeners = {action: [], browser_action: [], page_action: []};\n var commandListeners = [];\n var capturedEvents = [];\n function captureEventOnce(event, sink) {\n // Polyfilled extensions expose ONE event object on both namespaces:\n // wrap it once, and the sink dedupes callbacks shared across wrappers.\n if (!event || capturedEvents.indexOf(event) !== -1) return;\n capturedEvents.push(event);\n captureEvent(event, sink);\n }\n var captureNamespaces = [g.chrome, g.browser];\n for (var cn = 0; cn < captureNamespaces.length; cn++) {\n var capNS = captureNamespaces[cn];\n if (!capNS) continue;\n for (var ak = 0; ak < ACTION_KEYS.length; ak++) {\n var akNS = capNS[ACTION_NAMESPACES[ACTION_KEYS[ak]]];\n captureEventOnce(akNS && akNS.onClicked, actionClickedListeners[ACTION_KEYS[ak]]);\n }\n captureEventOnce(capNS.commands && capNS.commands.onCommand, commandListeners);\n }\n\n var LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\", \"trace\"];\n // The dev server's HMR client logs its own chatter (\"[HMR] Waiting for\n // update signal from WDS...\") through the extension's console; it is not\n // the extension's output. Its warnings and errors still ship.\n function isDevServerChatter(level, args) {\n if (level === \"warn\" || level === \"error\") return false;\n var first = args && args[0];\n return typeof first === \"string\" && /^\\[(?:HMR|webpack-dev-server|rspack-dev-server)\\] /.test(first);\n }\n var socket = null;\n var open = false;\n var queue = [];\n var backoff = 250;\n var MAX_BACKOFF = 5000;\n var connectFailures = 0;\n var MAX_QUEUE = 1000;\n var MAX_RESULT_BYTES = 256 * 1024;\n // Where log frames of every level are parked so a context that dies before\n // its socket opens does not take them along: a Safari background woken by\n // an event can unload before it connects. Capped; plain lines go before\n // errors when the cap bites.\n var PENDING_ERRORS_KEY = \"__extjsPendingErrors\";\n var MAX_PENDING_ERRORS = 100;\n var PENDING_ERROR_TTL = 300000;\n\n function nowId() {\n return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);\n }\n\n // The extension's own URL scheme names the engine outright, which beats a\n // user agent where Chrome and Safari both say \"Safari\".\n function engineName() {\n try {\n var scheme = (typeof location !== \"undefined\" && location.protocol) || \"\";\n if (scheme.indexOf(\"safari-web-extension\") === 0) return \"webkit\";\n if (scheme.indexOf(\"moz-extension\") === 0) return \"firefox\";\n if (scheme.indexOf(\"chrome-extension\") === 0) return \"chromium\";\n var ua = (typeof navigator !== \"undefined\" && navigator.userAgent) || \"\";\n if (/firefox/i.test(ua)) return \"firefox\";\n if (/safari/i.test(ua) && !/chrome|chromium|edg/i.test(ua)) return \"webkit\";\n return \"chromium\";\n } catch (e) { return \"chromium\"; }\n }\n\n function safeValue(v) {\n try {\n var s = JSON.stringify(v);\n if (s === undefined) return {value: undefined, truncated: false};\n if (s.length > MAX_RESULT_BYTES) {\n return {value: {__type: \"truncated\", preview: s.slice(0, 1024)}, truncated: true};\n }\n return {value: JSON.parse(s), truncated: false};\n } catch (e) {\n return {value: {__type: \"unserializable\", preview: String(v).slice(0, 512)}, truncated: false};\n }\n }\n\n // A page cap counts characters, the transport counts the escaped JSON, and\n // markup grows under escaping. Shrink the html until the whole snapshot\n // fits, so a capped inspect still returns html instead of a placeholder.\n function fitSnapshot(snap) {\n try {\n if (!snap || typeof snap.html !== \"string\") return snap;\n if (JSON.stringify(snap).length <= MAX_RESULT_BYTES) return snap;\n var html = snap.html;\n var cut = html.length;\n for (var attempt = 0; attempt < 40 && cut > 0; attempt++) {\n snap.html = html.slice(0, cut);\n snap.htmlTruncated = true;\n var size = JSON.stringify(snap).length;\n if (size <= MAX_RESULT_BYTES) return snap;\n cut = Math.floor(cut * (MAX_RESULT_BYTES / size) * 0.98);\n }\n snap.html = \"\";\n snap.htmlTruncated = true;\n return snap;\n } catch (e) {\n return snap;\n }\n }\n\n function replyOk(cmdId, value) {\n var s = safeValue(value);\n var frame = {type: \"result\", cmdId: cmdId, ok: true, value: s.value};\n if (s.truncated) frame.truncated = true;\n try { socket && socket.send(JSON.stringify(frame)); } catch (e) {\n // Ignore\n }\n }\n\n function replyErr(cmdId, name, message, code) {\n var frame = {type: \"result\", cmdId: cmdId, ok: false, error: {name: name, message: String(message), engine: engineName()}};\n if (code) frame.error.code = code;\n try { socket && socket.send(JSON.stringify(frame)); } catch (e) {\n // Ignore\n }\n }\n\n // A tabs.* failure the caller can act on gets a name and a refusal code:\n // a tab id nobody has is TargetNotFound, and a url the engine refuses by\n // rule (Gecko's \"Illegal URL\", Chromium's javascript: ban) is BadRequest.\n // Anything else keeps the op's own error name.\n function replyTabsFailure(cmdId, err, fallbackName, url) {\n var msg = String((err && err.message) || err);\n if (/no tab with id|invalid tab id/i.test(msg)) {\n replyErr(cmdId, \"TargetNotFound\", msg, \"tab_not_found\");\n return;\n }\n if (url && /illegal url|javascript urls are not allowed|invalid url/i.test(msg)) {\n replyErr(cmdId, \"BadRequest\", engineName() + \" refuses to open \" + url + \" from the extension's tabs API (\" + msg + \")\", \"url_refused\");\n return;\n }\n replyErr(cmdId, fallbackName, msg);\n }\n\n // A surface relay that answered nothing is closed only when the engine\n // says no receiver exists. Any other lastError (a reply the engine could\n // not clone, a channel that closed) means the surface WAS open and ran the\n // expression, so the message quotes the engine instead of \"not open\".\n function surfaceReplyFailure(ctx, resp) {\n var le = null;\n try { le = g.chrome && g.chrome.runtime && g.chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n if (!le && resp) return null;\n var lem = le ? String((le && le.message) || le) : \"\";\n if (!lem || /receiving end does not exist|could not establish connection/i.test(lem)) {\n return {code: \"surface_not_open\", message: \"surface '\" + ctx + \"' is not open (open it first: extension open \" + ctx + \")\"};\n }\n return {code: \"surface_reply_failed\", message: \"surface '\" + ctx + \"' answered but the reply did not arrive: \" + lem};\n }\n\n // Why a tab injection cannot run here. An MV3 copy whose manifest omits\n // the scripting permission has no chrome.scripting (Firefox gates the\n // whole namespace on it); only MV2 lacks the API by design.\n function scriptingMissingReason(tabId) {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { m = null; }\n var mv = m && m.manifest_version;\n if (mv >= 3) {\n var perms = stringList(m.permissions);\n if (perms.indexOf(\"scripting\") === -1) {\n return \"cannot inject into tab \" + tabId + \": this MV3 build's manifest has no \\\"scripting\\\" permission, so chrome.scripting is missing (Firefox exposes it only with that permission). Add \\\"scripting\\\" to permissions, or use a dev session (extension dev), which adds it; --context background still works\";\n }\n return \"cannot inject into tab \" + tabId + \": chrome.scripting is missing on this engine even though the manifest declares \\\"scripting\\\"; use --context background\";\n }\n if (mv === 2) return \"chrome.scripting is not available on this engine (MV2 has no scripting API); use --context background\";\n return \"cannot inject into tab \" + tabId + \": chrome.scripting is not available on this engine; use --context background\";\n }\n\n // The page a surface lives in, as the manifest names it, so the background\n // can ask the engine whether that page is open at all.\n function surfacePagePath(ctx) {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { return null; }\n if (!m) return null;\n var p = null;\n if (ctx === \"popup\") p = (m.action && m.action.default_popup) || (m.browser_action && m.browser_action.default_popup) || (m.page_action && m.page_action.default_popup);\n else if (ctx === \"options\") p = (m.options_ui && m.options_ui.page) || m.options_page;\n else if (ctx === \"sidebar\") p = (m.side_panel && m.side_panel.default_path) || (m.sidebar_action && m.sidebar_action.default_panel);\n else if (ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") p = m.chrome_url_overrides && m.chrome_url_overrides[ctx];\n // Character classes on purpose: this source is a template literal, and\n // a backslash escape in a regex would be eaten before it ever ran.\n return typeof p === \"string\" && p ? p.replace(/^[.]?[/]/, \"\") : null;\n }\n\n // Chrome says \"message port closed\" both when the surface died mid-op and\n // when a bystander extension page (the options page, a new tab override)\n // received the message and passed, since a relay returns nothing for a\n // context that is not its own. Only the engine's open-context list tells\n // the two apart, so it is asked before a reply gets the blame. Engines\n // without getContexts keep the plain classification.\n function classifySurfaceFailure(ctx, resp, cb) {\n var relayErr = surfaceReplyFailure(ctx, resp);\n if (!relayErr || relayErr.code !== \"surface_reply_failed\" || !/message port closed/i.test(relayErr.message)) { cb(relayErr); return; }\n var rt = g.chrome && g.chrome.runtime;\n var page = surfacePagePath(ctx);\n if (!page || !rt || typeof rt.getContexts !== \"function\") { cb(relayErr); return; }\n var wanted = \"\";\n try { wanted = String(rt.getURL(page)).split(/[?#]/)[0]; } catch (e) { cb(relayErr); return; }\n var notOpen = {code: \"surface_not_open\", message: \"surface '\" + ctx + \"' is not open (open it first: extension open \" + ctx + \")\"};\n try {\n Promise.resolve(rt.getContexts({})).then(function (list) {\n var open = false;\n for (var i = 0; i < (list || []).length; i++) {\n var u = list[i] && list[i].documentUrl;\n if (u && String(u).split(/[?#]/)[0] === wanted) { open = true; break; }\n }\n cb(open ? relayErr : notOpen);\n }, function () { cb(relayErr); });\n } catch (e) { cb(relayErr); }\n }\n\n // Every engine's wording for \"this document's CSP forbids eval\". Gecko\n // says \"call to eval() blocked by CSP\", Chromium quotes the directive.\n function cspBlocksEval(message) {\n return /call to eval\\(\\)|blocked by (?:the )?CSP|Content Security Policy|unsafe-eval/i.test(String(message == null ? \"\" : message));\n }\n\n // Name the refusal the browser wrote as prose, so a consumer branches on\n // error.code instead of matching the engine's sentence.\n function openRefusalCode(message) {\n var m = String(message == null ? \"\" : message);\n if (/user gesture|user input|user interaction|user action/i.test(m)) return \"needs_user_gesture\";\n if (/browser window|active window/i.test(m)) return \"needs_headed_window\";\n return undefined;\n }\n\n // Resolve a numeric tab id when the caller did not pass one: match\n // target.url against open tabs, else default to the active tab. (#51)\n function resolveTargetTab(target, cb) {\n var chrome = g.chrome;\n if (!chrome || !chrome.tabs) { cb(null, \"chrome.tabs is not available\"); return; }\n var url = target && target.url;\n if (url) {\n var substringMatch = function () {\n try {\n chrome.tabs.query({}, function (all) {\n var hit = (all || []).filter(function (t) { return t.url && String(t.url).indexOf(url) !== -1; })[0];\n if (hit && typeof hit.id === \"number\") { cb(hit.id, null); return; }\n cb(null, \"no open tab matches url: \" + url);\n });\n } catch (e2) { cb(null, \"tab query failed\"); }\n };\n try {\n // chrome.tabs.query accepts URL match patterns; a bare url/glob may\n // not be a valid pattern, so fall back to a substring scan.\n chrome.tabs.query({url: url}, function (tabs) {\n if (chrome.runtime && chrome.runtime.lastError) { substringMatch(); return; }\n if (tabs && tabs.length && typeof tabs[0].id === \"number\") { cb(tabs[0].id, null); return; }\n substringMatch();\n });\n } catch (e) { substringMatch(); }\n return;\n }\n try {\n chrome.tabs.query({active: true, lastFocusedWindow: true}, function (tabs) {\n var t = tabs && tabs[0];\n if (t && typeof t.id === \"number\") { cb(t.id, null); return; }\n cb(null, \"no active tab to target\");\n });\n } catch (e3) { cb(null, \"tab query failed\"); }\n }\n\n // chrome.* async APIs are callback-only on Gecko. Prefer promisified\n // browser.* when present, else the chrome.* callback form. cb(err, result).\n function nsCall(nsName, method, callArgs, cb) {\n var chromeG = g.chrome;\n var done = false;\n var once = function (err, r) { if (!done) { done = true; cb(err, r); } };\n var viaPromise = function (ns) {\n try {\n var ret = ns[method].apply(ns, callArgs);\n if (ret && typeof ret.then === \"function\") {\n ret.then(function (r) { once(null, r); }, function (e) { once(e); });\n return true;\n }\n } catch (e) { once(e); return true; }\n return false;\n };\n var bNS = g.browser && g.browser[nsName];\n if (bNS && typeof bNS[method] === \"function\" && viaPromise(bNS)) return;\n var cNS = chromeG && chromeG[nsName];\n if (!cNS || typeof cNS[method] !== \"function\") {\n once(new Error(\"chrome.\" + nsName + \".\" + method + \" is not available (engine: \" + engineName() + \")\"));\n return;\n }\n try {\n var ret2 = cNS[method].apply(cNS, callArgs.concat([function (r) {\n var le = chromeG.runtime && chromeG.runtime.lastError;\n if (le) once(le); else once(null, r);\n }]));\n // A promise-only implementation ignores the trailing callback and\n // returns a thenable instead; resolve through it (once() dedupes).\n if (ret2 && typeof ret2.then === \"function\") {\n ret2.then(function (r) { once(null, r); }, function (e) { once(e); });\n }\n } catch (e2) {\n if (!viaPromise(cNS)) once(e2);\n }\n }\n\n // Only a tab the engine could not find is a missing target. Anything else\n // happened in a tab that exists, a value it could not clone back above all.\n // Firefox refuses to script a moz-extension:// page or a page outside\n // host access with the tab right there, so that refusal is named too.\n function injectionErrorName(err) {\n var msg = String((err && err.message) || err || \"\");\n if (/no tab with id|invalid tab id/i.test(msg)) return \"TargetNotFound\";\n if (/clon/i.test(msg)) return \"DataCloneError\";\n if (injectionRefused(msg)) return \"InjectionRefused\";\n return \"ExecutorError\";\n }\n\n function injectionRefused(msg) {\n return /missing host permission|cannot access contents|cannot be scripted|cannot access a chrome|extensions gallery/i.test(String(msg));\n }\n\n function replyInjectionErr(cmdId, err) {\n var msg = (err && err.message) || err;\n replyErr(cmdId, injectionErrorName(err), msg, injectionRefused(msg) ? \"injection_refused\" : undefined);\n }\n\n function executeCommand(cmd) {\n var op = cmd.op, target = cmd.target || {}, args = cmd.args || {};\n var ctx = target.context || \"background\";\n var chrome = g.chrome;\n var cmdId = cmd.cmdId;\n // content/page eval & inspect need a numeric tab id: resolve --url (or\n // nothing) to a tab and re-dispatch with target.tabId filled in. (#51)\n if ((op === \"eval\" || op === \"inspect\" || op === \"reload\") && (ctx === \"content\" || ctx === \"page\") && target.tabId == null) {\n resolveTargetTab(target, function (tabId, err) {\n if (tabId == null) {\n // A filter that matched nothing, or no active tab, is a missing\n // target the caller can fix, not a missing feature.\n if (err && /^no open tab matches|^no active tab/i.test(String(err))) {\n replyErr(cmdId, \"TargetNotFound\", err, \"tab_not_found\");\n return;\n }\n replyErr(cmdId, \"Unsupported\", err || (\"eval/inspect in context \" + ctx + \" needs a --tab id, a --url to match, or an active tab\"));\n return;\n }\n var next = {};\n for (var k in cmd) { if (Object.prototype.hasOwnProperty.call(cmd, k)) next[k] = cmd[k]; }\n next.target = {};\n for (var tk in target) { if (Object.prototype.hasOwnProperty.call(target, tk)) next.target[tk] = target[tk]; }\n next.target.tabId = tabId;\n executeCommand(next);\n });\n return;\n }\n try {\n if (!chrome) { replyErr(cmdId, \"Unsupported\", \"chrome.* not available in this context\"); return; }\n if (op === \"eval\") {\n if (ctx === \"background\") {\n Promise.resolve().then(function () { return (0, eval)(args.expression); })\n .then(function (r) { replyOk(cmdId, r); }, function (e) {\n var msg = (e && e.message) || String(e);\n // MV3 forbids eval of strings in the SW/extension pages and\n // rejects 'unsafe-eval'. Gecko words the same refusal \"call to\n // eval() blocked by CSP\", which read as a guest throw.\n if (cspBlocksEval(msg)) {\n replyErr(cmdId, \"Unsupported\", \"eval is blocked in the extension background by the extension's content_security_policy, which allows no unsafe-eval. Use --context page --tab <id> (eval runs in the page's MAIN world), or run on a build whose CSP permits it. Engine: \" + engineName(), \"csp_blocks_eval\");\n } else {\n replyErr(cmdId, (e && e.name) || \"EvalError\", msg);\n }\n });\n } else if ((ctx === \"content\" || ctx === \"page\") && target.tabId && chrome.scripting) {\n // Wrap the eval so a throw INSIDE the tab comes back as data:\n // Chrome swallows an injected function's exception (null result).\n // A returned promise is settled in the tab, since Firefox cannot\n // clone one that sits inside the result object.\n nsCall(\"scripting\", \"executeScript\", [{\n target: {tabId: target.tabId},\n world: ctx === \"page\" ? \"MAIN\" : \"ISOLATED\",\n func: async function (src) {\n try { return {__extjsEval: 1, ok: true, value: await eval(src)}; }\n catch (e) { return {__extjsEval: 1, ok: false, name: (e && e.name) || \"EvalError\", message: (e && e.message) || String(e)}; }\n },\n args: [String(args.expression)]\n }], function (err, res) {\n if (err) { replyInjectionErr(cmdId, err); return; }\n var frame = res && res[0] ? res[0].result : undefined;\n if (!frame || frame.__extjsEval !== 1) {\n replyErr(cmdId, \"TargetNotFound\", \"the expression never executed in tab \" + target.tabId + \": no injectable frame returned a result (restricted page, or outside host_permissions)\");\n return;\n }\n if (frame.ok) { replyOk(cmdId, frame.value); return; }\n if (ctx === \"content\" && (cspBlocksEval(String(frame.name) + \" \" + String(frame.message)) || String(frame.name) === \"EvalError\")) {\n replyErr(cmdId, \"Unsupported\", \"eval of a string is blocked in the ISOLATED (content) world by the extension's content_security_policy. Use --context page (runs in the page's MAIN world). Original: \" + frame.message, \"csp_blocks_eval\");\n return;\n }\n replyErr(cmdId, frame.name || \"EvalError\", frame.message);\n });\n } else if (ctx === \"popup\" || ctx === \"options\" || ctx === \"sidebar\" || ctx === \"devtools\" || ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") {\n // The SW can't eval in another extension page; ask the surface's\n // own in-bundle relay (only the open, matching-context page responds).\n chrome.runtime.sendMessage(\n {__extjsEvalRequest: true, target: target, args: {expression: String(args.expression)}},\n function (resp) {\n classifySurfaceFailure(ctx, resp, function (relayErr) {\n if (relayErr) {\n replyErr(cmdId, \"Unsupported\", relayErr.message, relayErr.code);\n } else if (resp.ok) {\n replyOk(cmdId, resp.value);\n } else {\n replyErr(cmdId, (resp.error && resp.error.name) || \"EvalError\", (resp.error && resp.error.message) || \"eval failed\", resp.error && resp.error.code);\n }\n });\n }\n );\n } else if (ctx === \"content\" || ctx === \"page\") {\n replyErr(cmdId, \"Unsupported\", target.tabId\n ? scriptingMissingReason(target.tabId)\n : \"eval in context \" + ctx + \" requires a tabId\", target.tabId ? \"scripting_unavailable\" : undefined);\n } else {\n replyErr(cmdId, \"BadRequest\", \"unknown eval context: \" + ctx);\n }\n return;\n }\n if (op === \"storage.get\" || op === \"storage.set\") {\n // chrome.* storage is callback-only on Gecko and older Chromium.\n // Prefer promisified browser.*, then fall back to the callback shape.\n var storageNS = (g.browser && g.browser.storage) ? g.browser.storage : chrome.storage;\n var storageArea = storageNS && storageNS[args.area || \"local\"];\n if (!storageArea) { replyErr(cmdId, \"StorageError\", \"storage.\" + (args.area || \"local\") + \" unavailable\"); return; }\n var isSet = op === \"storage.set\";\n var callArgs = isSet ? [args.items || {}] : [args.key != null ? args.key : null];\n // The dev runtime keeps its own bookkeeping under __extjs* keys in\n // the same area; a whole-area read shows only the extension's data.\n var withoutFrameworkKeys = function (r) {\n if (args.key != null || !r || typeof r !== \"object\") return r;\n var own = {};\n for (var k in r) {\n if (Object.prototype.hasOwnProperty.call(r, k) && k.indexOf(\"__extjs\") !== 0) own[k] = r[k];\n }\n return own;\n };\n var onStorageOk = function (r) { replyOk(cmdId, isSet ? {set: Object.keys(args.items || {})} : withoutFrameworkKeys(r)); };\n var onStorageErr = function (e) { replyErr(cmdId, \"StorageError\", (e && e.message) || String(e)); };\n var storageFn = isSet ? storageArea.set : storageArea.get;\n try {\n var storageRet = storageFn.apply(storageArea, callArgs);\n if (storageRet && typeof storageRet.then === \"function\") {\n storageRet.then(onStorageOk, onStorageErr);\n return;\n }\n } catch (e) { /* not thenable / threw synchronously: fall back to callback */ }\n try {\n storageFn.apply(storageArea, callArgs.concat([function (r) {\n var le = chrome.runtime && chrome.runtime.lastError;\n if (le) onStorageErr(le); else onStorageOk(r);\n }]));\n } catch (e) { onStorageErr(e); }\n return;\n }\n if (op === \"reload\") {\n if (ctx === \"background\") {\n // The answer names the override tabs the next generation restores.\n restartExtension(50, function (restoring) {\n var value = {reloading: true, reloaded: [\"background\"]};\n if (restoring.length) {\n value.restoring = [];\n for (var r = 0; r < restoring.length; r++) value.restoring.push({tabId: restoring[r].tabId, surface: restoring[r].surface});\n }\n replyOk(cmdId, value);\n });\n } else if (target.tabId) {\n nsCall(\"tabs\", \"reload\", [target.tabId], function (err) {\n if (err) replyTabsFailure(cmdId, err, \"ReloadError\");\n else replyOk(cmdId, {reloaded: target.tabId});\n });\n } else {\n replyErr(cmdId, \"Unsupported\", \"reload needs background or a tabId\");\n }\n return;\n }\n if (op === \"open\") {\n var surface = args.surface || ctx;\n // The toolbar entry a click lands on: MV3 declares action, MV2\n // browser_action or page_action. Firefox MV3 still exposes\n // pageAction, so the manifest picks first, and its namespace has to\n // exist. Without a declared key, the first namespace present wins.\n var actionManifestKey = function () {\n var m = null;\n try { m = chrome.runtime.getManifest(); } catch (e) { m = null; }\n var hasNS = function (key) {\n var n = ACTION_NAMESPACES[key];\n return !!((g.browser && g.browser[n]) || (g.chrome && g.chrome[n]));\n };\n for (var k = 0; k < ACTION_KEYS.length; k++) {\n if (m && m[ACTION_KEYS[k]] && hasNS(ACTION_KEYS[k])) return ACTION_KEYS[k];\n }\n for (var n = 0; n < ACTION_KEYS.length; n++) {\n if (hasNS(ACTION_KEYS[n])) return ACTION_KEYS[n];\n }\n return null;\n };\n // A page action's popup is per tab, and both engines require the\n // tabId. Always resolves to a string.\n var getActionPopup = function (key, tab, cb) {\n var details = key === \"page_action\" ? {tabId: tab && tab.id} : {};\n nsCall(ACTION_NAMESPACES[key], \"getPopup\", [details], function (err, p) {\n cb(err ? \"\" : (p || \"\"));\n });\n };\n var resolveActiveTab = function (a, cb) {\n if (a && typeof a.tabId === \"number\") {\n try { chrome.tabs.get(a.tabId, function (t) { cb(t || {id: a.tabId}); }); return; }\n catch (e) {\n // Ignore\n }\n }\n try { chrome.tabs.query({active: true, lastFocusedWindow: true}, function (tabs) { cb((tabs && tabs[0]) || undefined); }); }\n catch (e) { cb(undefined); }\n };\n // Replaying a listener carries no user gesture, so activeTab is never\n // granted. Warn when the manifest declares it.\n var activeTabWarning = function () {\n try {\n var m = chrome.runtime.getManifest();\n var perms = (m && m.permissions) || [];\n if (perms.indexOf(\"activeTab\") !== -1) {\n return \"replayed without a user gesture: activeTab is NOT granted, so APIs that depend on it (scripting on the active tab, captureVisibleTab) behave differently than a real click\";\n }\n } catch (e) {\n // Ignore\n }\n return null;\n };\n if (surface === \"popup\") {\n var popupKey = actionManifestKey();\n var popupNS = popupKey && ACTION_NAMESPACES[popupKey];\n if (popupNS && chrome[popupNS] && chrome[popupNS].openPopup) {\n nsCall(popupNS, \"openPopup\", [], function (err) {\n if (err) {\n var openMsg = (err && err.message) || err;\n replyErr(cmdId, \"Unsupported\", \"openPopup: \" + openMsg, openRefusalCode(openMsg));\n } else replyOk(cmdId, {opened: \"popup\"});\n });\n } else { replyErr(cmdId, \"Unsupported\", (popupNS || \"action\") + \".openPopup not available\", \"api_unavailable\"); }\n } else if (surface === \"options\") {\n // Chrome answers a manifest with no options page through lastError\n // and still calls back, so the callback must read it.\n try {\n chrome.runtime.openOptionsPage(function () {\n var optErr = chrome.runtime.lastError;\n if (optErr) {\n replyErr(cmdId, \"Unsupported\", \"openOptionsPage: \" + (optErr.message || optErr) + \" (the manifest declares no options_ui or options_page)\", \"surface_not_declared\");\n } else replyOk(cmdId, {opened: \"options\"});\n });\n }\n catch (e) { replyErr(cmdId, \"Unsupported\", \"openOptionsPage: \" + e); }\n } else if (surface === \"sidebar\") {\n // The two member reads below are exactly what the Safari\n // unsupported-API scan looks for, and this runtime is prepended to\n // the background asset at PROCESS_ASSETS_STAGE_REPORT + 101, after\n // that scan runs at SUMMARIZE + 1. Move the injection earlier and\n // every Safari dev session warns about this line.\n if (chrome.sidePanel && chrome.sidePanel.open && chrome.windows) {\n chrome.windows.getCurrent(function (w) {\n nsCall(\"sidePanel\", \"open\", [{windowId: w.id}], function (err) {\n if (err) {\n var sideMsg = (err && err.message) || err;\n replyErr(cmdId, \"Unsupported\", \"sidePanel.open: \" + sideMsg, openRefusalCode(sideMsg));\n } else replyOk(cmdId, {opened: \"sidebar\"});\n });\n });\n } else { replyErr(cmdId, \"Unsupported\", \"sidePanel not available (engine: \" + engineName() + \")\", \"api_unavailable\"); }\n } else if (surface === \"action\") {\n // With a popup the click opens it; without one, replay the\n // onClicked listeners captured at install time. The answer names\n // the manifest key the click went through.\n var actionKey = actionManifestKey();\n if (actionKey) {\n var actionNS = ACTION_NAMESPACES[actionKey];\n var clicked = actionClickedListeners[actionKey];\n resolveActiveTab(args, function (tab) {\n getActionPopup(actionKey, tab, function (popup) {\n if (popup) {\n nsCall(actionNS, \"openPopup\", [], function (err) {\n if (err) {\n var actMsg = (err && err.message) || err;\n replyErr(cmdId, \"Unsupported\", \"openPopup: \" + actMsg, openRefusalCode(actMsg));\n } else replyOk(cmdId, {triggered: \"popup\", manifestKey: actionKey});\n });\n } else if (clicked.length) {\n var fired = 0;\n for (var i = 0; i < clicked.length; i++) {\n try { clicked[i](tab); fired++; } catch (e) {\n // Ignore\n }\n }\n var reply = {triggered: \"onClicked\", listeners: fired, gesture: false, manifestKey: actionKey};\n var warning = activeTabWarning();\n if (warning) reply.warning = warning;\n replyOk(cmdId, reply);\n } else {\n replyErr(cmdId, \"Unsupported\", actionKey + \" has no popup and no \" + actionNS + \".onClicked listener registered\");\n }\n });\n });\n } else { replyErr(cmdId, \"Unsupported\", \"the manifest declares no action, browser_action or page_action (engine: \" + engineName() + \")\", \"surface_not_declared\"); }\n } else if (surface === \"command\") {\n var commandName = (args && args.name) || undefined;\n if (!commandListeners.length) {\n replyErr(cmdId, \"Unsupported\", \"no chrome.commands.onCommand listener registered\");\n } else {\n resolveActiveTab(args, function (tab) {\n var fired = 0;\n for (var i = 0; i < commandListeners.length; i++) {\n try { commandListeners[i](commandName, tab); fired++; } catch (e) {\n // Ignore\n }\n }\n replyOk(cmdId, {triggered: \"command\", command: commandName || null, listeners: fired, gesture: false});\n });\n }\n } else { replyErr(cmdId, \"BadRequest\", \"unknown surface: \" + surface); }\n return;\n }\n if (op === \"tabs.query\") {\n nsCall(\"tabs\", \"query\", [args || {}], function (err, tabs) {\n if (err) { replyErr(cmdId, \"TabsError\", (err && err.message) || err); return; }\n replyOk(cmdId, (tabs || []).map(function (t) { return {id: t.id, url: t.url, title: t.title, active: t.active, windowId: t.windowId}; }));\n });\n return;\n }\n // Navigation is a static tabs.* call, never an eval: an MV3 background\n // (Safari's included) refuses eval by CSP, so a url must reach a tab\n // through code that shipped with the bridge. A tabId targets that\n // tab, newTab opens one, and otherwise the active tab is reused.\n if (op === \"tabs.navigate\") {\n var navUrl = typeof args.url === \"string\" ? args.url : \"\";\n if (!navUrl) { replyErr(cmdId, \"BadRequest\", \"tabs.navigate needs a url\"); return; }\n var navDone = function (err, tab, created) {\n if (err) { replyTabsFailure(cmdId, err, \"TabsError\", navUrl); return; }\n replyOk(cmdId, {tabId: tab && tab.id != null ? tab.id : null, url: navUrl, created: !!created});\n };\n if (target.tabId != null) {\n nsCall(\"tabs\", \"update\", [target.tabId, {url: navUrl}], function (err, tab) { navDone(err, tab, false); });\n return;\n }\n if (args.newTab) {\n nsCall(\"tabs\", \"create\", [{url: navUrl, active: args.active !== false}], function (err, tab) { navDone(err, tab, true); });\n return;\n }\n nsCall(\"tabs\", \"query\", [{active: true, currentWindow: true}], function (qErr, tabs) {\n var active = !qErr && tabs && tabs[0];\n if (active && active.id != null) {\n nsCall(\"tabs\", \"update\", [active.id, {url: navUrl}], function (err, tab) { navDone(err, tab, false); });\n } else {\n nsCall(\"tabs\", \"create\", [{url: navUrl}], function (err, tab) { navDone(err, tab, true); });\n }\n });\n return;\n }\n if (op === \"inspect\") {\n // Extract a DOM snapshot from the target page via chrome.scripting\n // (CDP-free). Closed shadow roots need CDP; here we read open ones.\n if ((ctx === \"content\" || ctx === \"page\") && target.tabId && chrome.scripting) {\n var maxBytes = (args && args.maxBytes) || 262144;\n var includeHtml = !args || !args.include || args.include.indexOf(\"html\") !== -1;\n nsCall(\"scripting\", \"executeScript\", [{\n target: {tabId: target.tabId},\n world: ctx === \"page\" ? \"MAIN\" : \"ISOLATED\",\n func: function (wantHtml, cap) {\n function countShadow(root) {\n var n = 0, els = root.querySelectorAll(\"*\");\n for (var i = 0; i < els.length; i++) { if (els[i].shadowRoot) { n++; n += countShadow(els[i].shadowRoot); } }\n return n;\n }\n var doc = document;\n var roots = doc.querySelectorAll('#extension-root,[data-extension-root]');\n var out = {\n url: location.href,\n title: doc.title,\n summary: {\n htmlLength: doc.documentElement.outerHTML.length,\n scriptCount: doc.querySelectorAll(\"script\").length,\n styleCount: doc.querySelectorAll(\"style,link[rel=stylesheet]\").length,\n extensionRootCount: roots.length,\n openShadowRoots: countShadow(doc),\n bodyChildCount: doc.body ? doc.body.children.length : 0\n }\n };\n if (wantHtml) {\n var html = doc.documentElement.outerHTML;\n if (cap > 0 && html.length > cap) { out.html = html.slice(0, cap); out.htmlTruncated = true; }\n else { out.html = html; }\n }\n return out;\n },\n args: [includeHtml, maxBytes]\n }], function (err, res) {\n if (err) { replyInjectionErr(cmdId, err); return; }\n var snap = res && res[0] ? res[0].result : undefined;\n if (snap == null) { replyErr(cmdId, \"TargetNotFound\", \"no injectable frame returned a snapshot for tab \" + target.tabId + \" (restricted page, or outside host_permissions)\"); return; }\n replyOk(cmdId, fitSnapshot(snap));\n });\n } else if (ctx === \"popup\" || ctx === \"options\" || ctx === \"sidebar\" || ctx === \"devtools\" || ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") {\n // The SW can't read a surface page's DOM; ask the surface's own\n // in-bundle relay (only the open, matching-context page responds).\n chrome.runtime.sendMessage(\n {__extjsInspectRequest: true, target: target, args: args},\n function (resp) {\n classifySurfaceFailure(ctx, resp, function (relayErr) {\n if (relayErr) {\n replyErr(cmdId, \"Unsupported\", relayErr.message, relayErr.code);\n } else if (resp.ok) {\n replyOk(cmdId, fitSnapshot(resp.value));\n } else {\n replyErr(cmdId, (resp.error && resp.error.name) || \"InspectError\", (resp.error && resp.error.message) || \"inspect failed\");\n }\n });\n }\n );\n } else if ((ctx === \"content\" || ctx === \"page\") && target.tabId) {\n replyErr(cmdId, \"Unsupported\", scriptingMissingReason(target.tabId), \"scripting_unavailable\");\n } else if (ctx === \"background\") {\n replyErr(cmdId, \"Unsupported\", \"the service worker has no DOM; inspect a content/page (with --tab) or an open surface\");\n } else {\n replyErr(cmdId, \"Unsupported\", \"inspect of \" + ctx + \" requires a tabId (content/page) or an open surface\");\n }\n return;\n }\n replyErr(cmdId, \"BadRequest\", \"unknown op: \" + op);\n } catch (e) {\n replyErr(cmdId, \"ExecutorError\", e);\n }\n }\n\n function noopLastError() { try { void g.chrome.runtime.lastError; } catch (e) {\n // Ignore\n } }\n\n // Only http(s)/file/ftp tabs can run a content script; skip chrome://, the\n // extension's own pages, about:blank, etc.\n function isInjectableUrl(url) {\n return typeof url === \"string\" && /^(https?|file|ftp):/i.test(url);\n }\n\n function stringList(value) {\n return Array.isArray(value) ? value.filter(function (v) { return typeof v === \"string\"; }) : [];\n }\n\n // The manifest glob dialect: * is any run of characters, ? exactly one,\n // and the pattern covers the whole url.\n function globMatches(glob, text) {\n var gi = 0, ti = 0, star = -1, mark = 0;\n while (ti < text.length) {\n if (gi < glob.length && (glob.charAt(gi) === \"?\" || glob.charAt(gi) === text.charAt(ti))) { gi++; ti++; }\n else if (gi < glob.length && glob.charAt(gi) === \"*\") { star = gi++; mark = ti; }\n else if (star !== -1) { gi = star + 1; ti = ++mark; }\n else return false;\n }\n while (gi < glob.length && glob.charAt(gi) === \"*\") gi++;\n return gi === glob.length;\n }\n\n // include_globs narrows matches and exclude_globs removes from them, the\n // same way the browser decides where the built extension runs.\n function passesGlobs(url, includeGlobs, excludeGlobs) {\n var u = String(url || \"\");\n var i;\n if (includeGlobs.length) {\n var included = false;\n for (i = 0; i < includeGlobs.length; i++) {\n if (globMatches(includeGlobs[i], u)) { included = true; break; }\n }\n if (!included) return false;\n }\n for (i = 0; i < excludeGlobs.length; i++) {\n if (globMatches(excludeGlobs[i], u)) return false;\n }\n return true;\n }\n\n // Re-inject one declared entry's fresh files into every matching open tab.\n // exclude_matches MUST be honored: query the excludes and subtract them.\n // opts.completeOnly skips a tab still loading: Chrome injects the static\n // script into it when it lands, and a second copy here would run twice.\n function reinjectContentScriptEntry(entry, opts) {\n var chrome = g.chrome;\n var completeOnly = !!(opts && opts.completeOnly);\n var matches = (entry && entry.matches) || [];\n if (!Array.isArray(matches) || !matches.length) return;\n var excludeMatches = (entry && entry.exclude_matches) || [];\n var includeGlobs = stringList(entry && entry.include_globs);\n var excludeGlobs = stringList(entry && entry.exclude_globs);\n var jsFiles = ((entry && entry.js) || []).filter(function (f) { return typeof f === \"string\"; });\n var cssFiles = ((entry && entry.css) || []).filter(function (f) { return typeof f === \"string\"; });\n if (!jsFiles.length && !cssFiles.length) return;\n var world = entry.world === \"MAIN\" ? \"MAIN\" : \"ISOLATED\";\n var allFrames = !!entry.all_frames;\n function injectInto(excludedTabIds) {\n try {\n chrome.tabs.query({url: matches}, function (tabs) {\n var err = null;\n try { err = chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n if (err || !tabs) return;\n for (var i = 0; i < tabs.length; i++) {\n (function (tab) {\n if (!tab || tab.id == null || !isInjectableUrl(tab.url)) return;\n if (excludedTabIds[tab.id]) return;\n if (!passesGlobs(tab.url, includeGlobs, excludeGlobs)) return;\n if (completeOnly && tab.status === \"loading\") return;\n var target = {tabId: tab.id, allFrames: allFrames};\n if (cssFiles.length && chrome.scripting.insertCSS) {\n try { chrome.scripting.insertCSS({target: target, files: cssFiles}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n if (jsFiles.length && chrome.scripting.executeScript) {\n try {\n chrome.scripting.executeScript(\n {target: target, files: jsFiles, world: world, injectImmediately: true},\n noopLastError\n );\n } catch (e) {\n // Ignore\n }\n }\n })(tabs[i]);\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n if (Array.isArray(excludeMatches) && excludeMatches.length) {\n try {\n chrome.tabs.query({url: excludeMatches}, function (excludedTabs) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var excluded = {};\n if (excludedTabs) {\n for (var i = 0; i < excludedTabs.length; i++) {\n if (excludedTabs[i] && excludedTabs[i].id != null) excluded[excludedTabs[i].id] = true;\n }\n }\n injectInto(excluded);\n });\n return;\n } catch (e) {\n // Ignore\n }\n }\n injectInto({});\n }\n\n // Re-inject all content scripts into their open tabs. Reads the manifest\n // FROM DISK: getManifest() is frozen and dev filenames are content-hashed.\n // opts.register false skips the dynamic registration: at boot the static\n // manifest already names the current files, and a copy injects twice.\n function reinjectContentScripts(onDone, opts) {\n var chrome = g.chrome;\n var register = !opts || opts.register !== false;\n try {\n if (typeof g.fetch !== \"function\" || !chrome.scripting) return false;\n g.fetch(chrome.runtime.getURL(\"manifest.json\"), {cache: \"no-store\"})\n .then(function (r) { return r.json(); })\n .then(function (manifest) {\n var entries = (manifest && manifest.content_scripts) || [];\n for (var i = 0; i < entries.length; i++) reinjectContentScriptEntry(entries[i], opts);\n if (register) reregisterForFutureNavigations(entries);\n if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } }\n })\n .catch(function () {\n // Ignore\n });\n return true;\n } catch (e) { return false; }\n }\n\n function mapRunAt(runAt) {\n if (runAt === \"document_start\") return \"document_start\";\n if (runAt === \"document_end\") return \"document_end\";\n return \"document_idle\";\n }\n\n // Re-register content scripts dynamically at the fresh files, so tabs\n // opened AFTER an edit also get the new build. Idempotent per entry id.\n function reregisterForFutureNavigations(entries) {\n var chrome = g.chrome;\n if (\n !chrome.scripting ||\n !chrome.scripting.registerContentScripts ||\n !chrome.scripting.getRegisteredContentScripts\n ) return;\n\n var scripts = [];\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i] || {};\n if (!Array.isArray(e.matches) || !e.matches.length) continue;\n // registerContentScripts has no glob keys, so a copy of a globbed\n // entry would run on pages the built extension never reaches.\n if (stringList(e.include_globs).length || stringList(e.exclude_globs).length) continue;\n var js = (e.js || []).filter(function (f) { return typeof f === \"string\"; });\n var css = (e.css || []).filter(function (f) { return typeof f === \"string\"; });\n if (!js.length && !css.length) continue;\n // Every field is sent: updateContentScripts keeps any key left out, so\n // a dropped exclude_matches, css file or fallback would outlive the edit.\n scripts.push({\n id: \"extjs-dev-cs-\" + i,\n matches: e.matches,\n excludeMatches: (e.exclude_matches || []).filter(function (p) { return typeof p === \"string\"; }),\n js: js,\n css: css,\n runAt: mapRunAt(e.run_at),\n allFrames: !!e.all_frames,\n world: e.world === \"MAIN\" ? \"MAIN\" : \"ISOLATED\",\n matchOriginAsFallback: e.match_origin_as_fallback === true,\n // A browser restart loads the static manifest fresh; a copy that\n // outlived the session would inject every page twice.\n persistAcrossSessions: false\n });\n }\n if (!scripts.length) return;\n\n try {\n chrome.scripting.getRegisteredContentScripts(function (existing) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var have = {};\n if (existing) for (var k = 0; k < existing.length; k++) have[existing[k].id] = true;\n var toRegister = [], toUpdate = [];\n for (var j = 0; j < scripts.length; j++) {\n (have[scripts[j].id] ? toUpdate : toRegister).push(scripts[j]);\n }\n if (toRegister.length) {\n try { chrome.scripting.registerContentScripts(toRegister, noopLastError); } catch (e) {\n // Ignore\n }\n }\n if (toUpdate.length) {\n try { chrome.scripting.updateContentScripts(toUpdate, noopLastError); } catch (e) {\n // Ignore\n }\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // The dev content-script runtime (plugin-reload) owns registration, the\n // boot heal and the tab reloads when its registry exists; absent, the\n // manifest-based paths below stay in charge.\n function devContentScripts() {\n try { return g.__extjsDevContentScripts || null; } catch (e) { return null; }\n }\n\n // An extension reload unloads chrome_url_overrides, and Chromium leaves\n // the open override tabs on its stock page. Only a fresh navigation to the\n // browser url (a tab reload does not) picks the override up again.\n var OVERRIDE_TABS_KEY = \"__extjsDevOverrideTabs\";\n var OVERRIDE_KINDS = [\"newtab\", \"history\", \"bookmarks\"];\n\n function overriddenKinds() {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { return []; }\n var o = m && m.chrome_url_overrides;\n var out = [];\n if (!o) return out;\n for (var i = 0; i < OVERRIDE_KINDS.length; i++) {\n if (typeof o[OVERRIDE_KINDS[i]] === \"string\" && o[OVERRIDE_KINDS[i]]) out.push(OVERRIDE_KINDS[i]);\n }\n return out;\n }\n\n // chrome://newtab/, edge://history and the like. Gecko shows about: urls\n // there, which this never matches, so other engines record nothing.\n function overrideKindOf(url, kinds) {\n var match = /^[a-z-]+:[/][/]([a-z]+)[/]?(?:[?#].*)?$/.exec(String(url || \"\"));\n return match && kinds.indexOf(match[1]) !== -1 ? match[1] : null;\n }\n\n // Records the open override tabs for the next generation and answers with\n // them. The guard keeps a silent tabs.query from blocking the reload.\n function rememberOverrideTabs(cb) {\n var chrome = g.chrome;\n var answered = false;\n var guard = null;\n var answer = function (list) {\n if (answered) return;\n answered = true;\n if (guard) { try { clearTimeout(guard); } catch (e) {\n // Ignore\n } }\n try { cb(list); } catch (e) {\n // Ignore\n }\n };\n var kinds = overriddenKinds();\n if (!kinds.length || !chrome.tabs || !chrome.tabs.query || !chrome.storage || !chrome.storage.local) return answer([]);\n try { guard = setTimeout(function () { answer([]); }, 1000); } catch (e) {\n // Ignore\n }\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n var list = [];\n for (var i = 0; tabs && i < tabs.length; i++) {\n var t = tabs[i];\n var kind = t && t.id != null ? overrideKindOf(t.url, kinds) : null;\n if (kind) list.push({tabId: t.id, surface: kind, url: t.url});\n }\n if (!list.length) return answer(list);\n try {\n var rec = {};\n rec[OVERRIDE_TABS_KEY] = {at: Date.now(), tabs: list};\n chrome.storage.local.set(rec, function () { noopLastError(); answer(list); });\n } catch (e) { answer([]); }\n });\n } catch (e) { answer([]); }\n }\n\n // Shared by every path that restarts the extension, so none of them\n // strands the override tabs.\n function restartExtension(delayMs, onRecorded) {\n // Every restart path flags the next generation's heal, so open tabs get\n // their content scripts back whichever path asked for the reload.\n try {\n if (g.chrome && g.chrome.storage && g.chrome.storage.local) {\n g.chrome.storage.local.set({__extjsDevPendingReinject: Date.now()}, noopLastError);\n }\n } catch (e) {\n // Ignore\n }\n rememberOverrideTabs(function (list) {\n if (onRecorded) { try { onRecorded(list); } catch (e) {\n // Ignore\n } }\n try { setTimeout(function () { try { g.chrome.runtime.reload(); } catch (e) {\n // Ignore\n } }, delayMs); } catch (e) {\n // Ignore\n }\n });\n }\n g.__extjsDevRestartExtension = restartExtension;\n\n // The new generation sends each recorded tab back to its browser url, once,\n // unless the tab has navigated elsewhere since.\n function restoreOverrideTabsAtBoot() {\n var chrome = g.chrome;\n if (!chrome || !chrome.storage || !chrome.storage.local || !chrome.tabs || !chrome.tabs.update) return;\n chrome.storage.local.get(OVERRIDE_TABS_KEY, function (res) {\n noopLastError();\n var rec = res && res[OVERRIDE_TABS_KEY];\n if (!rec || typeof rec !== \"object\" || !Array.isArray(rec.tabs)) return;\n try { chrome.storage.local.remove(OVERRIDE_TABS_KEY, noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof rec.at !== \"number\" || Date.now() - rec.at > 30000) return;\n var kinds = overriddenKinds();\n setTimeout(function () {\n for (var i = 0; i < rec.tabs.length; i++) {\n (function (t) {\n if (!t || t.tabId == null || kinds.indexOf(t.surface) === -1) return;\n var go = function () {\n try { chrome.tabs.update(t.tabId, {url: t.url}, noopLastError); } catch (e) {\n // Ignore\n }\n };\n if (!chrome.tabs.get) return go();\n try {\n chrome.tabs.get(t.tabId, function (tab) {\n noopLastError();\n if (tab && overrideKindOf(tab.url, kinds) === t.surface) go();\n });\n } catch (e) {\n // Ignore\n }\n })(rec.tabs[i]);\n }\n }, 250);\n });\n }\n\n // Dev-loop reload without the CDP controller: content-scripts reload the\n // matching tabs at the new bundle, or re-inject in place where no registry\n // exists; service-worker/full/manifest restart the extension.\n function performDevReload(type, onDone, frame) {\n var chrome = g.chrome;\n if (!chrome) return;\n\n var fullReload = function () {\n // restartExtension flags the next generation's heal before it reloads.\n // Deferred so in-flight frames and the tab console announcement flush\n // before the SW dies; the devtools companion confirms completion.\n restartExtension(150);\n };\n\n if (type === \"content-scripts\" && chrome.scripting && chrome.tabs && chrome.tabs.query) {\n var dev = devContentScripts();\n if (dev && typeof dev.reload === \"function\") {\n try {\n dev.reload(frame && frame.changedContentScriptEntries, function (handled) {\n if (handled) { if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } } return; }\n if (reinjectContentScripts(onDone)) return;\n fullReload();\n });\n return;\n } catch (e) {\n // Ignore\n }\n }\n if (reinjectContentScripts(onDone)) return;\n }\n\n fullReload();\n }\n\n // One server-built label travels the ReloadFrame; the announcement\n // fires HERE, next to the actual reload action, so it stays true.\n\n // console.log the reload line into every open injectable tab; the patched\n // ISOLATED-world console also lands it in the dev-server log stream.\n function announceReloadInTabs(text) {\n var chrome = g.chrome;\n if (!chrome || !chrome.tabs || !chrome.tabs.query) return;\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n if (!tabs) return;\n for (var i = 0; i < tabs.length; i++) {\n (function (tab) {\n if (!tab || tab.id == null || !isInjectableUrl(tab.url)) return;\n if (chrome.scripting && chrome.scripting.executeScript) {\n try {\n chrome.scripting.executeScript(\n {target: {tabId: tab.id}, func: function (t) { console.log(t); }, args: [text]},\n noopLastError\n );\n return;\n } catch (e) {\n // Ignore\n }\n }\n // MV2 fallback (Firefox without the scripting API).\n if (chrome.tabs.executeScript) {\n try {\n chrome.tabs.executeScript(tab.id, {code: \"console.log(\" + JSON.stringify(text) + \");\"}, noopLastError);\n } catch (e) {\n // Ignore\n }\n }\n })(tabs[i]);\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // The scripts-replay shim (plugin-reload) keeps the SW's own\n // executeScript registry; the replay is fire-and-forget by design.\n function replayProgrammaticScripts(changedScriptFiles) {\n if (!Array.isArray(changedScriptFiles) || changedScriptFiles.length === 0) return;\n var replay = g.__extjsScriptsReplay;\n if (typeof replay !== \"function\") return;\n try {\n var outcome = replay(changedScriptFiles);\n if (outcome && typeof outcome.then === \"function\") {\n outcome.then(null, function () {});\n }\n } catch (e) {\n // Ignore\n }\n }\n\n function handleDevReloadFrame(frame) {\n var kind = frame.reloadType || \"full\";\n var label = typeof frame.label === \"string\" ? frame.label : \"\";\n // The server always builds the label; the kind-derived fallback only\n // covers a malformed frame so the announcement stays truthful.\n var fallback = kind === \"content-scripts\" ? \"content_script\"\n : kind === \"service-worker\" ? \"service_worker\"\n : \"extension\";\n var announced = \"[Extension.js] Reloading \" + (label || fallback) + \"\u2026\";\n\n // Receipt for the broker: proves this SW's message pump processed the\n // frame (a socket write proves nothing). Sent FIRST, so a full reload\n // cannot tear the worker down between the receipt and the reload, and\n // the correlation id is echoed so it confirms only this broadcast.\n var ack = {type: \"reload-ack\", reloadType: kind, label: label};\n if (frame.reloadId) ack.reloadId = frame.reloadId;\n send(ack);\n\n // A scripts/ bundle edit: re-run the executeScript calls that named it\n // on their recorded tabs, before any reload decision below.\n replayProgrammaticScripts(frame.changedScriptFiles);\n\n if (kind === \"page\") {\n // Notify-only: rspack-dev-server's livereload refreshes the open\n // surface; reloading the extension here would race it.\n return;\n }\n\n announceReloadInTabs(announced);\n performDevReload(kind, function () {}, frame);\n }\n\n function sanitize(args) {\n var out = [];\n for (var i = 0; i < args.length; i++) {\n var p = args[i];\n try {\n if (typeof p === \"string\") out.push(p.length > 2048 ? p.slice(0, 2048) + \"...\" : p);\n else if (p instanceof Error) out.push(p.name + \": \" + p.message);\n else out.push(JSON.stringify(p));\n } catch (e) {\n out.push(String(p));\n }\n if (out.join(\" \").length > 8192) break;\n }\n return out;\n }\n\n // While an earlier context's parked lines replay, this context's own\n // frames wait in the queue so the agent reads them in the order written.\n var replaying = false;\n\n function flush() {\n while (queue.length && open && socket && !replaying) {\n var f = queue.shift();\n try { socket.send(JSON.stringify(f)); } catch (e) { break; }\n }\n }\n\n function send(frame) {\n if (open && socket && !replaying) {\n try { socket.send(JSON.stringify(frame)); return; } catch (e) {\n // Ignore\n }\n }\n if (queue.length < MAX_QUEUE) queue.push(frame);\n parkPendingError(frame);\n }\n\n // The queue above lives in this context's memory only, so a background\n // that throws while it evaluates dies with the error still queued: the\n // socket has not finished its handshake yet. Park log frames in extension\n // storage too, where the NEXT context to connect can ship them.\n // Best effort by construction: the write is asynchronous, so a teardown\n // can cut it before the browser records anything.\n var parkedErrors = [];\n // What an earlier context parked and this one has not shipped yet. Null\n // until read: the key is rewritten whole, so a write before the read\n // would erase the lines a background that just unloaded left behind.\n var inheritedParked = null;\n function storageLocalArea() {\n try {\n var ns = (g.chrome && g.chrome.storage) || (g.browser && g.browser.storage);\n var area = ns && ns.local;\n if (!area || typeof area.get !== \"function\" || typeof area.set !== \"function\") return null;\n return area;\n } catch (e) { return null; }\n }\n function trimParked(list) {\n while (list.length > MAX_PENDING_ERRORS) {\n var dropped = false;\n for (var i = 0; i < list.length; i++) {\n var ev = list[i] && list[i].event;\n if (!ev || ev.level !== \"error\") { list.splice(i, 1); dropped = true; break; }\n }\n if (!dropped) list.shift();\n }\n return list;\n }\n function parkedHere(id) {\n for (var i = 0; i < parkedErrors.length; i++) {\n var ev = parkedErrors[i] && parkedErrors[i].event;\n if (ev && ev.id === id) return true;\n }\n return false;\n }\n function replayable(frame) {\n var ev = frame && frame.event;\n if (!ev || ev.runId !== INSTANCE_ID) return false;\n if (parkedHere(ev.id)) return false;\n return typeof ev.timestamp === \"number\" && Date.now() - ev.timestamp <= PENDING_ERROR_TTL;\n }\n // The whole list is rewritten on every park, so two lines in one turn\n // cannot lose each other to a read-modify-write, and the cap holds.\n function writeParked() {\n if (inheritedParked === null) return;\n var area = storageLocalArea();\n if (!area) return;\n var items = {};\n items[PENDING_ERRORS_KEY] = trimParked(inheritedParked.concat(parkedErrors));\n try { area.set(items, noopLastError); } catch (e) {\n // Ignore\n }\n }\n function parkPendingError(frame) {\n if (open) return;\n if (!frame || frame.type !== \"log\" || !frame.event) return;\n if (!storageLocalArea()) return;\n parkedErrors.push(frame);\n trimParked(parkedErrors);\n writeParked();\n }\n function readParked(area, onList) {\n var read = false;\n function onRead(res) {\n if (read) return;\n read = true;\n var list = res && res[PENDING_ERRORS_KEY];\n onList(Array.isArray(list) ? list : []);\n }\n try {\n var ret = area.get(PENDING_ERRORS_KEY, function (res) { noopLastError(); onRead(res); });\n if (ret && typeof ret.then === \"function\") ret.then(onRead, function () { onRead(null); });\n } catch (e) {\n onRead(null);\n }\n }\n function adoptInheritedParked() {\n var area = storageLocalArea();\n if (!area) { inheritedParked = []; return; }\n readParked(area, function (list) {\n if (inheritedParked !== null) return;\n inheritedParked = [];\n for (var i = 0; i < list.length; i++) {\n if (replayable(list[i])) inheritedParked.push(list[i]);\n }\n if (parkedErrors.length && !open) writeParked();\n });\n }\n // Ship what an earlier context parked and never got to send. Entries from\n // another build (a different instance id) or from an older run are dropped,\n // and the key is cleared on read so one failure is reported once. They\n // were written before anything this context queued, so they go first and\n // straight to the socket; done() then releases this context's own queue.\n var PENDING_READ_TIMEOUT = 1000;\n function flushPendingErrors(done) {\n var area = storageLocalArea();\n if (!area) { done(); return; }\n var finished = false;\n function finish() {\n if (finished) return;\n finished = true;\n done();\n }\n try {\n setTimeout(finish, PENDING_READ_TIMEOUT);\n } catch (e) {\n // Ignore\n }\n readParked(area, function (list) {\n if (finished) return;\n if (list.length) {\n try {\n if (typeof area.remove === \"function\") area.remove(PENDING_ERRORS_KEY, noopLastError);\n } catch (e) {\n // Ignore\n }\n }\n var earlier = [];\n for (var i = 0; i < list.length; i++) {\n if (replayable(list[i])) earlier.push(list[i]);\n }\n // Shipped or queued from here on, so nothing parked so far may be\n // written back for a later context to report twice.\n inheritedParked = [];\n parkedErrors = [];\n if (open && socket) {\n for (var j = 0; j < earlier.length; j++) {\n try { socket.send(JSON.stringify(earlier[j])); } catch (e) {\n // Ignore\n }\n }\n } else {\n queue = earlier.concat(queue).slice(0, MAX_QUEUE);\n }\n finish();\n });\n }\n\n // The baked PORT is a snapshot of an ephemeral port. After a dev-server\n // restart, the port file shipped in the unpacked extension names the\n // live one, and unpacked resources are read from disk on every fetch.\n function refreshControlPort(done) {\n try {\n var runtime = (g.chrome && g.chrome.runtime) || (g.browser && g.browser.runtime);\n if (!runtime || typeof runtime.getURL !== \"function\" || typeof g.fetch !== \"function\") { done(); return; }\n g.fetch(runtime.getURL(\"extension-js-control.json\"), {cache: \"no-store\"})\n .then(function (res) { return res.json(); })\n .then(function (data) {\n var next = data && parseInt(data.port, 10);\n if (next && next > 0 && next < 65536 && next !== PORT) PORT = next;\n done();\n })\n .catch(function () { done(); });\n } catch (e) { done(); }\n }\n\n function schedule() {\n var delay = backoff;\n backoff = Math.min(backoff * 2, MAX_BACKOFF);\n connectFailures++;\n try {\n setTimeout(function () {\n // Two straight failures make the baked port suspect (a restarted\n // server dials out on a new port): re-resolve before re-dialing.\n if (connectFailures >= 2) refreshControlPort(connect);\n else connect();\n }, delay);\n } catch (e) {\n // Ignore\n }\n }\n\n function connect() {\n try {\n socket = new WS(\"ws://\" + HOST + \":\" + PORT + \"/extjs-control\");\n } catch (e) {\n schedule();\n return;\n }\n socket.onopen = function () {\n open = true;\n backoff = 250;\n connectFailures = 0;\n try {\n socket.send(JSON.stringify({type: \"hello\", v: 1, role: \"producer\", instanceId: INSTANCE_ID, acksReloads: true}));\n } catch (e) {\n // Ignore\n }\n // Hello goes first, then whatever a previous context parked before it\n // died, then this context's own queue.\n replaying = true;\n flushPendingErrors(function () {\n replaying = false;\n flush();\n });\n };\n socket.onmessage = function (ev) {\n var frame;\n try { frame = JSON.parse(typeof ev.data === \"string\" ? ev.data : \"\"); } catch (e) { return; }\n if (frame && frame.type === \"command\") {\n try { executeCommand(frame); } catch (e) { replyErr(frame.cmdId, \"ExecutorError\", e); }\n } else if (frame && frame.type === \"reload\") {\n // Dev-loop reload broadcast (see broker.broadcastReload).\n // Fire-and-forget: no result frame is expected.\n try { handleDevReloadFrame(frame); } catch (e) {\n // Ignore\n }\n } else if (frame && frame.type === \"ping\") {\n // Server keepalive: merely RECEIVING this resets the MV3 SW's ~30s\n // idle timer (Chrome 116+), keeping it reachable. Nothing to do.\n }\n };\n socket.onclose = function () {\n open = false;\n socket = null;\n schedule();\n };\n socket.onerror = function () {\n try { socket && socket.close(); } catch (e) {\n // Ignore\n }\n };\n }\n\n // Uncaught errors don't route through the patched console; the handlers\n // below forward them, using these signatures to skip already-logged throws.\n var recentErrorSigs = [];\n function errorSig(message, stack) {\n return String(message == null ? \"\" : message) + \"::\" + String(stack == null ? \"\" : stack).slice(0, 200);\n }\n function noteErrorSig(sig) {\n recentErrorSigs.push({sig: sig, t: Date.now()});\n if (recentErrorSigs.length > 50) recentErrorSigs.shift();\n }\n function errorSigSeenRecently(sig) {\n var now = Date.now();\n for (var i = recentErrorSigs.length - 1; i >= 0; i--) {\n if (now - recentErrorSigs[i].t > 3000) { recentErrorSigs.splice(i, 1); continue; }\n if (recentErrorSigs[i].sig === sig) return true;\n }\n return false;\n }\n\n LEVELS.forEach(function (level) {\n var orig = typeof consoleRef[level] === \"function\"\n ? consoleRef[level].bind(consoleRef)\n : function () {};\n consoleRef[level] = function () {\n try {\n if (level === \"error\") {\n for (var ai = 0; ai < arguments.length; ai++) {\n if (arguments[ai] instanceof Error) noteErrorSig(errorSig(arguments[ai].message, arguments[ai].stack));\n }\n }\n if (!isDevServerChatter(level, arguments)) send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: level,\n context: CONTEXT,\n messageParts: sanitize([].slice.call(arguments)),\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n return orig.apply(consoleRef, arguments);\n };\n });\n\n // Forward uncaught throws / unhandled rejections as level:\"error\", deduped\n // so a logged-then-rethrown Error emits once.\n function shipUncaughtError(message, stack, url) {\n try {\n var sig = errorSig(message, stack);\n if (errorSigSeenRecently(sig)) return;\n noteErrorSig(sig);\n send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: \"error\",\n context: CONTEXT,\n messageParts: sanitize([String(message) + (stack ? \"\\n\" + stack : \"\")]),\n url: url,\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n try {\n if (typeof g.addEventListener === \"function\") {\n g.addEventListener(\"error\", function (ev) {\n var err = ev && ev.error;\n var message = (err && err.message) || (ev && ev.message) || \"Uncaught error\";\n shipUncaughtError(message, err && err.stack, ev && ev.filename);\n });\n g.addEventListener(\"unhandledrejection\", function (ev) {\n var reason = ev && ev.reason;\n var message = (reason && reason.message) || (reason != null ? String(reason) : \"Unhandled rejection\");\n shipUncaughtError(\"Unhandled promise rejection: \" + message, reason && reason.stack, undefined);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // Other contexts relay console logs to this SW over a NAMED runtime.Port:\n // they can't open the WS under page CSP, and sendMessage can echo-loop.\n function shipRelayedLog(ev, sender) {\n try {\n send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: ev.level || \"log\",\n context: ev.context || \"content\",\n messageParts: Array.isArray(ev.messageParts) ? ev.messageParts : [],\n url: ev.url || (sender ? sender.url : undefined),\n tabId: sender && sender.tab ? sender.tab.id : undefined,\n frameId: sender ? sender.frameId : undefined,\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n try {\n var rtPort = g.chrome;\n if (rtPort && rtPort.runtime && rtPort.runtime.onConnect) {\n rtPort.runtime.onConnect.addListener(function (port) {\n if (!port || port.name !== \"__extjs-bridge-log__\") return;\n try {\n port.onMessage.addListener(function (msg) {\n if (!msg || !msg.__extjsBridgeLog) return;\n shipRelayedLog(msg.__extjsBridgeLog, port.sender);\n });\n } catch (e) {\n // Ignore\n }\n });\n }\n } catch (e) {\n // Ignore\n }\n // sendMessage path: how the devtools page relays, since its port would be\n // mistaken for the extension's own devtools connection. Also accepts any\n // surface still relaying the old way.\n try {\n var rt = g.chrome;\n if (rt && rt.runtime && rt.runtime.onMessage) {\n rt.runtime.onMessage.addListener(function (msg, sender) {\n if (!msg || !msg.__extjsBridgeLog) return;\n shipRelayedLog(msg.__extjsBridgeLog, sender);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // Dev registrations outlive runtime.reload(), while the new generation's\n // static manifest already names the current files: drop them first, or\n // every navigation from here on runs the content script twice.\n function unregisterDevContentScripts(onDone) {\n var chrome = g.chrome;\n var done = function () { if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } } };\n try {\n if (\n !chrome.scripting ||\n !chrome.scripting.getRegisteredContentScripts ||\n !chrome.scripting.unregisterContentScripts\n ) return done();\n chrome.scripting.getRegisteredContentScripts(function (existing) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var ids = [];\n if (existing) {\n for (var i = 0; i < existing.length; i++) {\n var id = existing[i] && existing[i].id;\n if (typeof id === \"string\" && id.indexOf(\"extjs-dev-cs-\") === 0) ids.push(id);\n }\n }\n if (!ids.length) return done();\n try {\n chrome.scripting.unregisterContentScripts({ids: ids}, function () { noopLastError(); done(); });\n } catch (e) { done(); }\n });\n } catch (e) { done(); }\n }\n\n // One heal per producer generation: onInstalled and the pre-reload storage\n // flag can both fire on the same boot, and each would inject once more.\n var bootHealDone = false;\n function healOpenTabsAtBoot() {\n if (bootHealDone) return;\n bootHealDone = true;\n // Firefox injects declared content scripts into open tabs on a reload\n // itself, so a heal there runs every script a second time.\n try { if (engineName() === \"firefox\") return; } catch (e) {\n // Ignore\n }\n setTimeout(function () {\n var dev = devContentScripts();\n if (dev && typeof dev.heal === \"function\") {\n try { dev.heal(); return; } catch (e) {\n // Ignore\n }\n }\n unregisterDevContentScripts(function () {\n try { reinjectContentScripts(undefined, {register: false, completeOnly: true}); } catch (e) {\n // Ignore\n }\n });\n }, 250);\n }\n\n // Chrome never injects manifest content scripts into already-open tabs, so\n // fire one reinject on onInstalled (which skips idle-stop SW wakes). Not\n // on the first install: the tabs the browser launched with load beside\n // the extension and Chrome injects them itself.\n try {\n var rtBoot = g.chrome;\n if (rtBoot && rtBoot.runtime && rtBoot.runtime.onInstalled) {\n rtBoot.runtime.onInstalled.addListener(function (details) {\n if (details && details.reason === \"install\") return;\n try { healOpenTabsAtBoot(); } catch (e) {\n // Ignore\n }\n });\n }\n } catch (e) {\n // Ignore\n }\n\n try { restoreOverrideTabsAtBoot(); } catch (e) {\n // Ignore\n }\n\n // Chromium 146 fires no onInstalled on runtime.reload() while 151 reports\n // an \"update\": the pre-reload storage flag (fresh only) covers the former.\n try {\n var stBoot = g.chrome;\n if (stBoot && stBoot.storage && stBoot.storage.local) {\n stBoot.storage.local.get(\"__extjsDevPendingReinject\", function (res) {\n noopLastError();\n var ts = res && res.__extjsDevPendingReinject;\n if (ts == null) return;\n try { stBoot.storage.local.remove(\"__extjsDevPendingReinject\", noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof ts !== \"number\" || Date.now() - ts > 30000) return;\n healOpenTabsAtBoot();\n });\n }\n } catch (e) {\n // Ignore\n }\n\n adoptInheritedParked();\n connect();\n } catch (e) {\n // Ignore\n }\n})();\n";
|
|
3
|
-
export declare const BRIDGE_RELAY_SOURCE = ";(function () {\n try {\n var g = (typeof globalThis === \"object\" && globalThis) ? globalThis : this;\n if (!g || g.__extjsBridgeRelayInstalled) return;\n\n var CONTEXT = \"__EXTJS_CONTEXT__\";\n var chrome = g.chrome;\n if (!chrome || !chrome.runtime) return;\n var canRelay = typeof chrome.runtime.connect === \"function\";\n\n g.__extjsBridgeRelayInstalled = true;\n var consoleRef = g.console || {};\n var LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\", \"trace\"];\n // Same filter as the producer: HMR chatter is not the page's output.\n function isDevServerChatter(level, args) {\n if (level === \"warn\" || level === \"error\") return false;\n var first = args && args[0];\n return typeof first === \"string\" && /^\\[(?:HMR|webpack-dev-server|rspack-dev-server)\\] /.test(first);\n }\n\n // Every engine's wording for \"this document's CSP forbids eval\". Gecko\n // says \"call to eval() blocked by CSP\", Chromium quotes the directive.\n function cspBlocksEval(message) {\n return /call to eval\\(\\)|blocked by (?:the )?CSP|Content Security Policy|unsafe-eval/i.test(String(message == null ? \"\" : message));\n }\n\n function sanitize(args) {\n var out = [];\n for (var i = 0; i < args.length; i++) {\n var p = args[i];\n try {\n if (typeof p === \"string\") out.push(p.length > 2048 ? p.slice(0, 2048) + \"...\" : p);\n else if (p instanceof Error) out.push(p.name + \": \" + p.message);\n else out.push(JSON.stringify(p));\n } catch (e) { out.push(String(p)); }\n if (out.join(\" \").length > 8192) break;\n }\n return out;\n }\n\n function here() { try { return g.location ? g.location.href : undefined; } catch (e) { return undefined; } }\n\n // The devtools page is the one surface whose port carries no sender.tab,\n // which is how a devtools extension recognizes its own devtools connection.\n // Ours would arrive first and be taken for it, so that surface sends\n // messages instead and the extension's port topology matches production.\n var relayOverPort = canRelay && CONTEXT !== \"devtools\";\n var canSend = typeof chrome.runtime.sendMessage === \"function\";\n\n function sendLog(payload) {\n if (!canSend) return;\n try {\n chrome.runtime.sendMessage({__extjsBridgeLog: payload}, function () {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // Lazy named port to the SW producer: connecting wakes an idle SW, but\n // port frames never reach the extension's own onMessage listeners.\n var logPort = null;\n function getLogPort() {\n if (!relayOverPort) return null;\n if (logPort) return logPort;\n try {\n logPort = chrome.runtime.connect({name: \"__extjs-bridge-log__\"});\n logPort.onDisconnect.addListener(function () {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n logPort = null;\n });\n } catch (e) { logPort = null; }\n return logPort;\n }\n\n // Relay one log payload to the SW producer over the named port, redialing\n // once if the port went stale (SW restarted).\n function postLog(payload) {\n if (!relayOverPort) return sendLog(payload);\n\n var p = getLogPort();\n if (!p) return;\n try {\n p.postMessage({__extjsBridgeLog: payload});\n } catch (e) {\n logPort = null;\n var p2 = getLogPort();\n if (p2) { try { p2.postMessage({__extjsBridgeLog: payload}); } catch (e2) {\n // Ignore\n } }\n }\n }\n\n // Uncaught throws / unhandled rejections never route through the patched\n // console; forward them, deduped against console.error Error signatures.\n var recentErrorSigs = [];\n function errorSig(message, stack) {\n return String(message == null ? \"\" : message) + \"::\" + String(stack == null ? \"\" : stack).slice(0, 200);\n }\n function noteErrorSig(sig) {\n recentErrorSigs.push({sig: sig, t: Date.now()});\n if (recentErrorSigs.length > 50) recentErrorSigs.shift();\n }\n function errorSigSeenRecently(sig) {\n var now = Date.now();\n for (var i = recentErrorSigs.length - 1; i >= 0; i--) {\n if (now - recentErrorSigs[i].t > 3000) { recentErrorSigs.splice(i, 1); continue; }\n if (recentErrorSigs[i].sig === sig) return true;\n }\n return false;\n }\n\n LEVELS.forEach(function (level) {\n var orig = typeof consoleRef[level] === \"function\" ? consoleRef[level].bind(consoleRef) : function () {};\n consoleRef[level] = function () {\n try {\n if (level === \"error\") {\n for (var ai = 0; ai < arguments.length; ai++) {\n if (arguments[ai] instanceof Error) noteErrorSig(errorSig(arguments[ai].message, arguments[ai].stack));\n }\n }\n if (!isDevServerChatter(level, arguments)) postLog({level: level, context: CONTEXT, messageParts: sanitize([].slice.call(arguments)), url: here()});\n } catch (e) {\n // Ignore\n }\n return orig.apply(consoleRef, arguments);\n };\n });\n\n function shipUncaughtError(message, stack, url) {\n try {\n var sig = errorSig(message, stack);\n if (errorSigSeenRecently(sig)) return;\n noteErrorSig(sig);\n postLog({level: \"error\", context: CONTEXT, messageParts: sanitize([String(message) + (stack ? \"\\n\" + stack : \"\")]), url: url || here()});\n } catch (e) {\n // Ignore\n }\n }\n try {\n if (typeof g.addEventListener === \"function\") {\n g.addEventListener(\"error\", function (ev) {\n var err = ev && ev.error;\n var message = (err && err.message) || (ev && ev.message) || \"Uncaught error\";\n shipUncaughtError(message, err && err.stack, (ev && ev.filename) || undefined);\n });\n g.addEventListener(\"unhandledrejection\", function (ev) {\n var reason = ev && ev.reason;\n var message = (reason && reason.message) || (reason != null ? String(reason) : \"Unhandled rejection\");\n shipUncaughtError(\"Unhandled promise rejection: \" + message, reason && reason.stack, undefined);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // The SW executor can't reach another extension page's DOM or eval there,\n // so THIS surface answers inspect/eval requests for its own context.\n try {\n if (chrome.runtime && chrome.runtime.onMessage) {\n chrome.runtime.onMessage.addListener(function (msg, _sender, sendResponse) {\n if (!msg || !msg.__extjsEvalRequest) return;\n if (!msg.target || msg.target.context !== CONTEXT) return; // not for me\n var respondValue = function (value) {\n try { sendResponse({ok: true, value: value}); }\n catch (eSend) { sendResponse({ok: true, value: String(value)}); }\n };\n var respondError = function (e) {\n var emsg = (e && e.message) || String(e);\n if (cspBlocksEval(emsg)) {\n sendResponse({ok: false, error: {name: \"Unsupported\", code: \"csp_blocks_eval\", message: \"eval of a string is blocked in the \" + CONTEXT + \" page by the extension's content_security_policy. Use extension inspect --context \" + CONTEXT + \" to read its DOM instead. Original: \" + emsg}});\n } else {\n sendResponse({ok: false, error: {name: (e && e.name) || \"EvalError\", message: emsg}});\n }\n };\n try {\n var value = (0, eval)(String((msg.args && msg.args.expression) || \"\"));\n // A promise is not structured-cloneable: Chrome throws on the reply\n // and Firefox drops it on the way out, which the background read as\n // \"surface is not open\" while the page kept running the expression.\n // Settle it first, the way the background eval already does.\n if (value && typeof value.then === \"function\") {\n value.then(respondValue, respondError);\n } else {\n respondValue(value);\n }\n } catch (e) {\n respondError(e);\n }\n return true; // responded, possibly later\n });\n }\n } catch (e) {\n // Ignore\n }\n\n try {\n if (chrome.runtime && chrome.runtime.onMessage) {\n chrome.runtime.onMessage.addListener(function (msg, _sender, sendResponse) {\n if (!msg || !msg.__extjsInspectRequest) return;\n if (!msg.target || msg.target.context !== CONTEXT) return; // not for me\n try {\n var args = msg.args || {};\n var wantHtml = !args.include || args.include.indexOf(\"html\") !== -1;\n var cap = args.maxBytes || 262144;\n function countShadow(root) {\n var n = 0, els = root.querySelectorAll(\"*\");\n for (var i = 0; i < els.length; i++) { if (els[i].shadowRoot) { n++; n += countShadow(els[i].shadowRoot); } }\n return n;\n }\n var doc = g.document;\n var roots = doc.querySelectorAll('#extension-root,[data-extension-root]');\n var snap = {\n context: CONTEXT,\n url: here(),\n title: doc.title,\n summary: {\n htmlLength: doc.documentElement.outerHTML.length,\n scriptCount: doc.querySelectorAll(\"script\").length,\n styleCount: doc.querySelectorAll(\"style,link[rel=stylesheet]\").length,\n extensionRootCount: roots.length,\n openShadowRoots: countShadow(doc),\n bodyChildCount: doc.body ? doc.body.children.length : 0\n }\n };\n if (wantHtml) {\n var html = doc.documentElement.outerHTML;\n if (cap > 0 && html.length > cap) { snap.html = html.slice(0, cap); snap.htmlTruncated = true; }\n else { snap.html = html; }\n }\n sendResponse({ok: true, value: snap});\n } catch (e) {\n sendResponse({ok: false, error: {name: \"InspectError\", message: String(e)}});\n }\n return true; // responded\n });\n }\n } catch (e) {\n // Ignore\n }\n } catch (e) {\n // Ignore\n }\n})();\n";
|
|
2
|
+
export declare const BRIDGE_PRODUCER_SOURCE = ";(function () {\n try {\n var g = (typeof globalThis === \"object\" && globalThis) ? globalThis : this;\n if (!g || g.__extjsBridgeProducerInstalled) return;\n\n var PORT = parseInt(\"__EXTJS_CONTROL_PORT__\", 10);\n var INSTANCE_ID = \"__EXTJS_INSTANCE_ID__\";\n var CONTEXT = \"__EXTJS_CONTEXT__\";\n // Connectable host of the dev-server control WS. Baked from the resolved\n // connectable host (loopback locally; the public host for remote/devcontainer).\n var HOST = \"__EXTJS_CONTROL_HOST__\";\n if (!HOST || HOST.indexOf(\"__EXTJS\") === 0) HOST = \"127.0.0.1\";\n // A dev background names no session, so its file is the same bytes in\n // every session and a kept profile's cached copy of it is not stale.\n var SESSION_FROM_FILE = \"__EXTJS_SESSION_FROM_FILE__\" === \"1\";\n if (SESSION_FROM_FILE) { PORT = 0; INSTANCE_ID = \"\"; }\n else if (!PORT || PORT < 1) return;\n\n var WS = g.WebSocket;\n if (typeof WS !== \"function\") return;\n\n var consoleRef = g.console || {};\n g.__extjsBridgeProducerInstalled = true;\n\n // Capture extension event listeners at install time: these wraps run\n // BEFORE user code, and no platform API exists to dispatch these events.\n function captureEvent(event, sink) {\n try {\n if (!event || typeof event.addListener !== \"function\") return;\n var origAdd = event.addListener.bind(event);\n event.addListener = function (cb) {\n if (typeof cb === \"function\" && sink.indexOf(cb) === -1) sink.push(cb);\n return origAdd(cb);\n };\n if (typeof event.removeListener === \"function\") {\n var origRemove = event.removeListener.bind(event);\n event.removeListener = function (cb) {\n var i = sink.indexOf(cb);\n if (i !== -1) sink.splice(i, 1);\n return origRemove(cb);\n };\n }\n } catch (e) { /* non-fatal: trigger falls back to its no-listener reply */ }\n }\n\n // Use the raw globals (not the hoisted chrome var below). This runs first.\n // On Gecko browser.* is a DISTINCT wrapper object: hook BOTH namespaces.\n // One sink per manifest key, so a replay fires only the entry it clicks.\n var ACTION_KEYS = [\"action\", \"browser_action\", \"page_action\"];\n var ACTION_NAMESPACES = {action: \"action\", browser_action: \"browserAction\", page_action: \"pageAction\"};\n var actionClickedListeners = {action: [], browser_action: [], page_action: []};\n var commandListeners = [];\n var capturedEvents = [];\n function captureEventOnce(event, sink) {\n // Polyfilled extensions expose ONE event object on both namespaces:\n // wrap it once, and the sink dedupes callbacks shared across wrappers.\n if (!event || capturedEvents.indexOf(event) !== -1) return;\n capturedEvents.push(event);\n captureEvent(event, sink);\n }\n var captureNamespaces = [g.chrome, g.browser];\n for (var cn = 0; cn < captureNamespaces.length; cn++) {\n var capNS = captureNamespaces[cn];\n if (!capNS) continue;\n for (var ak = 0; ak < ACTION_KEYS.length; ak++) {\n var akNS = capNS[ACTION_NAMESPACES[ACTION_KEYS[ak]]];\n captureEventOnce(akNS && akNS.onClicked, actionClickedListeners[ACTION_KEYS[ak]]);\n }\n captureEventOnce(capNS.commands && capNS.commands.onCommand, commandListeners);\n }\n\n var LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\", \"trace\"];\n // The dev server's HMR client logs its own chatter (\"[HMR] Waiting for\n // update signal from WDS...\") through the extension's console; it is not\n // the extension's output. Its warnings and errors still ship.\n function isDevServerChatter(level, args) {\n if (level === \"warn\" || level === \"error\") return false;\n var first = args && args[0];\n return typeof first === \"string\" && /^\\[(?:HMR|webpack-dev-server|rspack-dev-server)\\] /.test(first);\n }\n var socket = null;\n var open = false;\n var queue = [];\n var backoff = 250;\n var MAX_BACKOFF = 5000;\n var connectFailures = 0;\n var MAX_QUEUE = 1000;\n var MAX_RESULT_BYTES = 256 * 1024;\n // Where log frames of every level are parked so a context that dies before\n // its socket opens does not take them along: a Safari background woken by\n // an event can unload before it connects. Capped; plain lines go before\n // errors when the cap bites.\n var PENDING_ERRORS_KEY = \"__extjsPendingErrors\";\n var MAX_PENDING_ERRORS = 100;\n var PENDING_ERROR_TTL = 300000;\n\n function nowId() {\n return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);\n }\n\n // The extension's own URL scheme names the engine outright, which beats a\n // user agent where Chrome and Safari both say \"Safari\".\n function engineName() {\n try {\n var scheme = (typeof location !== \"undefined\" && location.protocol) || \"\";\n if (scheme.indexOf(\"safari-web-extension\") === 0) return \"webkit\";\n if (scheme.indexOf(\"moz-extension\") === 0) return \"firefox\";\n if (scheme.indexOf(\"chrome-extension\") === 0) return \"chromium\";\n var ua = (typeof navigator !== \"undefined\" && navigator.userAgent) || \"\";\n if (/firefox/i.test(ua)) return \"firefox\";\n if (/safari/i.test(ua) && !/chrome|chromium|edg/i.test(ua)) return \"webkit\";\n return \"chromium\";\n } catch (e) { return \"chromium\"; }\n }\n\n // A cycle cannot cross as JSON. Each repeat of an ancestor becomes null,\n // which is what Chromium answers for a value returned from a tab.\n function cycleSafeJson(v) {\n var stack = [];\n return JSON.stringify(v, function (_key, val) {\n while (stack.length && stack[stack.length - 1] !== this) stack.pop();\n if (typeof val === \"bigint\") val = {__type: \"bigint\", value: String(val)};\n if (val && typeof val === \"object\") {\n if (stack.indexOf(val) !== -1) return null;\n stack.push(val);\n }\n return val;\n });\n }\n\n function safeValue(v) {\n try {\n var s;\n try { s = JSON.stringify(v); } catch (eCycle) { s = cycleSafeJson(v); }\n if (s === undefined) return {value: undefined, truncated: false};\n if (s.length > MAX_RESULT_BYTES) {\n return {value: {__type: \"truncated\", preview: s.slice(0, 1024)}, truncated: true};\n }\n return {value: JSON.parse(s), truncated: false};\n } catch (e) {\n return {value: {__type: \"unserializable\", preview: String(v).slice(0, 512)}, truncated: false};\n }\n }\n\n // A page cap counts characters, the transport counts the escaped JSON, and\n // markup grows under escaping. Shrink the html until the whole snapshot\n // fits, so a capped inspect still returns html instead of a placeholder.\n function fitSnapshot(snap) {\n try {\n if (!snap || typeof snap.html !== \"string\") return snap;\n if (JSON.stringify(snap).length <= MAX_RESULT_BYTES) return snap;\n var html = snap.html;\n var cut = html.length;\n for (var attempt = 0; attempt < 40 && cut > 0; attempt++) {\n snap.html = html.slice(0, cut);\n snap.htmlTruncated = true;\n var size = JSON.stringify(snap).length;\n if (size <= MAX_RESULT_BYTES) return snap;\n cut = Math.floor(cut * (MAX_RESULT_BYTES / size) * 0.98);\n }\n snap.html = \"\";\n snap.htmlTruncated = true;\n return snap;\n } catch (e) {\n return snap;\n }\n }\n\n function replyOk(cmdId, value) {\n var s = safeValue(value);\n var frame = {type: \"result\", cmdId: cmdId, ok: true, value: s.value};\n if (s.truncated) frame.truncated = true;\n try { socket && socket.send(JSON.stringify(frame)); } catch (e) {\n // Ignore\n }\n }\n\n function replyErr(cmdId, name, message, code, hint) {\n var frame = {type: \"result\", cmdId: cmdId, ok: false, error: {name: name, message: String(message), engine: engineName()}};\n if (code) frame.error.code = code;\n if (hint) frame.error.hint = hint;\n try { socket && socket.send(JSON.stringify(frame)); } catch (e) {\n // Ignore\n }\n }\n\n // A tabs.* failure the caller can act on gets a name and a refusal code:\n // a tab id nobody has is TargetNotFound, and a url the engine refuses by\n // rule (Gecko's \"Illegal URL\", Chromium's javascript: ban) is BadRequest.\n // Anything else keeps the op's own error name.\n function replyTabsFailure(cmdId, err, fallbackName, url) {\n var msg = String((err && err.message) || err);\n if (/no tab with id|invalid tab id/i.test(msg)) {\n replyErr(cmdId, \"TargetNotFound\", msg, \"tab_not_found\");\n return;\n }\n if (url && /illegal url|javascript urls are not allowed|invalid url/i.test(msg)) {\n replyErr(cmdId, \"BadRequest\", engineName() + \" refuses to open \" + url + \" from the extension's tabs API (\" + msg + \")\", \"url_refused\");\n return;\n }\n replyErr(cmdId, fallbackName, msg);\n }\n\n // extension open reaches the popup, options and sidebar only. A devtools\n // page runs while DevTools is open on a tab, an override page in its tab.\n // The advice names extension open only where that engine lets it work.\n function surfaceNotOpen(ctx) {\n var engine = engineName();\n var how = \"open it first: extension open \" + ctx;\n if (engine === \"chromium\" && (ctx === \"popup\" || ctx === \"sidebar\")) {\n how = \"open it first: click the extension's toolbar entry, or its row in the extensions menu\";\n } else if (engine === \"firefox\" && ctx === \"sidebar\") {\n how = \"open it first: the sidebar button in the toolbar, or View > Sidebar\";\n }\n if (ctx === \"devtools\") {\n var flag = engine === \"firefox\" ? \"--devtools\" : engine === \"chromium\" ? \"--auto-open-devtools-for-tabs\" : \"\";\n how = \"the devtools page runs only while DevTools is open on a tab, and extension open cannot open DevTools. Open DevTools on a tab first\" + (flag ? \", or start the session with \" + flag + \" added to EXTENSION_BROWSER_FLAGS\" : \"\");\n } else if (ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") {\n how = \"open that page in a tab first\";\n }\n return {code: \"surface_not_open\", message: \"surface '\" + ctx + \"' is not open (\" + how + \")\"};\n }\n\n // A surface relay that answered nothing is closed only when the engine\n // says no receiver exists. Any other lastError (a reply the engine could\n // not clone, a channel that closed) means the surface WAS open and ran the\n // expression, so the message quotes the engine instead of \"not open\".\n function surfaceReplyFailure(ctx, resp) {\n var le = null;\n try { le = g.chrome && g.chrome.runtime && g.chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n if (!le && resp) return null;\n var lem = le ? String((le && le.message) || le) : \"\";\n if (!lem || /receiving end does not exist|could not establish connection/i.test(lem)) {\n return surfaceNotOpen(ctx);\n }\n return {code: \"surface_reply_failed\", message: \"surface '\" + ctx + \"' answered but the reply did not arrive: \" + lem};\n }\n\n // Why a tab injection cannot run here. An MV3 copy whose manifest omits\n // the scripting permission has no chrome.scripting (Firefox gates the\n // whole namespace on it); only MV2 lacks the API by design.\n function scriptingMissingReason(tabId) {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { m = null; }\n var mv = m && m.manifest_version;\n if (mv >= 3) {\n var perms = stringList(m.permissions);\n if (perms.indexOf(\"scripting\") === -1) {\n var gate = engineName() === \"firefox\" ? \" (Firefox exposes it only with that permission)\" : \"\";\n return \"cannot inject into tab \" + tabId + \": this MV3 build's manifest has no \\\"scripting\\\" permission, so chrome.scripting is missing\" + gate + \". Add \\\"scripting\\\" to permissions, or use a dev session (extension dev), which adds it; --context background still works\";\n }\n return \"cannot inject into tab \" + tabId + \": chrome.scripting is missing on this engine even though the manifest declares \\\"scripting\\\"; use --context background\";\n }\n if (mv === 2) return \"chrome.scripting is not available on this engine (MV2 has no scripting API); use --context background\";\n return \"cannot inject into tab \" + tabId + \": chrome.scripting is not available on this engine; use --context background\";\n }\n\n // A tab id nobody has is a missing target on any build, so the engine is\n // asked for the tab before the missing permission gets the blame.\n function replyScriptingMissing(cmdId, tabId) {\n nsCall(\"tabs\", \"get\", [tabId], function (err) {\n var msg = String((err && err.message) || err || \"\");\n if (err && /no tab with id|invalid tab id/i.test(msg)) {\n replyErr(cmdId, \"TargetNotFound\", msg, \"tab_not_found\");\n return;\n }\n replyErr(cmdId, \"Unsupported\", scriptingMissingReason(tabId), \"scripting_unavailable\");\n });\n }\n\n function ownPopupIsOpen(cb) {\n try {\n var ext = (g.browser && g.browser.extension) || (g.chrome && g.chrome.extension);\n if (ext && typeof ext.getViews === \"function\") { cb(ext.getViews({type: \"popup\"}).length > 0); return; }\n } catch (e) {\n // Ignore\n }\n var rt = g.chrome && g.chrome.runtime;\n if (!rt || typeof rt.getContexts !== \"function\") { cb(false); return; }\n try {\n Promise.resolve(rt.getContexts({contextTypes: [\"POPUP\"]})).then(function (list) { cb(!!(list && list.length)); }, function () { cb(false); });\n } catch (e2) { cb(false); }\n }\n\n // Firefox refuses openPopup while any panel shows. When that panel is this\n // extension's own popup, the caller already has what it asked for.\n function replyOpenPopupFailure(cmdId, err, surface, okValue) {\n var msg = String((err && err.message) || err);\n if (!/another panel is open/i.test(msg)) {\n replyErr(cmdId, \"Unsupported\", \"openPopup: \" + msg, openRefusalCode(msg));\n return;\n }\n ownPopupIsOpen(function (open) {\n if (open) { okValue.alreadyOpen = true; replyOk(cmdId, okValue); return; }\n replyErr(cmdId, \"Unsupported\", \"another panel is open in the browser window, and one panel shows at a time (\" + msg + \")\", \"panel_already_open\", \"Close the open panel, then run extension open \" + surface + \" again.\");\n });\n }\n\n // The page a surface lives in, as the manifest names it, so the background\n // can ask the engine whether that page is open at all.\n function surfacePagePath(ctx) {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { return null; }\n if (!m) return null;\n var p = null;\n if (ctx === \"popup\") p = (m.action && m.action.default_popup) || (m.browser_action && m.browser_action.default_popup) || (m.page_action && m.page_action.default_popup);\n else if (ctx === \"options\") p = (m.options_ui && m.options_ui.page) || m.options_page;\n else if (ctx === \"sidebar\") p = (m.side_panel && m.side_panel.default_path) || (m.sidebar_action && m.sidebar_action.default_panel);\n else if (ctx === \"devtools\") p = m.devtools_page;\n else if (ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") p = m.chrome_url_overrides && m.chrome_url_overrides[ctx];\n // Character classes on purpose: this source is a template literal, and\n // a backslash escape in a regex would be eaten before it ever ran.\n return typeof p === \"string\" && p ? p.replace(/^[.]?[/]/, \"\") : null;\n }\n\n function surfaceManifestKeys(ctx) {\n if (ctx === \"popup\") return \"action.default_popup, browser_action.default_popup or page_action.default_popup\";\n if (ctx === \"options\") return \"options_ui.page or options_page\";\n if (ctx === \"sidebar\") return \"side_panel.default_path or sidebar_action.default_panel\";\n if (ctx === \"devtools\") return \"devtools_page\";\n return \"chrome_url_overrides.\" + ctx;\n }\n\n // A surface the manifest never declares has no page to open, so asking\n // the caller to open it first would send them after nothing.\n function surfaceNotDeclared(ctx) {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { return null; }\n if (!m || surfacePagePath(ctx)) return null;\n return {code: \"surface_not_declared\", message: \"the manifest declares no \" + ctx + \" page: it has no \" + surfaceManifestKeys(ctx)};\n }\n\n // Chrome says \"message port closed\" both when the surface died mid-op and\n // when a bystander extension page (the options page, a new tab override)\n // received the message and passed, since a relay returns nothing for a\n // context that is not its own. Only the engine's open-context list tells\n // the two apart, so it is asked before a reply gets the blame. Engines\n // without getContexts keep the plain classification.\n function classifySurfaceFailure(ctx, resp, cb) {\n var relayErr = surfaceReplyFailure(ctx, resp);\n if (!relayErr || relayErr.code !== \"surface_reply_failed\" || !/message port closed/i.test(relayErr.message)) { cb(relayErr); return; }\n var rt = g.chrome && g.chrome.runtime;\n var page = surfacePagePath(ctx);\n if (!page || !rt || typeof rt.getContexts !== \"function\") { cb(relayErr); return; }\n var wanted = \"\";\n try { wanted = String(rt.getURL(page)).split(/[?#]/)[0]; } catch (e) { cb(relayErr); return; }\n var notOpen = surfaceNotOpen(ctx);\n try {\n Promise.resolve(rt.getContexts({})).then(function (list) {\n var open = false;\n for (var i = 0; i < (list || []).length; i++) {\n var u = list[i] && list[i].documentUrl;\n if (u && String(u).split(/[?#]/)[0] === wanted) { open = true; break; }\n }\n cb(open ? relayErr : notOpen);\n }, function () { cb(relayErr); });\n } catch (e) { cb(relayErr); }\n }\n\n // Every engine's wording for \"this document's CSP forbids eval\". Gecko\n // says \"call to eval() blocked by CSP\", Chromium quotes the directive.\n function cspBlocksEval(message) {\n return /call to eval\\(\\)|blocked by (?:the )?CSP|Content Security Policy|unsafe-eval/i.test(String(message == null ? \"\" : message));\n }\n\n // Name the refusal the browser wrote as prose, so a consumer branches on\n // error.code instead of matching the engine's sentence.\n function openRefusalCode(message) {\n var m = String(message == null ? \"\" : message);\n if (/user gesture|user input|user interaction|user action/i.test(m)) return \"needs_user_gesture\";\n if (/browser window|active window/i.test(m)) return \"needs_headed_window\";\n return undefined;\n }\n\n // Resolve a numeric tab id when the caller did not pass one: match\n // target.url against open tabs, else default to the active tab. (#51)\n function resolveTargetTab(target, cb) {\n var chrome = g.chrome;\n if (!chrome || !chrome.tabs) { cb(null, \"chrome.tabs is not available\"); return; }\n var url = target && target.url;\n if (url) {\n var substringMatch = function () {\n try {\n chrome.tabs.query({}, function (all) {\n var hit = (all || []).filter(function (t) { return t.url && String(t.url).indexOf(url) !== -1; })[0];\n if (hit && typeof hit.id === \"number\") { cb(hit.id, null); return; }\n cb(null, \"no open tab matches url: \" + url);\n });\n } catch (e2) { cb(null, \"tab query failed\"); }\n };\n try {\n // chrome.tabs.query accepts URL match patterns; a bare url/glob may\n // not be a valid pattern, so fall back to a substring scan.\n chrome.tabs.query({url: url}, function (tabs) {\n if (chrome.runtime && chrome.runtime.lastError) { substringMatch(); return; }\n if (tabs && tabs.length && typeof tabs[0].id === \"number\") { cb(tabs[0].id, null); return; }\n substringMatch();\n });\n } catch (e) { substringMatch(); }\n return;\n }\n try {\n chrome.tabs.query({active: true, lastFocusedWindow: true}, function (tabs) {\n var t = tabs && tabs[0];\n if (t && typeof t.id === \"number\") { cb(t.id, null); return; }\n cb(null, \"no active tab to target\");\n });\n } catch (e3) { cb(null, \"tab query failed\"); }\n }\n\n // chrome.* async APIs are callback-only on Gecko. Prefer promisified\n // browser.* when present, else the chrome.* callback form. cb(err, result).\n function nsCall(nsName, method, callArgs, cb) {\n var chromeG = g.chrome;\n var done = false;\n var once = function (err, r) { if (!done) { done = true; cb(err, r); } };\n var viaPromise = function (ns) {\n try {\n var ret = ns[method].apply(ns, callArgs);\n if (ret && typeof ret.then === \"function\") {\n ret.then(function (r) { once(null, r); }, function (e) { once(e); });\n return true;\n }\n } catch (e) { once(e); return true; }\n return false;\n };\n var bNS = g.browser && g.browser[nsName];\n if (bNS && typeof bNS[method] === \"function\" && viaPromise(bNS)) return;\n var cNS = chromeG && chromeG[nsName];\n if (!cNS || typeof cNS[method] !== \"function\") {\n once(new Error(\"chrome.\" + nsName + \".\" + method + \" is not available (engine: \" + engineName() + \")\"));\n return;\n }\n try {\n var ret2 = cNS[method].apply(cNS, callArgs.concat([function (r) {\n var le = chromeG.runtime && chromeG.runtime.lastError;\n if (le) once(le); else once(null, r);\n }]));\n // A promise-only implementation ignores the trailing callback and\n // returns a thenable instead; resolve through it (once() dedupes).\n if (ret2 && typeof ret2.then === \"function\") {\n ret2.then(function (r) { once(null, r); }, function (e) { once(e); });\n }\n } catch (e2) {\n if (!viaPromise(cNS)) once(e2);\n }\n }\n\n // Only a tab the engine could not find is a missing target. Anything else\n // happened in a tab that exists, a value it could not clone back above all.\n // Firefox refuses to script a moz-extension:// page or a page outside\n // host access with the tab right there, so that refusal is named too.\n function injectionErrorName(err) {\n var msg = String((err && err.message) || err || \"\");\n if (/no tab with id|invalid tab id/i.test(msg)) return \"TargetNotFound\";\n if (/clon/i.test(msg)) return \"DataCloneError\";\n if (injectionRefused(msg)) return \"InjectionRefused\";\n return \"ExecutorError\";\n }\n\n function injectionRefused(msg) {\n return /missing host permission|cannot access contents|cannot be scripted|cannot access a chrome|extensions gallery/i.test(String(msg));\n }\n\n function replyInjectionErr(cmdId, err) {\n var msg = (err && err.message) || err;\n var name = injectionErrorName(err);\n replyErr(cmdId, name, msg, injectionRefused(msg) ? \"injection_refused\" : name === \"TargetNotFound\" ? \"tab_not_found\" : undefined);\n }\n\n function executeCommand(cmd) {\n var op = cmd.op, target = cmd.target || {}, args = cmd.args || {};\n var ctx = target.context || \"background\";\n var chrome = g.chrome;\n var cmdId = cmd.cmdId;\n // content/page eval & inspect need a numeric tab id: resolve --url (or\n // nothing) to a tab and re-dispatch with target.tabId filled in. (#51)\n if ((op === \"eval\" || op === \"inspect\" || op === \"reload\") && (ctx === \"content\" || ctx === \"page\") && target.tabId == null) {\n resolveTargetTab(target, function (tabId, err) {\n if (tabId == null) {\n // A filter that matched nothing, or no active tab, is a missing\n // target the caller can fix, not a missing feature.\n if (err && /^no open tab matches|^no active tab/i.test(String(err))) {\n replyErr(cmdId, \"TargetNotFound\", err, \"tab_not_found\");\n return;\n }\n replyErr(cmdId, \"Unsupported\", err || (\"eval/inspect in context \" + ctx + \" needs a --tab id, a --url to match, or an active tab\"));\n return;\n }\n var next = {};\n for (var k in cmd) { if (Object.prototype.hasOwnProperty.call(cmd, k)) next[k] = cmd[k]; }\n next.target = {};\n for (var tk in target) { if (Object.prototype.hasOwnProperty.call(target, tk)) next.target[tk] = target[tk]; }\n next.target.tabId = tabId;\n executeCommand(next);\n });\n return;\n }\n try {\n if (!chrome) { replyErr(cmdId, \"Unsupported\", \"chrome.* not available in this context\"); return; }\n if (op === \"eval\") {\n if (ctx === \"background\") {\n Promise.resolve().then(function () { return (0, eval)(args.expression); })\n .then(function (r) { replyOk(cmdId, r); }, function (e) {\n var msg = (e && e.message) || String(e);\n // MV3 forbids eval of strings in the SW/extension pages and\n // rejects 'unsafe-eval'. Gecko words the same refusal \"call to\n // eval() blocked by CSP\", which read as a guest throw.\n if (cspBlocksEval(msg)) {\n replyErr(cmdId, \"Unsupported\", \"eval is blocked in the extension background by the extension's content_security_policy, which allows no unsafe-eval. Use --context page --tab <id> (eval runs in the page's MAIN world), or run on a build whose CSP permits it. Engine: \" + engineName(), \"csp_blocks_eval\");\n } else {\n replyErr(cmdId, (e && e.name) || \"EvalError\", msg);\n }\n });\n } else if ((ctx === \"content\" || ctx === \"page\") && target.tabId && chrome.scripting) {\n // Wrap the eval so a throw INSIDE the tab comes back as data:\n // Chrome swallows an injected function's exception (null result).\n // A returned promise is settled in the tab, since Firefox cannot\n // clone one that sits inside the result object.\n nsCall(\"scripting\", \"executeScript\", [{\n target: {tabId: target.tabId},\n world: ctx === \"page\" ? \"MAIN\" : \"ISOLATED\",\n func: async function (src) {\n // Firefox refuses to clone a cycle or a DOM node out of a tab and\n // Chromium nulls them, so the value takes its JSON form in the tab.\n function __extjsJsonForm(v) {\n var stack = [];\n try {\n var json = JSON.stringify(v, function (_key, val) {\n while (stack.length && stack[stack.length - 1] !== this) stack.pop();\n if (typeof val === \"bigint\") val = {__type: \"bigint\", value: String(val)};\n if (val && typeof val === \"object\") {\n if (stack.indexOf(val) !== -1) return null;\n stack.push(val);\n }\n return val;\n });\n return json === undefined ? undefined : JSON.parse(json);\n } catch (e) { return v; }\n }\n try { return {__extjsEval: 1, ok: true, value: __extjsJsonForm(await eval(src))}; }\n catch (e) { return {__extjsEval: 1, ok: false, name: (e && e.name) || \"EvalError\", message: (e && e.message) || String(e)}; }\n },\n args: [String(args.expression)]\n }], function (err, res) {\n if (err) { replyInjectionErr(cmdId, err); return; }\n var frame = res && res[0] ? res[0].result : undefined;\n if (!frame || frame.__extjsEval !== 1) {\n replyErr(cmdId, \"TargetNotFound\", \"the expression never executed in tab \" + target.tabId + \": no injectable frame returned a result (restricted page, or outside host_permissions)\");\n return;\n }\n if (frame.ok) { replyOk(cmdId, frame.value); return; }\n if (ctx === \"content\" && (cspBlocksEval(String(frame.name) + \" \" + String(frame.message)) || String(frame.name) === \"EvalError\")) {\n replyErr(cmdId, \"Unsupported\", \"eval of a string is blocked in the ISOLATED (content) world by the extension's content_security_policy. Use --context page (runs in the page's MAIN world). Original: \" + frame.message, \"csp_blocks_eval\");\n return;\n }\n replyErr(cmdId, frame.name || \"EvalError\", frame.message);\n });\n } else if (ctx === \"popup\" || ctx === \"options\" || ctx === \"sidebar\" || ctx === \"devtools\" || ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") {\n var evalUndeclared = surfaceNotDeclared(ctx);\n if (evalUndeclared) { replyErr(cmdId, \"Unsupported\", evalUndeclared.message, evalUndeclared.code); return; }\n // The SW can't eval in another extension page; ask the surface's\n // own in-bundle relay (only the open, matching-context page responds).\n chrome.runtime.sendMessage(\n {__extjsEvalRequest: true, target: target, args: {expression: String(args.expression)}},\n function (resp) {\n classifySurfaceFailure(ctx, resp, function (relayErr) {\n if (relayErr) {\n replyErr(cmdId, \"Unsupported\", relayErr.message, relayErr.code);\n } else if (resp.ok) {\n replyOk(cmdId, resp.value);\n } else {\n replyErr(cmdId, (resp.error && resp.error.name) || \"EvalError\", (resp.error && resp.error.message) || \"eval failed\", resp.error && resp.error.code);\n }\n });\n }\n );\n } else if (ctx === \"content\" || ctx === \"page\") {\n if (target.tabId) replyScriptingMissing(cmdId, target.tabId);\n else replyErr(cmdId, \"Unsupported\", \"eval in context \" + ctx + \" requires a tabId\");\n } else {\n replyErr(cmdId, \"BadRequest\", \"unknown eval context: \" + ctx);\n }\n return;\n }\n if (op === \"storage.get\" || op === \"storage.set\") {\n // chrome.* storage is callback-only on Gecko and older Chromium.\n // Prefer promisified browser.*, then fall back to the callback shape.\n var storageNS = (g.browser && g.browser.storage) ? g.browser.storage : chrome.storage;\n var storageArea = storageNS && storageNS[args.area || \"local\"];\n if (!storageArea) { replyErr(cmdId, \"StorageError\", \"storage.\" + (args.area || \"local\") + \" unavailable\"); return; }\n var isSet = op === \"storage.set\";\n var callArgs = isSet ? [args.items || {}] : [args.key != null ? args.key : null];\n // The dev runtime keeps its own bookkeeping under __extjs* keys in\n // the same area; a whole-area read shows only the extension's data.\n var withoutFrameworkKeys = function (r) {\n if (args.key != null || !r || typeof r !== \"object\") return r;\n var own = {};\n for (var k in r) {\n if (Object.prototype.hasOwnProperty.call(r, k) && k.indexOf(\"__extjs\") !== 0) own[k] = r[k];\n }\n return own;\n };\n var onStorageOk = function (r) { replyOk(cmdId, isSet ? {set: Object.keys(args.items || {})} : withoutFrameworkKeys(r)); };\n var onStorageErr = function (e) { replyErr(cmdId, \"StorageError\", (e && e.message) || String(e)); };\n var storageFn = isSet ? storageArea.set : storageArea.get;\n try {\n var storageRet = storageFn.apply(storageArea, callArgs);\n if (storageRet && typeof storageRet.then === \"function\") {\n storageRet.then(onStorageOk, onStorageErr);\n return;\n }\n } catch (e) { /* not thenable / threw synchronously: fall back to callback */ }\n try {\n storageFn.apply(storageArea, callArgs.concat([function (r) {\n var le = chrome.runtime && chrome.runtime.lastError;\n if (le) onStorageErr(le); else onStorageOk(r);\n }]));\n } catch (e) { onStorageErr(e); }\n return;\n }\n if (op === \"reload\") {\n if (ctx === \"background\") {\n // The answer names the override tabs the next generation restores.\n restartExtension(50, function (restoring) {\n var value = {reloading: true, reloaded: [\"background\"]};\n if (restoring.length) {\n value.restoring = [];\n for (var r = 0; r < restoring.length; r++) value.restoring.push({tabId: restoring[r].tabId, surface: restoring[r].surface});\n }\n replyOk(cmdId, value);\n });\n } else if (target.tabId) {\n nsCall(\"tabs\", \"reload\", [target.tabId], function (err) {\n if (err) replyTabsFailure(cmdId, err, \"ReloadError\");\n else replyOk(cmdId, {reloaded: target.tabId});\n });\n } else {\n replyErr(cmdId, \"Unsupported\", \"reload needs background or a tabId\");\n }\n return;\n }\n if (op === \"open\") {\n var surface = args.surface || ctx;\n // The toolbar entry a click lands on: MV3 declares action, MV2\n // browser_action or page_action. Firefox MV3 still exposes\n // pageAction, so the manifest picks first, and its namespace has to\n // exist. Without a declared key, the first namespace present wins.\n var actionManifestKey = function () {\n var m = null;\n try { m = chrome.runtime.getManifest(); } catch (e) { m = null; }\n var hasNS = function (key) {\n var n = ACTION_NAMESPACES[key];\n return !!((g.browser && g.browser[n]) || (g.chrome && g.chrome[n]));\n };\n for (var k = 0; k < ACTION_KEYS.length; k++) {\n if (m && m[ACTION_KEYS[k]] && hasNS(ACTION_KEYS[k])) return ACTION_KEYS[k];\n }\n for (var n = 0; n < ACTION_KEYS.length; n++) {\n if (hasNS(ACTION_KEYS[n])) return ACTION_KEYS[n];\n }\n return null;\n };\n // A page action's popup is per tab, and both engines require the\n // tabId. Always resolves to a string.\n var getActionPopup = function (key, tab, cb) {\n var details = key === \"page_action\" ? {tabId: tab && tab.id} : {};\n nsCall(ACTION_NAMESPACES[key], \"getPopup\", [details], function (err, p) {\n cb(err ? \"\" : (p || \"\"));\n });\n };\n var resolveActiveTab = function (a, cb) {\n if (a && typeof a.tabId === \"number\") {\n try { chrome.tabs.get(a.tabId, function (t) { cb(t || {id: a.tabId}); }); return; }\n catch (e) {\n // Ignore\n }\n }\n try { chrome.tabs.query({active: true, lastFocusedWindow: true}, function (tabs) { cb((tabs && tabs[0]) || undefined); }); }\n catch (e) { cb(undefined); }\n };\n // Replaying a listener carries no user gesture, so activeTab is never\n // granted. Warn when the manifest declares it.\n var activeTabWarning = function () {\n try {\n var m = chrome.runtime.getManifest();\n var perms = (m && m.permissions) || [];\n if (perms.indexOf(\"activeTab\") !== -1) {\n return \"replayed without a user gesture: activeTab is NOT granted, so APIs that depend on it (scripting on the active tab, captureVisibleTab) behave differently than a real click\";\n }\n } catch (e) {\n // Ignore\n }\n return null;\n };\n if (surface === \"popup\") {\n var popupKey = actionManifestKey();\n var popupNS = popupKey && ACTION_NAMESPACES[popupKey];\n if (popupNS && chrome[popupNS] && chrome[popupNS].openPopup) {\n nsCall(popupNS, \"openPopup\", [], function (err) {\n if (err) replyOpenPopupFailure(cmdId, err, \"popup\", {opened: \"popup\"});\n else replyOk(cmdId, {opened: \"popup\"});\n });\n } else { replyErr(cmdId, \"Unsupported\", (popupNS || \"action\") + \".openPopup not available\", \"api_unavailable\"); }\n } else if (surface === \"options\") {\n // Chrome answers a manifest with no options page through lastError\n // and still calls back, so the callback must read it.\n try {\n chrome.runtime.openOptionsPage(function () {\n var optErr = chrome.runtime.lastError;\n if (optErr) {\n replyErr(cmdId, \"Unsupported\", \"openOptionsPage: \" + (optErr.message || optErr) + \" (the manifest declares no options_ui or options_page)\", \"surface_not_declared\");\n } else replyOk(cmdId, {opened: \"options\"});\n });\n }\n catch (e) { replyErr(cmdId, \"Unsupported\", \"openOptionsPage: \" + e); }\n } else if (surface === \"sidebar\") {\n // The two member reads below are exactly what the Safari\n // unsupported-API scan looks for, and this runtime is prepended to\n // the background asset at PROCESS_ASSETS_STAGE_REPORT + 101, after\n // that scan runs at SUMMARIZE + 1. Move the injection earlier and\n // every Safari dev session warns about this line.\n if (chrome.sidePanel && chrome.sidePanel.open && chrome.windows) {\n chrome.windows.getCurrent(function (w) {\n nsCall(\"sidePanel\", \"open\", [{windowId: w.id}], function (err) {\n if (err) {\n var sideMsg = (err && err.message) || err;\n replyErr(cmdId, \"Unsupported\", \"sidePanel.open: \" + sideMsg, openRefusalCode(sideMsg));\n } else replyOk(cmdId, {opened: \"sidebar\"});\n });\n });\n } else if (engineName() === \"firefox\") {\n // Firefox has no side panel API, and its sidebar opens only inside\n // a user action handler, which a bridge command is not.\n replyErr(cmdId, \"Unsupported\", \"the sidebar comes from sidebar_action here and opens only on a user action, so the CLI cannot open it\", \"api_unavailable\", \"Open it from the Firefox sidebar button, or View > Sidebar. Once it is open, extension eval --context sidebar and extension inspect --context sidebar reach it.\");\n } else { replyErr(cmdId, \"Unsupported\", \"sidePanel is not available\", \"api_unavailable\"); }\n } else if (surface === \"action\") {\n // With a popup the click opens it; without one, replay the\n // onClicked listeners captured at install time. The answer names\n // the manifest key the click went through.\n var actionKey = actionManifestKey();\n if (actionKey) {\n var actionNS = ACTION_NAMESPACES[actionKey];\n var clicked = actionClickedListeners[actionKey];\n resolveActiveTab(args, function (tab) {\n getActionPopup(actionKey, tab, function (popup) {\n if (popup) {\n nsCall(actionNS, \"openPopup\", [], function (err) {\n if (err) replyOpenPopupFailure(cmdId, err, \"action\", {triggered: \"popup\", manifestKey: actionKey});\n else replyOk(cmdId, {triggered: \"popup\", manifestKey: actionKey});\n });\n } else if (clicked.length) {\n var fired = 0;\n for (var i = 0; i < clicked.length; i++) {\n try { clicked[i](tab); fired++; } catch (e) {\n // Ignore\n }\n }\n var reply = {triggered: \"onClicked\", listeners: fired, gesture: false, manifestKey: actionKey};\n var warning = activeTabWarning();\n if (warning) reply.warning = warning;\n replyOk(cmdId, reply);\n } else {\n replyErr(cmdId, \"Unsupported\", actionKey + \" has no popup and no \" + actionNS + \".onClicked listener registered\");\n }\n });\n });\n } else { replyErr(cmdId, \"Unsupported\", \"the manifest declares no action, browser_action or page_action\", \"surface_not_declared\"); }\n } else if (surface === \"command\") {\n var commandName = (args && args.name) || undefined;\n if (!commandListeners.length) {\n replyErr(cmdId, \"Unsupported\", \"no chrome.commands.onCommand listener registered\");\n } else {\n resolveActiveTab(args, function (tab) {\n var fired = 0;\n for (var i = 0; i < commandListeners.length; i++) {\n try { commandListeners[i](commandName, tab); fired++; } catch (e) {\n // Ignore\n }\n }\n replyOk(cmdId, {triggered: \"command\", command: commandName || null, listeners: fired, gesture: false});\n });\n }\n } else { replyErr(cmdId, \"BadRequest\", \"unknown surface: \" + surface); }\n return;\n }\n if (op === \"tabs.query\") {\n nsCall(\"tabs\", \"query\", [args || {}], function (err, tabs) {\n if (err) { replyErr(cmdId, \"TabsError\", (err && err.message) || err); return; }\n replyOk(cmdId, (tabs || []).map(function (t) { return {id: t.id, url: t.url, title: t.title, active: t.active, windowId: t.windowId}; }));\n });\n return;\n }\n // Navigation is a static tabs.* call, never an eval: an MV3 background\n // (Safari's included) refuses eval by CSP, so a url must reach a tab\n // through code that shipped with the bridge. A tabId targets that\n // tab, newTab opens one, and otherwise the active tab is reused.\n if (op === \"tabs.navigate\") {\n var navUrl = typeof args.url === \"string\" ? args.url : \"\";\n if (!navUrl) { replyErr(cmdId, \"BadRequest\", \"tabs.navigate needs a url\"); return; }\n var navDone = function (err, tab, created) {\n if (err) { replyTabsFailure(cmdId, err, \"TabsError\", navUrl); return; }\n replyOk(cmdId, {tabId: tab && tab.id != null ? tab.id : null, url: navUrl, created: !!created});\n };\n if (target.tabId != null) {\n nsCall(\"tabs\", \"update\", [target.tabId, {url: navUrl}], function (err, tab) { navDone(err, tab, false); });\n return;\n }\n if (args.newTab) {\n nsCall(\"tabs\", \"create\", [{url: navUrl, active: args.active !== false}], function (err, tab) { navDone(err, tab, true); });\n return;\n }\n nsCall(\"tabs\", \"query\", [{active: true, currentWindow: true}], function (qErr, tabs) {\n var active = !qErr && tabs && tabs[0];\n if (active && active.id != null) {\n nsCall(\"tabs\", \"update\", [active.id, {url: navUrl}], function (err, tab) { navDone(err, tab, false); });\n } else {\n nsCall(\"tabs\", \"create\", [{url: navUrl}], function (err, tab) { navDone(err, tab, true); });\n }\n });\n return;\n }\n if (op === \"inspect\") {\n // Extract a DOM snapshot from the target page via chrome.scripting\n // (CDP-free). Closed shadow roots need CDP; here we read open ones.\n if ((ctx === \"content\" || ctx === \"page\") && target.tabId && chrome.scripting) {\n var maxBytes = (args && args.maxBytes) || 262144;\n var includeHtml = !args || !args.include || args.include.indexOf(\"html\") !== -1;\n nsCall(\"scripting\", \"executeScript\", [{\n target: {tabId: target.tabId},\n world: ctx === \"page\" ? \"MAIN\" : \"ISOLATED\",\n func: function (wantHtml, cap) {\n function countShadow(root) {\n var n = 0, els = root.querySelectorAll(\"*\");\n for (var i = 0; i < els.length; i++) { if (els[i].shadowRoot) { n++; n += countShadow(els[i].shadowRoot); } }\n return n;\n }\n var doc = document;\n var roots = doc.querySelectorAll('#extension-root,[data-extension-root]');\n var out = {\n url: location.href,\n title: doc.title,\n summary: {\n htmlLength: doc.documentElement.outerHTML.length,\n scriptCount: doc.querySelectorAll(\"script\").length,\n styleCount: doc.querySelectorAll(\"style,link[rel=stylesheet]\").length,\n extensionRootCount: roots.length,\n openShadowRoots: countShadow(doc),\n bodyChildCount: doc.body ? doc.body.children.length : 0\n }\n };\n if (wantHtml) {\n var html = doc.documentElement.outerHTML;\n if (cap > 0 && html.length > cap) { out.html = html.slice(0, cap); out.htmlTruncated = true; }\n else { out.html = html; }\n }\n return out;\n },\n args: [includeHtml, maxBytes]\n }], function (err, res) {\n if (err) { replyInjectionErr(cmdId, err); return; }\n var snap = res && res[0] ? res[0].result : undefined;\n if (snap == null) { replyErr(cmdId, \"TargetNotFound\", \"no injectable frame returned a snapshot for tab \" + target.tabId + \" (restricted page, or outside host_permissions)\"); return; }\n replyOk(cmdId, fitSnapshot(snap));\n });\n } else if (ctx === \"popup\" || ctx === \"options\" || ctx === \"sidebar\" || ctx === \"devtools\" || ctx === \"newtab\" || ctx === \"history\" || ctx === \"bookmarks\") {\n var inspectUndeclared = surfaceNotDeclared(ctx);\n if (inspectUndeclared) { replyErr(cmdId, \"Unsupported\", inspectUndeclared.message, inspectUndeclared.code); return; }\n // The SW can't read a surface page's DOM; ask the surface's own\n // in-bundle relay (only the open, matching-context page responds).\n chrome.runtime.sendMessage(\n {__extjsInspectRequest: true, target: target, args: args},\n function (resp) {\n classifySurfaceFailure(ctx, resp, function (relayErr) {\n if (relayErr) {\n replyErr(cmdId, \"Unsupported\", relayErr.message, relayErr.code);\n } else if (resp.ok) {\n replyOk(cmdId, fitSnapshot(resp.value));\n } else {\n replyErr(cmdId, (resp.error && resp.error.name) || \"InspectError\", (resp.error && resp.error.message) || \"inspect failed\");\n }\n });\n }\n );\n } else if ((ctx === \"content\" || ctx === \"page\") && target.tabId) {\n replyScriptingMissing(cmdId, target.tabId);\n } else if (ctx === \"background\") {\n replyErr(cmdId, \"Unsupported\", (engineName() === \"chromium\" ? \"the service worker has no DOM\" : \"the background has no page to read\") + \"; inspect a content/page (with --tab) or an open surface\");\n } else {\n replyErr(cmdId, \"Unsupported\", \"inspect of \" + ctx + \" requires a tabId (content/page) or an open surface\");\n }\n return;\n }\n replyErr(cmdId, \"BadRequest\", \"unknown op: \" + op);\n } catch (e) {\n replyErr(cmdId, \"ExecutorError\", e);\n }\n }\n\n function noopLastError() { try { void g.chrome.runtime.lastError; } catch (e) {\n // Ignore\n } }\n\n // Only http(s)/file/ftp tabs can run a content script; skip chrome://, the\n // extension's own pages, about:blank, etc.\n function isInjectableUrl(url) {\n return typeof url === \"string\" && /^(https?|file|ftp):/i.test(url);\n }\n\n function stringList(value) {\n return Array.isArray(value) ? value.filter(function (v) { return typeof v === \"string\"; }) : [];\n }\n\n // The manifest glob dialect: * is any run of characters, ? exactly one,\n // and the pattern covers the whole url.\n function globMatches(glob, text) {\n var gi = 0, ti = 0, star = -1, mark = 0;\n while (ti < text.length) {\n if (gi < glob.length && (glob.charAt(gi) === \"?\" || glob.charAt(gi) === text.charAt(ti))) { gi++; ti++; }\n else if (gi < glob.length && glob.charAt(gi) === \"*\") { star = gi++; mark = ti; }\n else if (star !== -1) { gi = star + 1; ti = ++mark; }\n else return false;\n }\n while (gi < glob.length && glob.charAt(gi) === \"*\") gi++;\n return gi === glob.length;\n }\n\n // include_globs narrows matches and exclude_globs removes from them, the\n // same way the browser decides where the built extension runs.\n function passesGlobs(url, includeGlobs, excludeGlobs) {\n var u = String(url || \"\");\n var i;\n if (includeGlobs.length) {\n var included = false;\n for (i = 0; i < includeGlobs.length; i++) {\n if (globMatches(includeGlobs[i], u)) { included = true; break; }\n }\n if (!included) return false;\n }\n for (i = 0; i < excludeGlobs.length; i++) {\n if (globMatches(excludeGlobs[i], u)) return false;\n }\n return true;\n }\n\n // Re-inject one declared entry's fresh files into every matching open tab.\n // exclude_matches MUST be honored: query the excludes and subtract them.\n // opts.completeOnly skips a tab still loading: Chrome injects the static\n // script into it when it lands, and a second copy here would run twice.\n function reinjectContentScriptEntry(entry, opts) {\n var chrome = g.chrome;\n var completeOnly = !!(opts && opts.completeOnly);\n var matches = (entry && entry.matches) || [];\n if (!Array.isArray(matches) || !matches.length) return;\n var excludeMatches = (entry && entry.exclude_matches) || [];\n var includeGlobs = stringList(entry && entry.include_globs);\n var excludeGlobs = stringList(entry && entry.exclude_globs);\n var jsFiles = ((entry && entry.js) || []).filter(function (f) { return typeof f === \"string\"; });\n var cssFiles = ((entry && entry.css) || []).filter(function (f) { return typeof f === \"string\"; });\n if (!jsFiles.length && !cssFiles.length) return;\n var world = entry.world === \"MAIN\" ? \"MAIN\" : \"ISOLATED\";\n var allFrames = !!entry.all_frames;\n function injectInto(excludedTabIds) {\n try {\n chrome.tabs.query({url: matches}, function (tabs) {\n var err = null;\n try { err = chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n if (err || !tabs) return;\n for (var i = 0; i < tabs.length; i++) {\n (function (tab) {\n if (!tab || tab.id == null || !isInjectableUrl(tab.url)) return;\n if (excludedTabIds[tab.id]) return;\n if (!passesGlobs(tab.url, includeGlobs, excludeGlobs)) return;\n if (completeOnly && tab.status === \"loading\") return;\n var target = {tabId: tab.id, allFrames: allFrames};\n if (cssFiles.length && chrome.scripting.insertCSS) {\n try { chrome.scripting.insertCSS({target: target, files: cssFiles}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n if (jsFiles.length && chrome.scripting.executeScript) {\n try {\n chrome.scripting.executeScript(\n {target: target, files: jsFiles, world: world, injectImmediately: true},\n noopLastError\n );\n } catch (e) {\n // Ignore\n }\n }\n })(tabs[i]);\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n if (Array.isArray(excludeMatches) && excludeMatches.length) {\n try {\n chrome.tabs.query({url: excludeMatches}, function (excludedTabs) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var excluded = {};\n if (excludedTabs) {\n for (var i = 0; i < excludedTabs.length; i++) {\n if (excludedTabs[i] && excludedTabs[i].id != null) excluded[excludedTabs[i].id] = true;\n }\n }\n injectInto(excluded);\n });\n return;\n } catch (e) {\n // Ignore\n }\n }\n injectInto({});\n }\n\n // Re-inject all content scripts into their open tabs. Reads the manifest\n // FROM DISK: getManifest() is frozen and dev filenames are content-hashed.\n // opts.register false skips the dynamic registration: at boot the static\n // manifest already names the current files, and a copy injects twice.\n function reinjectContentScripts(onDone, opts) {\n var chrome = g.chrome;\n var register = !opts || opts.register !== false;\n try {\n if (typeof g.fetch !== \"function\" || !chrome.scripting) return false;\n g.fetch(chrome.runtime.getURL(\"manifest.json\"), {cache: \"no-store\"})\n .then(function (r) { return r.json(); })\n .then(function (manifest) {\n var entries = (manifest && manifest.content_scripts) || [];\n for (var i = 0; i < entries.length; i++) reinjectContentScriptEntry(entries[i], opts);\n if (register) reregisterForFutureNavigations(entries);\n if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } }\n })\n .catch(function () {\n // Ignore\n });\n return true;\n } catch (e) { return false; }\n }\n\n function mapRunAt(runAt) {\n if (runAt === \"document_start\") return \"document_start\";\n if (runAt === \"document_end\") return \"document_end\";\n return \"document_idle\";\n }\n\n // Re-register content scripts dynamically at the fresh files, so tabs\n // opened AFTER an edit also get the new build. Idempotent per entry id.\n function reregisterForFutureNavigations(entries) {\n var chrome = g.chrome;\n if (\n !chrome.scripting ||\n !chrome.scripting.registerContentScripts ||\n !chrome.scripting.getRegisteredContentScripts\n ) return;\n\n var scripts = [];\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i] || {};\n if (!Array.isArray(e.matches) || !e.matches.length) continue;\n // registerContentScripts has no glob keys, so a copy of a globbed\n // entry would run on pages the built extension never reaches.\n if (stringList(e.include_globs).length || stringList(e.exclude_globs).length) continue;\n var js = (e.js || []).filter(function (f) { return typeof f === \"string\"; });\n var css = (e.css || []).filter(function (f) { return typeof f === \"string\"; });\n if (!js.length && !css.length) continue;\n // Every field is sent: updateContentScripts keeps any key left out, so\n // a dropped exclude_matches, css file or fallback would outlive the edit.\n scripts.push({\n id: \"extjs-dev-cs-\" + i,\n matches: e.matches,\n excludeMatches: (e.exclude_matches || []).filter(function (p) { return typeof p === \"string\"; }),\n js: js,\n css: css,\n runAt: mapRunAt(e.run_at),\n allFrames: !!e.all_frames,\n world: e.world === \"MAIN\" ? \"MAIN\" : \"ISOLATED\",\n matchOriginAsFallback: e.match_origin_as_fallback === true,\n // A browser restart loads the static manifest fresh; a copy that\n // outlived the session would inject every page twice.\n persistAcrossSessions: false\n });\n }\n if (!scripts.length) return;\n\n try {\n chrome.scripting.getRegisteredContentScripts(function (existing) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var have = {};\n if (existing) for (var k = 0; k < existing.length; k++) have[existing[k].id] = true;\n var toRegister = [], toUpdate = [];\n for (var j = 0; j < scripts.length; j++) {\n (have[scripts[j].id] ? toUpdate : toRegister).push(scripts[j]);\n }\n if (toRegister.length) {\n try { chrome.scripting.registerContentScripts(toRegister, noopLastError); } catch (e) {\n // Ignore\n }\n }\n if (toUpdate.length) {\n try { chrome.scripting.updateContentScripts(toUpdate, noopLastError); } catch (e) {\n // Ignore\n }\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // The dev content-script runtime (plugin-reload) owns registration, the\n // boot heal and the tab reloads when its registry exists; absent, the\n // manifest-based paths below stay in charge.\n function devContentScripts() {\n try { return g.__extjsDevContentScripts || null; } catch (e) { return null; }\n }\n\n // An extension reload unloads chrome_url_overrides, and Chromium leaves\n // the open override tabs on its stock page. Only a fresh navigation to the\n // browser url (a tab reload does not) picks the override up again.\n var OVERRIDE_TABS_KEY = \"__extjsDevOverrideTabs\";\n var OVERRIDE_KINDS = [\"newtab\", \"history\", \"bookmarks\"];\n\n function overriddenKinds() {\n var m = null;\n try { m = g.chrome.runtime.getManifest(); } catch (e) { return []; }\n var o = m && m.chrome_url_overrides;\n var out = [];\n if (!o) return out;\n for (var i = 0; i < OVERRIDE_KINDS.length; i++) {\n if (typeof o[OVERRIDE_KINDS[i]] === \"string\" && o[OVERRIDE_KINDS[i]]) out.push(OVERRIDE_KINDS[i]);\n }\n return out;\n }\n\n // chrome://newtab/, edge://history and the like. Gecko shows about: urls\n // there, which this never matches, so other engines record nothing.\n function overrideKindOf(url, kinds) {\n var match = /^[a-z-]+:[/][/]([a-z]+)[/]?(?:[?#].*)?$/.exec(String(url || \"\"));\n return match && kinds.indexOf(match[1]) !== -1 ? match[1] : null;\n }\n\n // A reload closes the extension's own tabs on Chromium and leaves them on\n // the old document on Gecko, so the next generation brings each one back.\n var PAGE_TABS_KEY = \"__extjsDevPageTabs\";\n\n function ownPageUrl(url) {\n var base = \"\";\n try { base = String(g.chrome.runtime.getURL(\"\")); } catch (e) {\n // Ignore\n }\n return !!base && typeof url === \"string\" && url.indexOf(base) === 0;\n }\n\n // Records the override tabs and the extension's own page tabs, and answers\n // with the former. The guard keeps a silent tabs.query off the reload.\n function rememberOverrideTabs(cb) {\n var chrome = g.chrome;\n var answered = false;\n var guard = null;\n var answer = function (list) {\n if (answered) return;\n answered = true;\n if (guard) { try { clearTimeout(guard); } catch (e) {\n // Ignore\n } }\n try { cb(list); } catch (e) {\n // Ignore\n }\n };\n var kinds = overriddenKinds();\n if (!chrome.tabs || !chrome.tabs.query || !chrome.storage || !chrome.storage.local) return answer([]);\n try { guard = setTimeout(function () { answer([]); }, 1000); } catch (e) {\n // Ignore\n }\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n var list = [];\n var pages = [];\n for (var i = 0; tabs && i < tabs.length; i++) {\n var t = tabs[i];\n if (!t || t.id == null) continue;\n var kind = kinds.length ? overrideKindOf(t.url, kinds) : null;\n if (kind) list.push({tabId: t.id, surface: kind, url: t.url});\n else if (ownPageUrl(t.url)) {\n pages.push({tabId: t.id, url: t.url, windowId: t.windowId, index: t.index, active: t.active === true, pinned: t.pinned === true});\n }\n }\n if (!list.length && !pages.length) return answer(list);\n try {\n var rec = {};\n if (list.length) rec[OVERRIDE_TABS_KEY] = {at: Date.now(), tabs: list};\n if (pages.length) rec[PAGE_TABS_KEY] = {at: Date.now(), tabs: pages};\n chrome.storage.local.set(rec, function () { noopLastError(); answer(list); });\n } catch (e) { answer([]); }\n });\n } catch (e) { answer([]); }\n }\n\n // Shared by every path that restarts the extension, so none of them\n // strands the override tabs.\n function restartExtension(delayMs, onRecorded) {\n // Every restart path flags the next generation's heal, so open tabs get\n // their content scripts back whichever path asked for the reload.\n try {\n if (g.chrome && g.chrome.storage && g.chrome.storage.local) {\n g.chrome.storage.local.set({__extjsDevPendingReinject: Date.now()}, noopLastError);\n }\n } catch (e) {\n // Ignore\n }\n rememberOverrideTabs(function (list) {\n if (onRecorded) { try { onRecorded(list); } catch (e) {\n // Ignore\n } }\n try { setTimeout(function () { try { g.chrome.runtime.reload(); } catch (e) {\n // Ignore\n } }, delayMs); } catch (e) {\n // Ignore\n }\n });\n }\n g.__extjsDevRestartExtension = restartExtension;\n\n // The new generation sends each recorded tab back to its browser url, once,\n // unless the tab has navigated elsewhere since.\n function restoreOverrideTabsAtBoot() {\n var chrome = g.chrome;\n if (!chrome || !chrome.storage || !chrome.storage.local || !chrome.tabs || !chrome.tabs.update) return;\n chrome.storage.local.get(OVERRIDE_TABS_KEY, function (res) {\n noopLastError();\n var rec = res && res[OVERRIDE_TABS_KEY];\n if (!rec || typeof rec !== \"object\" || !Array.isArray(rec.tabs)) return;\n try { chrome.storage.local.remove(OVERRIDE_TABS_KEY, noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof rec.at !== \"number\" || Date.now() - rec.at > 30000) return;\n var kinds = overriddenKinds();\n setTimeout(function () {\n for (var i = 0; i < rec.tabs.length; i++) {\n (function (t) {\n if (!t || t.tabId == null || kinds.indexOf(t.surface) === -1) return;\n var go = function () {\n try { chrome.tabs.update(t.tabId, {url: t.url}, noopLastError); } catch (e) {\n // Ignore\n }\n };\n if (!chrome.tabs.get) return go();\n try {\n chrome.tabs.get(t.tabId, function (tab) {\n noopLastError();\n if (tab && overrideKindOf(tab.url, kinds) === t.surface) go();\n });\n } catch (e) {\n // Ignore\n }\n })(rec.tabs[i]);\n }\n }, 250);\n });\n }\n\n function reopenPageTab(page) {\n var chrome = g.chrome;\n var plain = function () {\n try { chrome.tabs.create({url: page.url, active: page.active === true}, noopLastError); } catch (e) {\n // Ignore\n }\n };\n try {\n chrome.tabs.create(\n {url: page.url, windowId: page.windowId, index: page.index, active: page.active === true, pinned: page.pinned === true},\n function () {\n var failed = false;\n try { failed = !!chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n // The window went with its last tab, so any window will do.\n if (failed) plain();\n }\n );\n } catch (e) { plain(); }\n }\n\n // A tab still open is reloaded, one the browser closed is opened again\n // unless the extension did so itself. Each recorded tab once.\n function restorePageTabsAtBoot() {\n var chrome = g.chrome;\n if (!chrome || !chrome.storage || !chrome.storage.local || !chrome.tabs || !chrome.tabs.query) return;\n chrome.storage.local.get(PAGE_TABS_KEY, function (res) {\n noopLastError();\n var rec = res && res[PAGE_TABS_KEY];\n if (!rec || typeof rec !== \"object\" || !Array.isArray(rec.tabs)) return;\n try { chrome.storage.local.remove(PAGE_TABS_KEY, noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof rec.at !== \"number\" || Date.now() - rec.at > 30000) return;\n setTimeout(function () {\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n var open = {};\n var byId = {};\n for (var i = 0; tabs && i < tabs.length; i++) {\n var t = tabs[i];\n if (!t || t.id == null) continue;\n byId[t.id] = t;\n if (typeof t.url === \"string\") open[t.url] = true;\n }\n for (var p = 0; p < rec.tabs.length; p++) {\n var page = rec.tabs[p];\n if (!page || typeof page.url !== \"string\" || !ownPageUrl(page.url)) continue;\n var kept = byId[page.tabId];\n // A tab that is still there and shows something else moved on.\n if (kept) {\n if (kept.url === page.url) {\n try { chrome.tabs.reload(page.tabId, {bypassCache: true}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n continue;\n }\n if (open[page.url] || !chrome.tabs.create) continue;\n open[page.url] = true;\n reopenPageTab(page);\n }\n });\n } catch (e) {\n // Ignore\n }\n }, 500);\n });\n }\n\n // A page the build ships as written has no dev client to refresh it, so\n // the open tabs that show it are reloaded from here.\n function reloadStandalonePages(files) {\n var chrome = g.chrome;\n if (!Array.isArray(files) || !files.length || !chrome || !chrome.tabs || !chrome.tabs.query || !chrome.tabs.reload) return;\n var wanted = {};\n for (var i = 0; i < files.length; i++) {\n if (typeof files[i] !== \"string\") continue;\n try { wanted[String(chrome.runtime.getURL(scriptFileName(files[i])))] = true; } catch (e) {\n // Ignore\n }\n }\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n for (var t = 0; tabs && t < tabs.length; t++) {\n var tab = tabs[t];\n if (!tab || tab.id == null || typeof tab.url !== \"string\") continue;\n if (!wanted[tab.url.replace(/[?#].*$/, \"\")]) continue;\n try { chrome.tabs.reload(tab.id, {bypassCache: true}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // Dev-loop reload without the CDP controller: content-scripts reload the\n // matching tabs at the new bundle, or re-inject in place where no registry\n // exists; service-worker/full/manifest restart the extension.\n function performDevReload(type, onDone, frame) {\n var chrome = g.chrome;\n if (!chrome) return;\n\n var fullReload = function () {\n // restartExtension flags the next generation's heal before it reloads.\n // Deferred so in-flight frames and the tab console announcement flush\n // before the SW dies; the devtools companion confirms completion.\n restartExtension(150);\n };\n\n if (type === \"content-scripts\" && chrome.scripting && chrome.tabs && chrome.tabs.query) {\n var dev = devContentScripts();\n if (dev && typeof dev.reload === \"function\") {\n try {\n dev.reload(frame && frame.changedContentScriptEntries, function (handled) {\n if (handled) { if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } } return; }\n if (reinjectContentScripts(onDone)) return;\n fullReload();\n });\n return;\n } catch (e) {\n // Ignore\n }\n }\n if (reinjectContentScripts(onDone)) return;\n }\n\n fullReload();\n }\n\n // One server-built label travels the ReloadFrame; the announcement\n // fires HERE, next to the actual reload action, so it stays true.\n\n // console.log the reload line into every open injectable tab; the patched\n // ISOLATED-world console also lands it in the dev-server log stream.\n function announceReloadInTabs(text) {\n var chrome = g.chrome;\n if (!chrome || !chrome.tabs || !chrome.tabs.query) return;\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n if (!tabs) return;\n for (var i = 0; i < tabs.length; i++) {\n (function (tab) {\n if (!tab || tab.id == null || !isInjectableUrl(tab.url)) return;\n if (chrome.scripting && chrome.scripting.executeScript) {\n try {\n chrome.scripting.executeScript(\n {target: {tabId: tab.id}, func: function (t) { console.log(t); }, args: [text]},\n noopLastError\n );\n return;\n } catch (e) {\n // Ignore\n }\n }\n // MV2 fallback (Firefox without the scripting API).\n if (chrome.tabs.executeScript) {\n try {\n chrome.tabs.executeScript(tab.id, {code: \"console.log(\" + JSON.stringify(text) + \");\"}, noopLastError);\n } catch (e) {\n // Ignore\n }\n }\n })(tabs[i]);\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // The scripts-replay shim (plugin-reload) keeps the SW's own\n // executeScript registry; the replay is fire-and-forget by design.\n // The answer is the number of open tabs a changed file ran in again.\n function replayProgrammaticScripts(changedScriptFiles, done) {\n var answer = function (outcomes) {\n var tabs = {};\n var count = 0;\n for (var i = 0; Array.isArray(outcomes) && i < outcomes.length; i++) {\n var one = outcomes[i];\n if (!one || !one.ok || tabs[one.tabId]) continue;\n tabs[one.tabId] = true;\n count++;\n }\n if (done) done(count);\n };\n if (!Array.isArray(changedScriptFiles) || changedScriptFiles.length === 0) return answer();\n var replay = g.__extjsScriptsReplay;\n if (typeof replay !== \"function\") return answer();\n try {\n var outcome = replay(changedScriptFiles);\n if (outcome && typeof outcome.then === \"function\") {\n outcome.then(answer, function () { answer(); });\n } else answer();\n } catch (e) { answer(); }\n }\n\n // The receipt of a reload that reloads nothing itself waits a moment\n // for its replay, so it can say how many tabs ran the file again.\n var REPLAY_RECEIPT_WAIT_MS = 500;\n var sendHeldReloadAck = null;\n\n // The browser reads a file named in scripting.registerContentScripts when\n // the script is registered, so an edit reaches no page until it reads again.\n var REGISTERED_RELOAD_KEY = \"__extjsDevRegisteredReload\";\n\n function scriptFileName(value) {\n return String(value || \"\").replace(/^[/]+/, \"\");\n }\n\n // Gecko reads a registered file once per address and keeps that copy\n // through an update and a tab reload. A new address is read from disk.\n var SCRIPT_ADDRESS_QUERY = \"?extjs-dev=\";\n var SCRIPT_VERSIONS_KEY = \"__extjsDevScriptVersions\";\n var scriptVersions = null;\n var scriptVersionWaiters = [];\n var scriptVersionCount = 0;\n var wrappedRegistries = [];\n var nativeRegistry = null;\n var registryCalls = 0;\n // An entry no registration has, so the browser refuses a call that\n // names it and changes nothing.\n var SHAPE_REFUSED = {id: \"_extjs-dev-shape\", js: [\"extjs-dev-shape.js\"], matches: [\"*://extjs.invalid/*\"]};\n var registryCalledAt = 0;\n\n function plainScriptAddress(value) {\n var name = String(value || \"\");\n var at = name.indexOf(SCRIPT_ADDRESS_QUERY);\n return at === -1 ? name : name.slice(0, at);\n }\n\n // A name that carries its own query or fragment is the author's address.\n function scriptAddress(value) {\n var plain = plainScriptAddress(value);\n if (plain.indexOf(\"?\") !== -1 || plain.indexOf(\"#\") !== -1) return plain;\n var version = scriptVersions ? scriptVersions[scriptFileName(plain)] : null;\n return typeof version === \"string\" ? plain + SCRIPT_ADDRESS_QUERY + version : plain;\n }\n\n function withFileNames(scripts, rename) {\n if (!Array.isArray(scripts)) return scripts;\n var renamed = function (files) {\n var out = [];\n for (var f = 0; f < files.length; f++) out.push(typeof files[f] === \"string\" ? rename(files[f]) : files[f]);\n return out;\n };\n var list = [];\n for (var i = 0; i < scripts.length; i++) {\n var script = scripts[i];\n if (!script || typeof script !== \"object\") { list.push(script); continue; }\n var copy = {};\n for (var key in script) {\n if (Object.prototype.hasOwnProperty.call(script, key)) copy[key] = script[key];\n }\n if (Array.isArray(script.js)) copy.js = renamed(script.js);\n if (Array.isArray(script.css)) copy.css = renamed(script.css);\n list.push(copy);\n }\n return list;\n }\n\n // Session storage outlives a suspended background and is emptied by an\n // extension reload, which is when every address is read again anyway.\n function withScriptVersions(cb) {\n if (scriptVersions) return cb();\n scriptVersionWaiters.push(cb);\n if (scriptVersionWaiters.length > 1) return;\n var done = function (map) {\n if (!scriptVersions) scriptVersions = map && typeof map === \"object\" ? map : {};\n var fns = scriptVersionWaiters;\n scriptVersionWaiters = [];\n for (var i = 0; i < fns.length; i++) { try { fns[i](); } catch (e) {\n // Ignore\n } }\n };\n try { setTimeout(function () { done(null); }, 1000); } catch (e) {\n // Ignore\n }\n try {\n g.chrome.storage.session.get(SCRIPT_VERSIONS_KEY, function (res) {\n noopLastError();\n done(res && res[SCRIPT_VERSIONS_KEY]);\n });\n } catch (e) { done(null); }\n }\n\n // The author's calls keep the names they wrote: a write takes the current\n // address of each file, and a read gives the plain names back.\n function wrapScriptRegistry(scripting) {\n if (!scripting || wrappedRegistries.indexOf(scripting) !== -1) return;\n if (typeof scripting.registerContentScripts !== \"function\" || typeof scripting.updateContentScripts !== \"function\") return;\n wrappedRegistries.push(scripting);\n var natives = {};\n // One namespace of an engine can answer a callback and hand nothing\n // back, so a single read tells which of the two forms this one has.\n var style = null;\n var answersCallback = function () {\n if (style === null) {\n var read;\n try { read = natives.getRegisteredContentScripts(); } catch (e) { style = false; return style; }\n style = !(read && typeof read.then === \"function\");\n if (!style) read.then(function () {}, function () {});\n }\n return style;\n };\n var wrapWrite = function (method, addresses) {\n if (typeof scripting[method] !== \"function\") return;\n var native = scripting[method].bind(scripting);\n natives[method] = native;\n scripting[method] = function () {\n var args = [].slice.call(arguments);\n var last = args.length - 1;\n var done = last >= 0 && typeof args[last] === \"function\" ? args[last] : null;\n registryCalls++;\n registryCalledAt = Date.now();\n var settled = false;\n var settle = function () {\n if (settled) return;\n settled = true;\n registryCalls--;\n registryCalledAt = Date.now();\n };\n var call = function () {\n if (addresses) args[0] = withFileNames(args[0], scriptAddress);\n if (done) args[last] = function () { settle(); return done.apply(this, arguments); };\n // The error is left unread, so the browser still names it.\n else if (answersCallback()) args.push(function () { settle(); });\n var ret = native.apply(null, args);\n if (done) return ret;\n if (ret && typeof ret.then === \"function\") ret.then(settle, settle);\n else if (!answersCallback()) settle();\n return ret;\n };\n if (!addresses || scriptVersions || !Array.isArray(args[0])) {\n try { return call(); } catch (e) { settle(); throw e; }\n }\n // The browser checks the shape of a call as it is made. The same\n // call with an entry it refuses later throws that check here.\n try {\n var refusal = method === \"registerContentScripts\" ? [SHAPE_REFUSED, SHAPE_REFUSED] : [{id: SHAPE_REFUSED.id}];\n var probe = [args[0].concat(refusal)];\n if (done || answersCallback()) probe.push(noopLastError);\n var refused;\n try { refused = native.apply(null, probe); } catch (e) {\n if (!done) throw e;\n probe.pop();\n refused = native.apply(null, probe);\n }\n if (refused && typeof refused.then === \"function\") refused.then(function () {}, function () {});\n } catch (e) { settle(); throw e; }\n // A call that hands nothing back is answered the same way here.\n if (done || answersCallback()) {\n withScriptVersions(function () { try { call(); } catch (e) { settle(); } });\n return undefined;\n }\n return new Promise(function (resolve, reject) {\n withScriptVersions(function () { try { resolve(call()); } catch (e) { settle(); reject(e); } });\n });\n };\n };\n if (typeof scripting.getRegisteredContentScripts !== \"function\") style = false;\n else natives.getRegisteredContentScripts = scripting.getRegisteredContentScripts.bind(scripting);\n wrapWrite(\"registerContentScripts\", true);\n wrapWrite(\"updateContentScripts\", true);\n wrapWrite(\"unregisterContentScripts\", false);\n if (typeof scripting.getRegisteredContentScripts === \"function\") {\n var nativeRead = natives.getRegisteredContentScripts;\n var plain = function (list) { return withFileNames(list, plainScriptAddress); };\n scripting.getRegisteredContentScripts = function () {\n var args = [].slice.call(arguments);\n var last = args.length - 1;\n if (last >= 0 && typeof args[last] === \"function\") {\n var done = args[last];\n args[last] = function (list) { return done.call(this, plain(list)); };\n return nativeRead.apply(null, args);\n }\n var ret = nativeRead.apply(null, args);\n return ret && typeof ret.then === \"function\" ? ret.then(plain) : ret;\n };\n }\n wrapInjection(scripting, answersCallback);\n if (!nativeRegistry) nativeRegistry = natives;\n }\n\n // Gecko runs the copy of an injected file it read first at an address,\n // so a file edited since is named at its current one, as a registration is.\n function wrapInjection(scripting, answersCallback) {\n if (typeof scripting.executeScript !== \"function\") return;\n var native = scripting.executeScript.bind(scripting);\n scripting.executeScript = function (injection) {\n var args = [].slice.call(arguments);\n var last = args.length - 1;\n var done = last > 0 && typeof args[last] === \"function\";\n var target = injection && typeof injection === \"object\" ? injection.target : null;\n if (!target || typeof target !== \"object\" || !Array.isArray(injection.files)) return native.apply(null, args);\n var call = function () {\n var copy = {};\n for (var key in injection) {\n if (Object.prototype.hasOwnProperty.call(injection, key)) copy[key] = injection[key];\n }\n copy.files = [];\n for (var f = 0; f < injection.files.length; f++) {\n copy.files.push(typeof injection.files[f] === \"string\" ? scriptAddress(injection.files[f]) : injection.files[f]);\n }\n args[0] = copy;\n return native.apply(null, args);\n };\n if (scriptVersions) return call();\n if (typeof target.tabId !== \"number\") return native.apply(null, args);\n // The browser checks the shape of a call as it is made. The same\n // call on a tab that cannot exist throws that check here.\n var probe = args.slice();\n var nowhere = {};\n for (var name in target) {\n if (Object.prototype.hasOwnProperty.call(target, name)) nowhere[name] = target[name];\n }\n nowhere.tabId = -1;\n probe[0] = {};\n for (var field in injection) {\n if (Object.prototype.hasOwnProperty.call(injection, field)) probe[0][field] = injection[field];\n }\n probe[0].target = nowhere;\n var unanswered = !done && answersCallback();\n if (done) probe[last] = noopLastError;\n else if (unanswered) probe.push(noopLastError);\n var refused = native.apply(null, probe);\n if (refused && typeof refused.then === \"function\") refused.then(function () {}, function () {});\n if (done || unanswered) {\n withScriptVersions(function () { try { call(); } catch (e) {\n // Ignore\n } });\n return undefined;\n }\n return new Promise(function (resolve, reject) {\n withScriptVersions(function () { try { resolve(call()); } catch (e) { reject(e); } });\n });\n };\n }\n\n function canAddressRegisteredScripts() {\n var chrome = g.chrome;\n return !!(\n engineName() === \"firefox\" && nativeRegistry && nativeRegistry.updateContentScripts &&\n chrome && chrome.storage && chrome.storage.session && chrome.storage.session.get && chrome.storage.session.set\n );\n }\n\n // Installed before the background's own code runs, so its first call\n // already goes through here.\n function installScriptAddresses() {\n var chrome = g.chrome;\n if (engineName() !== \"firefox\" || !chrome || !chrome.storage || !chrome.storage.session || !chrome.storage.session.get) return;\n var roots = [g.chrome, g.browser];\n for (var i = 0; i < roots.length; i++) {\n try { wrapScriptRegistry(roots[i] && roots[i].scripting); } catch (e) {\n // Ignore\n }\n }\n if (nativeRegistry) withScriptVersions(function () {});\n }\n\n // The first page of a session waits for the registrations a background\n // makes as it starts, so its boot is watched from the first line.\n var BOOT_IDLE_CHECK_MS = 25;\n var BOOT_EVENTS_GRACE_MS = 250;\n var BOOT_GIVE_UP_MS = 4000;\n var BOOT_LATE_WINDOW_MS = 15000;\n\n function watchBootRegistrations() {\n if (g.__extjsDevBootRegisters !== true) return;\n var bootedAt = Date.now();\n var inFlight = 0;\n var calls = 0;\n var landed = false;\n var reported = false;\n var lateSaid = false;\n var counted = [];\n var failed = function () {\n try { return !!(g.chrome && g.chrome.runtime && g.chrome.runtime.lastError); } catch (e) { return false; }\n };\n var devId = function (entry) {\n var id = entry && typeof entry === \"object\" ? entry.id : entry;\n return typeof id === \"string\" && id.indexOf(\"extjs-dev-cs-\") === 0;\n };\n // The dev build registers the manifest's own scripts through the same\n // calls, and those are not the author's registrations.\n var ownCall = function (first) {\n var list = Array.isArray(first) ? first : first && Array.isArray(first.ids) ? first.ids : null;\n if (!list || !list.length) return false;\n for (var i = 0; i < list.length; i++) if (!devId(list[i])) return false;\n return true;\n };\n // A registration that answers after the page was let go is on no open\n // page, which the author is told once.\n var land = function () {\n landed = true;\n if (!reported || lateSaid || Date.now() - bootedAt > BOOT_LATE_WINDOW_MS) return;\n lateSaid = true;\n send({type: \"boot-registrations\", late: true, afterMs: Date.now() - bootedAt});\n };\n // Any call the boot code is waiting on can be the one a registration\n // follows, so each is counted until the browser answers it.\n var count = function (owner, key, registry, method) {\n var inner = owner[key];\n if (typeof inner !== \"function\" || inner.__extjsBootCounted) return;\n var wrapper = function () {\n var args = [].slice.call(arguments);\n var self = method ? this : owner;\n if (registry && ownCall(args[0])) return inner.apply(self, args);\n var last = args.length - 1;\n var done = last >= 0 && typeof args[last] === \"function\" ? args[last] : null;\n var settled = false;\n var settle = function (ok) {\n if (settled) return;\n settled = true;\n inFlight--;\n if (ok && registry === \"write\") land();\n };\n inFlight++;\n if (registry) calls++;\n if (done) args[last] = function () { settle(!failed()); return done.apply(this, arguments); };\n var ret;\n try { ret = inner.apply(self, args); } catch (e) { settle(false); throw e; }\n if (done) return ret;\n if (!ret || typeof ret.then !== \"function\") { settle(true); return ret; }\n // The caller gets the same outcome, so a rejection it ignores is\n // still reported as unhandled.\n return ret.then(function (value) { settle(true); return value; }, function (error) { settle(false); throw error; });\n };\n wrapper.__extjsBootCounted = true;\n try {\n owner[key] = wrapper;\n if (owner[key] === wrapper) counted.push({owner: owner, key: key, inner: inner, wrapper: wrapper, kept: !!registry});\n } catch (e) {\n // Ignore\n }\n };\n var walk = function (owner, depth, seen) {\n var keys = [];\n try { keys = Object.keys(owner); } catch (e) {\n // Ignore\n }\n for (var i = 0; i < keys.length; i++) {\n var value;\n try { value = owner[keys[i]]; } catch (e) { continue; }\n if (typeof value === \"function\") { count(owner, keys[i], null); continue; }\n if (!value || typeof value !== \"object\" || depth >= 3 || seen.indexOf(value) !== -1) continue;\n // An event has listeners, not answers.\n if (typeof value.addListener === \"function\") continue;\n seen.push(value);\n walk(value, depth + 1, seen);\n }\n };\n // A registration a profile kept from an earlier session is already\n // there for the first page, whatever the background does next.\n var readKept = function (scripting) {\n if (typeof scripting.getRegisteredContentScripts !== \"function\") return;\n inFlight++;\n var answered = false;\n var answer = function (list) {\n if (answered) return;\n answered = true;\n inFlight--;\n for (var i = 0; list && i < list.length; i++) {\n if (list[i] && typeof list[i].id === \"string\" && !devId(list[i])) landed = true;\n }\n };\n try {\n var ret = scripting.getRegisteredContentScripts(function (list) { noopLastError(); answer(list); });\n if (ret && typeof ret.then === \"function\") ret.then(answer, function () { answer(null); });\n } catch (e) { answer(null); }\n };\n var roots = [g.chrome, g.browser];\n var seen = [];\n var read = false;\n for (var r = 0; r < roots.length; r++) {\n var root = roots[r];\n if (!root || seen.indexOf(root) !== -1) continue;\n seen.push(root);\n var scripting = null;\n try { scripting = root.scripting; } catch (e) {\n // Ignore\n }\n if (scripting && seen.indexOf(scripting) === -1) {\n if (!read) { read = true; readKept(scripting); }\n count(scripting, \"registerContentScripts\", \"write\");\n count(scripting, \"updateContentScripts\", \"write\");\n count(scripting, \"unregisterContentScripts\", \"call\");\n count(scripting, \"getRegisteredContentScripts\", \"call\");\n }\n walk(root, 1, seen);\n }\n if (typeof g.fetch === \"function\") count(g, \"fetch\", null);\n // A response is read after it arrived, and the read is waited on too.\n var body = g.Response && g.Response.prototype;\n var reads = [\"json\", \"text\", \"arrayBuffer\", \"blob\", \"formData\"];\n for (var b = 0; body && b < reads.length; b++) count(body, reads[b], null, true);\n\n // Once it has reported, the background runs on the browser's own calls\n // again. The registry stays counted for a late registration.\n var release = function () {\n for (var i = 0; i < counted.length; i++) {\n var c = counted[i];\n if (c.kept) continue;\n try { if (c.owner[c.key] === c.wrapper) c.owner[c.key] = c.inner; } catch (e) {\n // Ignore\n }\n }\n };\n\n // The browser hands a starting background its install events right\n // after its top level ran, and their listeners are boot code too.\n var eventsDone = false;\n var eventsDue = function () { eventsDone = true; };\n var worker = null;\n try { worker = g.serviceWorker && typeof g.serviceWorker.state === \"string\" ? g.serviceWorker : null; } catch (e) {\n // Ignore\n }\n var doc = null;\n try { doc = g.document && typeof g.document.readyState === \"string\" ? g.document : null; } catch (e) {\n // Ignore\n }\n if (worker && worker.state !== \"activated\" && typeof g.addEventListener === \"function\") {\n // An installing worker gets onInstalled before it activates.\n g.addEventListener(\"activate\", function () { setTimeout(eventsDue, 0); });\n setTimeout(eventsDue, 1000);\n } else if (!worker && doc && g.chrome && g.chrome.runtime && g.chrome.runtime.onInstalled) {\n // Gecko fires onInstalled a moment after the page loaded, and not at\n // all for a background it only woke.\n var afterLoad = function () { setTimeout(eventsDue, BOOT_EVENTS_GRACE_MS); };\n g.chrome.runtime.onInstalled.addListener(function () { setTimeout(eventsDue, 0); });\n if (doc.readyState === \"complete\" || typeof g.addEventListener !== \"function\") afterLoad();\n else g.addEventListener(\"load\", afterLoad);\n } else {\n setTimeout(eventsDue, worker ? 0 : BOOT_EVENTS_GRACE_MS);\n }\n\n var idleOnce = false;\n var check = function () {\n if (reported) return;\n var gaveUp = Date.now() - bootedAt >= BOOT_GIVE_UP_MS;\n var idle = eventsDone && inFlight <= 0;\n if ((idle && idleOnce) || gaveUp) {\n reported = true;\n release();\n var frame = {type: \"boot-registrations\", calls: calls, landed: landed};\n if (!(idle && idleOnce)) { frame.pending = true; lateSaid = true; }\n send(frame);\n return;\n }\n idleOnce = idle;\n try { setTimeout(check, BOOT_IDLE_CHECK_MS); } catch (e) {\n // Ignore\n }\n };\n setTimeout(check, 0);\n }\n\n // Every changed file gets a new address, registered now or later.\n function moveScriptAddresses(changedScriptFiles, cb) {\n withScriptVersions(function () {\n var version = Date.now().toString(36) + \"-\" + (scriptVersionCount++).toString(36);\n for (var i = 0; i < changedScriptFiles.length; i++) {\n var name = typeof changedScriptFiles[i] === \"string\" ? scriptFileName(changedScriptFiles[i]) : \"\";\n // A hot update file has a new name on every edit and is never registered.\n if (name && name.indexOf(\"hot/\") !== 0) scriptVersions[name] = version;\n }\n var rec = {};\n rec[SCRIPT_VERSIONS_KEY] = scriptVersions;\n try { g.chrome.storage.session.set(rec, noopLastError); } catch (e) {\n // Ignore\n }\n cb();\n });\n }\n\n // A background started for this edit may be between its own unregister\n // and register calls, and a read in that gap finds no registration.\n function whenRegistryQuiet(cb) {\n var waited = 0;\n // A loaded machine answers a call seconds late, and a read made\n // before that answer finds the gap and reloads no tab.\n var check = function () {\n if (waited >= 15000 || (registryCalls <= 0 && Date.now() - registryCalledAt >= 300)) return cb();\n waited += 100;\n try { setTimeout(check, 100); } catch (e) { cb(); }\n };\n check();\n }\n\n function registrationsNaming(existing, changedScriptFiles) {\n var changed = {};\n for (var c = 0; c < changedScriptFiles.length; c++) changed[scriptFileName(changedScriptFiles[c])] = true;\n var out = [];\n for (var i = 0; existing && i < existing.length; i++) {\n var s = existing[i];\n if (!s || typeof s.id !== \"string\" || s.id.indexOf(\"extjs-dev-cs-\") === 0) continue;\n var files = stringList(s.js).concat(stringList(s.css));\n for (var f = 0; f < files.length; f++) {\n if (changed[scriptFileName(plainScriptAddress(files[f]))]) { out.push(s); break; }\n }\n }\n return out;\n }\n\n // The ids of the open tabs the registrations match, excludeMatches honored.\n function tabIdsForRegistrations(scripts, cb) {\n var chrome = g.chrome;\n var ids = {};\n var pending = 1;\n var step = function () {\n pending--;\n if (pending > 0) return;\n var out = [];\n for (var id in ids) out.push(Number(id));\n cb(out);\n };\n var query = function (patterns, each) {\n if (!patterns.length || !chrome.tabs || !chrome.tabs.query) return each([]);\n try {\n chrome.tabs.query({url: patterns}, function (tabs) { noopLastError(); each(tabs || []); });\n } catch (e) { each([]); }\n };\n for (var i = 0; i < scripts.length; i++) {\n (function (script) {\n pending++;\n query(stringList(script.excludeMatches), function (excludedTabs) {\n var excluded = {};\n for (var x = 0; x < excludedTabs.length; x++) {\n if (excludedTabs[x] && excludedTabs[x].id != null) excluded[excludedTabs[x].id] = true;\n }\n query(stringList(script.matches), function (tabs) {\n for (var t = 0; t < tabs.length; t++) {\n var tab = tabs[t];\n if (!tab || tab.id == null || excluded[tab.id] || !isInjectableUrl(tab.url)) continue;\n ids[tab.id] = true;\n }\n step();\n });\n });\n })(scripts[i]);\n }\n step();\n }\n\n function reloadTabIds(tabIds) {\n var chrome = g.chrome;\n if (!chrome.tabs || !chrome.tabs.reload) return;\n for (var i = 0; i < tabIds.length; i++) {\n try { chrome.tabs.reload(tabIds[i], {}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n }\n\n // The update names each file at its current address, in the browser's\n // own call so nothing between here and it reads the names another way.\n function moveRegisteredScripts(scripts, cb) {\n var updates = [];\n for (var i = 0; i < scripts.length; i++) {\n var update = {id: scripts[i].id};\n if (stringList(scripts[i].js).length) update.js = stringList(scripts[i].js);\n if (stringList(scripts[i].css).length) update.css = stringList(scripts[i].css);\n updates.push(update);\n }\n try {\n nativeRegistry.updateContentScripts(withFileNames(updates, scriptAddress), function () {\n var failed = false;\n try { failed = !!g.chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n cb(!failed);\n });\n } catch (e) { cb(false); }\n }\n\n function restartForRegisteredScripts(scripts, tabIds) {\n var scriptIds = [];\n for (var i = 0; i < scripts.length; i++) scriptIds.push(scripts[i].id);\n try {\n var rec = {};\n rec[REGISTERED_RELOAD_KEY] = {at: Date.now(), tabs: tabIds, scripts: scriptIds};\n g.chrome.storage.local.set(rec, noopLastError);\n } catch (e) {\n // Ignore\n }\n if (sendHeldReloadAck) sendHeldReloadAck();\n restartExtension(150);\n }\n\n // Answers true when the extension restarts for the edit. Chromium reads the\n // files again on an update, Gecko reads them again at a new address.\n function refreshRegisteredScripts(changedScriptFiles, cb, moved) {\n var chrome = g.chrome;\n var answered = false;\n var guard = null;\n var answer = function (restarting) {\n if (answered) return;\n answered = true;\n if (guard) { try { clearTimeout(guard); } catch (e) {\n // Ignore\n } }\n try { cb(restarting); } catch (e) {\n // Ignore\n }\n };\n if (\n !Array.isArray(changedScriptFiles) || !changedScriptFiles.length ||\n !chrome || !chrome.scripting || !chrome.scripting.getRegisteredContentScripts\n ) return answer(false);\n var addressed = canAddressRegisteredScripts();\n var refresh = function () {\n try { guard = setTimeout(function () { answer(false); }, 1000); } catch (e) {\n // Ignore\n }\n // The update below is the browser's own call, so the read is too: a\n // wrapped read answers the names the author wrote, not the files run.\n var read = addressed && nativeRegistry.getRegisteredContentScripts\n ? nativeRegistry.getRegisteredContentScripts\n : function (done) { return chrome.scripting.getRegisteredContentScripts(done); };\n try {\n read(function (existing) {\n noopLastError();\n // The files already have their new address, so a slow answer\n // still moves the registrations and reloads their tabs.\n if (answered && !addressed) return;\n var scripts = registrationsNaming(existing, changedScriptFiles);\n if (!scripts.length) return answer(false);\n tabIdsForRegistrations(scripts, function (tabIds) {\n if (addressed) {\n return moveRegisteredScripts(scripts, function (moved) {\n if (moved) { reloadTabIds(tabIds); return answer(false); }\n if (answered) return;\n restartForRegisteredScripts(scripts, tabIds);\n answer(true);\n });\n }\n if (answered) return;\n if (engineName() === \"firefox\") {\n restartForRegisteredScripts(scripts, tabIds);\n return answer(true);\n }\n var updates = [];\n for (var u = 0; u < scripts.length; u++) {\n var update = {id: scripts[u].id};\n if (stringList(scripts[u].js).length) update.js = stringList(scripts[u].js);\n if (stringList(scripts[u].css).length) update.css = stringList(scripts[u].css);\n updates.push(update);\n }\n var finish = function () { noopLastError(); reloadTabIds(tabIds); answer(false); };\n if (!chrome.scripting.updateContentScripts) return finish();\n try { chrome.scripting.updateContentScripts(updates, finish); } catch (e) { finish(); }\n });\n });\n } catch (e) { answer(false); }\n };\n if (!addressed) return refresh();\n if (moved) return whenRegistryQuiet(refresh);\n moveScriptAddresses(changedScriptFiles, function () { whenRegistryQuiet(refresh); });\n }\n\n // The generation after that restart reloads the recorded tabs once two\n // reads in a row show the scripts registered, or a few seconds passed.\n function reloadRegisteredScriptTabsAtBoot() {\n var chrome = g.chrome;\n if (!chrome || !chrome.storage || !chrome.storage.local) return;\n chrome.storage.local.get(REGISTERED_RELOAD_KEY, function (res) {\n noopLastError();\n var rec = res && res[REGISTERED_RELOAD_KEY];\n if (!rec || typeof rec !== \"object\") return;\n try { chrome.storage.local.remove(REGISTERED_RELOAD_KEY, noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof rec.at !== \"number\" || Date.now() - rec.at > 30000 || !Array.isArray(rec.tabs)) return;\n var wanted = stringList(rec.scripts);\n var attempts = 0;\n var settled = 0;\n var check = function () {\n attempts++;\n var proceed = function (existing) {\n var have = {};\n for (var i = 0; existing && i < existing.length; i++) if (existing[i]) have[existing[i].id] = true;\n var missing = false;\n for (var w = 0; w < wanted.length; w++) if (!have[wanted[w]]) missing = true;\n // A background that unregisters before it registers leaves a gap.\n settled = missing ? 0 : settled + 1;\n if (settled < 2 && attempts < 20) return setTimeout(check, 250);\n reloadTabIds(rec.tabs);\n };\n try {\n chrome.scripting.getRegisteredContentScripts(function (existing) { noopLastError(); proceed(existing); });\n } catch (e) { reloadTabIds(rec.tabs); }\n };\n setTimeout(check, 250);\n });\n }\n\n // Gecko keeps a declared content script stylesheet by its address, for\n // open tabs and for later navigations, until the extension reloads.\n var SHEET_OVERRIDES_KEY = \"__extjsDevSheetOverrides\";\n var SHEET_SESSION_KEY = \"__extjsDevSheetSession\";\n var SHEET_SIGNAL = \"__extjsDevSheets\";\n var SHEET_ENTRIES_KEY = \"__extjsDevSheetEntries\";\n var SHEET_REGISTRATION_PREFIX = \"extjs-dev-cs-sheet-\";\n var sheetSessionChecked = false;\n var sheetSessionWaiters = [];\n var sheetOverrides = null;\n\n function sheetAddress(file, digest) {\n return file + \"?v=\" + String(digest).slice(0, 16);\n }\n\n // Gecko's getManifest names each content script file by its full address.\n function declaredFileName(value) {\n var name = String(value || \"\");\n var base = \"\";\n try { base = String(g.chrome.runtime.getURL(\"\")); } catch (e) {\n // Ignore\n }\n if (base && name.indexOf(base) === 0) name = name.slice(base.length);\n return scriptFileName(name);\n }\n\n function declaredEntries() {\n try { return g.chrome.runtime.getManifest().content_scripts || []; } catch (e) { return []; }\n }\n\n function declaredEntriesNaming(file) {\n var out = [];\n var entries = declaredEntries();\n var wanted = scriptFileName(file);\n for (var i = 0; i < entries.length; i++) {\n var css = stringList(entries[i] && entries[i].css);\n for (var c = 0; c < css.length; c++) {\n if (declaredFileName(css[c]) === wanted) { out.push(entries[i]); break; }\n }\n }\n return out;\n }\n\n // A frame names the bundles the browser ran in it, which is the browser's\n // own answer for matches, excludes, globs, frames and origin fallback.\n function entryRuns(entry, bundles) {\n var js = stringList(entry && entry.js);\n for (var i = 0; i < js.length; i++) {\n if (bundles.indexOf(declaredFileName(js[i])) !== -1) return true;\n }\n return false;\n }\n\n // Sent in this order and not awaited, so the new address is in the frame\n // before the old copies go. An address already there adds no second copy.\n function swapDeclaredSheet(target, file, previousDigest, digest) {\n var chrome = g.chrome;\n var stale = [file];\n if (previousDigest && previousDigest !== digest) stale.push(sheetAddress(file, previousDigest));\n try { chrome.scripting.insertCSS({target: target, files: [sheetAddress(file, digest)]}, noopLastError); } catch (e) {\n // Ignore\n }\n for (var i = 0; i < stale.length; i++) {\n try { chrome.scripting.removeCSS({target: target, files: [stale[i]]}, noopLastError); } catch (e) {\n // Ignore\n }\n }\n }\n\n function canSwapDeclaredSheets() {\n var chrome = g.chrome;\n return !!(\n engineName() === \"firefox\" && chrome && chrome.scripting && chrome.scripting.insertCSS &&\n chrome.scripting.removeCSS && chrome.scripting.executeScript && chrome.tabs && chrome.tabs.query &&\n chrome.storage && chrome.storage.local && chrome.storage.session\n );\n }\n\n // A registered sheet at the entry's own run_at lands after the declared\n // copy, so a later document starts on the new rules with no one awake.\n function registerSheetOverrides(overrides) {\n var chrome = g.chrome;\n if (\n !chrome.scripting.registerContentScripts || !chrome.scripting.getRegisteredContentScripts ||\n !chrome.scripting.updateContentScripts || !chrome.scripting.unregisterContentScripts\n ) return;\n var entries = declaredEntries();\n var wanted = [];\n for (var i = 0; i < entries.length; i++) {\n var entry = entries[i] || {};\n var matches = stringList(entry.matches);\n // A globbed entry has no registered form, its frames ask one by one.\n if (!matches.length || stringList(entry.include_globs).length || stringList(entry.exclude_globs).length) continue;\n var css = stringList(entry.css);\n var files = [];\n for (var c = 0; c < css.length; c++) {\n var name = declaredFileName(css[c]);\n if (typeof overrides[name] === \"string\") files.push(sheetAddress(name, overrides[name]));\n }\n if (!files.length) continue;\n wanted.push({\n id: SHEET_REGISTRATION_PREFIX + i,\n matches: matches,\n excludeMatches: stringList(entry.exclude_matches),\n css: files,\n runAt: mapRunAt(entry.run_at),\n allFrames: entry.all_frames === true,\n matchOriginAsFallback: entry.match_origin_as_fallback === true,\n persistAcrossSessions: false\n });\n }\n try {\n chrome.scripting.getRegisteredContentScripts(function (existing) {\n noopLastError();\n var have = {};\n for (var k = 0; existing && k < existing.length; k++) {\n var id = existing[k] && existing[k].id;\n if (typeof id === \"string\" && id.indexOf(SHEET_REGISTRATION_PREFIX) === 0) have[id] = true;\n }\n var toRegister = [], toUpdate = [], toDrop = [], keep = {};\n for (var j = 0; j < wanted.length; j++) {\n keep[wanted[j].id] = true;\n (have[wanted[j].id] ? toUpdate : toRegister).push(wanted[j]);\n }\n for (var old in have) if (!keep[old]) toDrop.push(old);\n try {\n if (toDrop.length) chrome.scripting.unregisterContentScripts({ids: toDrop}, noopLastError);\n if (toUpdate.length) chrome.scripting.updateContentScripts(toUpdate, noopLastError);\n if (toRegister.length) chrome.scripting.registerContentScripts(toRegister, noopLastError);\n } catch (e) {\n // Ignore\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // The overrides belong to one load of the extension: a reload reads every\n // declared file again, and session storage is what a reload empties.\n function checkSheetSession() {\n var chrome = g.chrome;\n var done = function () {\n sheetSessionChecked = true;\n var fns = sheetSessionWaiters;\n sheetSessionWaiters = [];\n for (var i = 0; i < fns.length; i++) { try { fns[i](); } catch (e) {\n // Ignore\n } }\n };\n if (!canSwapDeclaredSheets()) return done();\n try {\n chrome.storage.session.get(SHEET_SESSION_KEY, function (res) {\n noopLastError();\n if (res && res[SHEET_SESSION_KEY]) return done();\n var mark = {};\n mark[SHEET_SESSION_KEY] = Date.now();\n try { chrome.storage.session.set(mark, noopLastError); } catch (e) {\n // Ignore\n }\n sheetOverrides = {};\n try { registerSheetOverrides({}); } catch (e) {\n // Ignore\n }\n try { chrome.storage.local.remove(SHEET_OVERRIDES_KEY, function () { noopLastError(); done(); }); } catch (e) { done(); }\n });\n } catch (e) { done(); }\n }\n\n function withSheetOverrides(cb) {\n var read = function () {\n if (sheetOverrides) return cb(sheetOverrides);\n try {\n g.chrome.storage.local.get(SHEET_OVERRIDES_KEY, function (res) {\n noopLastError();\n var map = res && res[SHEET_OVERRIDES_KEY];\n sheetOverrides = map && typeof map === \"object\" ? map : {};\n cb(sheetOverrides);\n });\n } catch (e) { cb({}); }\n };\n if (sheetSessionChecked) read(); else sheetSessionWaiters.push(read);\n }\n\n // Asks every frame of a tab which declared bundles run in it.\n function bundlesByFrame(tabId, cb) {\n try {\n g.chrome.scripting.executeScript({\n target: {tabId: tabId, allFrames: true},\n args: [SHEET_ENTRIES_KEY],\n func: function (key) {\n try { return Object.keys(globalThis[key] || {}); } catch (e) { return []; }\n }\n }, function (results) { noopLastError(); cb(Array.isArray(results) ? results : []); });\n } catch (e) { cb([]); }\n }\n\n function swapInOpenFrames(jobs, previous) {\n var chrome = g.chrome;\n try {\n chrome.tabs.query({}, function (tabs) {\n noopLastError();\n for (var t = 0; tabs && t < tabs.length; t++) {\n (function (tab) {\n if (!tab || tab.id == null || (tab.url && !isInjectableUrl(tab.url))) return;\n bundlesByFrame(tab.id, function (frames) {\n for (var f = 0; f < frames.length; f++) {\n var frame = frames[f];\n if (!frame || !Array.isArray(frame.result) || !frame.result.length) continue;\n var target = {tabId: tab.id, frameIds: [typeof frame.frameId === \"number\" ? frame.frameId : 0]};\n for (var j = 0; j < jobs.length; j++) {\n if (!entryRuns(jobs[j].entry, frame.result)) continue;\n swapDeclaredSheet(target, jobs[j].file, previous[jobs[j].file], jobs[j].digest);\n }\n }\n });\n })(tabs[t]);\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // Answers false when only a reload delivers the edit: no API for the swap,\n // or an entry with no script to ask for it again on a later navigation.\n function refreshDeclaredSheets(sheets, cb) {\n var chrome = g.chrome;\n if (!Array.isArray(sheets) || !sheets.length || !canSwapDeclaredSheets()) return cb(false);\n var jobs = [];\n for (var i = 0; i < sheets.length; i++) {\n var sheet = sheets[i];\n if (!sheet || typeof sheet.file !== \"string\" || typeof sheet.digest !== \"string\") return cb(false);\n var entries = declaredEntriesNaming(sheet.file);\n for (var e = 0; e < entries.length; e++) {\n if (!stringList(entries[e].js).length) return cb(false);\n jobs.push({file: scriptFileName(sheet.file), digest: sheet.digest, entry: entries[e]});\n }\n }\n if (!jobs.length) return cb(false);\n withSheetOverrides(function (previous) {\n var next = {};\n for (var key in previous) next[key] = previous[key];\n for (var s = 0; s < sheets.length; s++) next[scriptFileName(sheets[s].file)] = sheets[s].digest;\n var rec = {};\n rec[SHEET_OVERRIDES_KEY] = next;\n sheetOverrides = next;\n // Recorded before any frame is asked: one that loads meanwhile either\n // reads the record and asks, or is already there to be asked.\n var apply = function () {\n noopLastError();\n try { registerSheetOverrides(next); } catch (e) {\n // Ignore\n }\n swapInOpenFrames(jobs, previous);\n };\n try { chrome.storage.local.set(rec, apply); } catch (e) { apply(); }\n cb(true);\n });\n }\n\n // A document loaded after a swap starts on the declared copy again, and\n // each bundle in it says so. Only the frame that asked is corrected.\n function correctSheetsFor(sender, signal) {\n if (!sender || !sender.tab || sender.tab.id == null || !canSwapDeclaredSheets()) return;\n if (!signal || typeof signal.file !== \"string\") return;\n var target = {tabId: sender.tab.id, frameIds: [typeof sender.frameId === \"number\" ? sender.frameId : 0]};\n var bundles = [scriptFileName(signal.file)];\n withSheetOverrides(function (overrides) {\n var entries = declaredEntries();\n for (var i = 0; i < entries.length; i++) {\n if (!entryRuns(entries[i], bundles)) continue;\n var css = stringList(entries[i].css);\n for (var c = 0; c < css.length; c++) {\n var file = declaredFileName(css[c]);\n if (typeof overrides[file] === \"string\") swapDeclaredSheet(target, file, null, overrides[file]);\n }\n }\n });\n }\n\n function handleDevReloadFrame(frame) {\n var kind = frame.reloadType || \"full\";\n var label = typeof frame.label === \"string\" ? frame.label : \"\";\n // The server always builds the label; the kind-derived fallback only\n // covers a malformed frame so the announcement stays truthful.\n var fallback = kind === \"content-scripts\" ? \"content_script\"\n : kind === \"service-worker\" ? \"service_worker\"\n : \"extension\";\n var announced = \"[Extension.js] Reloading \" + (label || fallback) + \"\u2026\";\n\n // Receipt for the broker: proves this SW's message pump processed the\n // frame (a socket write proves nothing). Sent FIRST, so a full reload\n // cannot tear the worker down between the receipt and the reload, and\n // the correlation id is echoed so it confirms only this broadcast.\n var ack = {type: \"reload-ack\", reloadType: kind, label: label};\n if (frame.reloadId) ack.reloadId = frame.reloadId;\n var changedScripts = frame.changedScriptFiles;\n var acked = false;\n var sendAck = function (replayedTabs) {\n if (acked) return;\n acked = true;\n sendHeldReloadAck = null;\n if (typeof replayedTabs === \"number\" && replayedTabs > 0) ack.replayedTabs = replayedTabs;\n send(ack);\n };\n var replays = kind === \"page\" && Array.isArray(changedScripts) && changedScripts.length > 0 &&\n typeof g.__extjsScriptsReplay === \"function\";\n if (replays) {\n if (sendHeldReloadAck) sendHeldReloadAck();\n sendHeldReloadAck = sendAck;\n try { setTimeout(function () { sendAck(); }, REPLAY_RECEIPT_WAIT_MS); } catch (e) { sendAck(); }\n } else sendAck();\n\n // The replay names each file at its address, so on Gecko the edited\n // files get their new one before it runs.\n if (Array.isArray(changedScripts) && changedScripts.length && canAddressRegisteredScripts()) {\n return moveScriptAddresses(changedScripts, function () { replayThenRefresh(frame, kind, announced, true, sendAck); });\n }\n replayThenRefresh(frame, kind, announced, false, sendAck);\n }\n\n function replayThenRefresh(frame, kind, announced, moved, replayed) {\n // A scripts/ bundle edit: re-run the executeScript calls that named it\n // on their recorded tabs, before any reload decision below.\n replayProgrammaticScripts(frame.changedScriptFiles, replayed);\n\n refreshRegisteredScripts(frame.changedScriptFiles, function (restarting) {\n if (restarting) return;\n // A restart brings every own tab back itself, so only the reloads\n // that keep the extension running reload a standalone page here.\n if (kind !== \"full\" && kind !== \"service-worker\") reloadStandalonePages(frame.standalonePages);\n // Notify-only: rspack-dev-server's livereload refreshes the open\n // surface; reloading the extension here would race it.\n if (kind === \"page\") return;\n\n announceReloadInTabs(announced);\n if (!Array.isArray(frame.refreshedStylesheets) || !frame.refreshedStylesheets.length) {\n return performDevReload(kind, function () {}, frame);\n }\n // A sheet-only edit: swap it where the browser can, reload otherwise.\n refreshDeclaredSheets(frame.refreshedStylesheets, function (swapped) {\n if (!swapped) restartExtension(150);\n });\n }, moved);\n }\n\n function sanitize(args) {\n var out = [];\n for (var i = 0; i < args.length; i++) {\n var p = args[i];\n try {\n if (typeof p === \"string\") out.push(p.length > 2048 ? p.slice(0, 2048) + \"...\" : p);\n else if (p instanceof Error) out.push(p.name + \": \" + p.message);\n else out.push(JSON.stringify(p));\n } catch (e) {\n out.push(String(p));\n }\n if (out.join(\" \").length > 8192) break;\n }\n return out;\n }\n\n // While an earlier context's parked lines replay, this context's own\n // frames wait in the queue so the agent reads them in the order written.\n var replaying = false;\n\n function flush() {\n while (queue.length && open && socket && !replaying) {\n var f = queue.shift();\n try { socket.send(JSON.stringify(f)); } catch (e) { break; }\n }\n }\n\n function send(frame) {\n if (open && socket && !replaying) {\n try { socket.send(JSON.stringify(frame)); return; } catch (e) {\n // Ignore\n }\n }\n if (queue.length < MAX_QUEUE) queue.push(frame);\n parkPendingError(frame);\n }\n\n // The queue above lives in this context's memory only, so a background\n // that throws while it evaluates dies with the error still queued: the\n // socket has not finished its handshake yet. Park log frames in extension\n // storage too, where the NEXT context to connect can ship them.\n // Best effort by construction: the write is asynchronous, so a teardown\n // can cut it before the browser records anything.\n var parkedErrors = [];\n // What an earlier context parked and this one has not shipped yet. Null\n // until read: the key is rewritten whole, so a write before the read\n // would erase the lines a background that just unloaded left behind.\n var inheritedParked = null;\n function storageLocalArea() {\n try {\n var ns = (g.chrome && g.chrome.storage) || (g.browser && g.browser.storage);\n var area = ns && ns.local;\n if (!area || typeof area.get !== \"function\" || typeof area.set !== \"function\") return null;\n return area;\n } catch (e) { return null; }\n }\n function trimParked(list) {\n while (list.length > MAX_PENDING_ERRORS) {\n var dropped = false;\n for (var i = 0; i < list.length; i++) {\n var ev = list[i] && list[i].event;\n if (!ev || ev.level !== \"error\") { list.splice(i, 1); dropped = true; break; }\n }\n if (!dropped) list.shift();\n }\n return list;\n }\n function parkedHere(id) {\n for (var i = 0; i < parkedErrors.length; i++) {\n var ev = parkedErrors[i] && parkedErrors[i].event;\n if (ev && ev.id === id) return true;\n }\n return false;\n }\n function replayable(frame) {\n var ev = frame && frame.event;\n if (!ev) return false;\n // A background that died before it read its session parked no run id.\n if (ev.runId !== INSTANCE_ID && !(SESSION_FROM_FILE && ev.runId === \"\")) return false;\n if (parkedHere(ev.id)) return false;\n return typeof ev.timestamp === \"number\" && Date.now() - ev.timestamp <= PENDING_ERROR_TTL;\n }\n // The whole list is rewritten on every park, so two lines in one turn\n // cannot lose each other to a read-modify-write, and the cap holds.\n function writeParked() {\n if (inheritedParked === null) return;\n var area = storageLocalArea();\n if (!area) return;\n var items = {};\n items[PENDING_ERRORS_KEY] = trimParked(inheritedParked.concat(parkedErrors));\n try { area.set(items, noopLastError); } catch (e) {\n // Ignore\n }\n }\n function parkPendingError(frame) {\n if (open) return;\n if (!frame || frame.type !== \"log\" || !frame.event) return;\n if (!storageLocalArea()) return;\n parkedErrors.push(frame);\n trimParked(parkedErrors);\n writeParked();\n }\n function readParked(area, onList) {\n var read = false;\n function onRead(res) {\n if (read) return;\n read = true;\n var list = res && res[PENDING_ERRORS_KEY];\n onList(Array.isArray(list) ? list : []);\n }\n try {\n var ret = area.get(PENDING_ERRORS_KEY, function (res) { noopLastError(); onRead(res); });\n if (ret && typeof ret.then === \"function\") ret.then(onRead, function () { onRead(null); });\n } catch (e) {\n onRead(null);\n }\n }\n function adoptInheritedParked() {\n var area = storageLocalArea();\n if (!area) { inheritedParked = []; return; }\n readParked(area, function (list) {\n if (inheritedParked !== null) return;\n inheritedParked = [];\n // Before the session is read nothing can be told apart yet, and the\n // lines are filtered again when they are shipped.\n for (var i = 0; i < list.length; i++) {\n if (!INSTANCE_ID || replayable(list[i])) inheritedParked.push(list[i]);\n }\n if (parkedErrors.length && !open) writeParked();\n });\n }\n // Ship what an earlier context parked and never got to send. Entries from\n // another build (a different instance id) or from an older run are dropped,\n // and the key is cleared on read so one failure is reported once. They\n // were written before anything this context queued, so they go first and\n // straight to the socket; done() then releases this context's own queue.\n var PENDING_READ_TIMEOUT = 1000;\n function flushPendingErrors(done) {\n var area = storageLocalArea();\n if (!area) { done(); return; }\n var finished = false;\n function finish() {\n if (finished) return;\n finished = true;\n done();\n }\n try {\n setTimeout(finish, PENDING_READ_TIMEOUT);\n } catch (e) {\n // Ignore\n }\n readParked(area, function (list) {\n if (finished) return;\n if (list.length) {\n try {\n if (typeof area.remove === \"function\") area.remove(PENDING_ERRORS_KEY, noopLastError);\n } catch (e) {\n // Ignore\n }\n }\n var earlier = [];\n for (var i = 0; i < list.length; i++) {\n if (replayable(list[i])) earlier.push(list[i]);\n }\n // Shipped or queued from here on, so nothing parked so far may be\n // written back for a later context to report twice.\n inheritedParked = [];\n parkedErrors = [];\n if (open && socket) {\n for (var j = 0; j < earlier.length; j++) {\n try { socket.send(JSON.stringify(earlier[j])); } catch (e) {\n // Ignore\n }\n }\n } else {\n queue = earlier.concat(queue).slice(0, MAX_QUEUE);\n }\n finish();\n });\n }\n\n // The baked PORT is a snapshot of an ephemeral port. After a dev-server\n // restart, the port file shipped in the unpacked extension names the\n // live one, and unpacked resources are read from disk on every fetch.\n // Lines logged before the session was read get its id once it is known.\n function adoptSession(id) {\n if (!SESSION_FROM_FILE || typeof id !== \"string\" || !id || id === INSTANCE_ID) return;\n INSTANCE_ID = id;\n var lists = [queue, parkedErrors];\n for (var l = 0; l < lists.length; l++) {\n for (var i = 0; i < lists[l].length; i++) {\n var ev = lists[l][i] && lists[l][i].event;\n if (ev && ev.runId === \"\") ev.runId = id;\n }\n }\n if (parkedErrors.length && !open) writeParked();\n }\n\n function refreshControlPort(done) {\n try {\n var runtime = (g.chrome && g.chrome.runtime) || (g.browser && g.browser.runtime);\n if (!runtime || typeof runtime.getURL !== \"function\" || typeof g.fetch !== \"function\") { done(); return; }\n g.fetch(runtime.getURL(\"extension-js-control.json\"), {cache: \"no-store\"})\n .then(function (res) { return res.json(); })\n .then(function (data) {\n var next = data && parseInt(data.port, 10);\n if (next && next > 0 && next < 65536 && next !== PORT) PORT = next;\n adoptSession(data && data.instanceId);\n done();\n })\n .catch(function () { done(); });\n } catch (e) { done(); }\n }\n\n function sessionKnown() {\n return !SESSION_FROM_FILE || (!!INSTANCE_ID && PORT > 0);\n }\n\n // The session file is there before the browser starts, so a read that\n // found none is retried like a server that is not listening yet.\n function dial() {\n if (sessionKnown()) connect();\n else schedule();\n }\n\n function schedule() {\n var delay = backoff;\n backoff = Math.min(backoff * 2, MAX_BACKOFF);\n connectFailures++;\n try {\n setTimeout(function () {\n // Two straight failures make the baked port suspect (a restarted\n // server dials out on a new port): re-resolve before re-dialing.\n if (connectFailures >= 2 || !sessionKnown()) refreshControlPort(dial);\n else dial();\n }, delay);\n } catch (e) {\n // Ignore\n }\n }\n\n function connect() {\n try {\n socket = new WS(\"ws://\" + HOST + \":\" + PORT + \"/extjs-control\");\n } catch (e) {\n schedule();\n return;\n }\n socket.onopen = function () {\n open = true;\n backoff = 250;\n connectFailures = 0;\n try {\n socket.send(JSON.stringify({type: \"hello\", v: 1, role: \"producer\", instanceId: INSTANCE_ID, acksReloads: true, build: g.__extjsDevBuild}));\n } catch (e) {\n // Ignore\n }\n // Hello goes first, then whatever a previous context parked before it\n // died, then this context's own queue.\n replaying = true;\n flushPendingErrors(function () {\n replaying = false;\n flush();\n });\n };\n socket.onmessage = function (ev) {\n var frame;\n try { frame = JSON.parse(typeof ev.data === \"string\" ? ev.data : \"\"); } catch (e) { return; }\n if (frame && frame.type === \"command\") {\n try { executeCommand(frame); } catch (e) { replyErr(frame.cmdId, \"ExecutorError\", e); }\n } else if (frame && frame.type === \"reload\") {\n // Dev-loop reload broadcast (see broker.broadcastReload).\n // Fire-and-forget: no result frame is expected.\n try { handleDevReloadFrame(frame); } catch (e) {\n // Ignore\n }\n } else if (frame && frame.type === \"ping\") {\n // Server keepalive: merely RECEIVING this resets the MV3 SW's ~30s\n // idle timer (Chrome 116+), keeping it reachable. Nothing to do.\n }\n };\n socket.onclose = function () {\n open = false;\n socket = null;\n schedule();\n };\n socket.onerror = function () {\n try { socket && socket.close(); } catch (e) {\n // Ignore\n }\n };\n }\n\n // Uncaught errors don't route through the patched console; the handlers\n // below forward them, using these signatures to skip already-logged throws.\n var recentErrorSigs = [];\n function errorSig(message, stack) {\n return String(message == null ? \"\" : message) + \"::\" + String(stack == null ? \"\" : stack).slice(0, 200);\n }\n function noteErrorSig(sig) {\n recentErrorSigs.push({sig: sig, t: Date.now()});\n if (recentErrorSigs.length > 50) recentErrorSigs.shift();\n }\n function errorSigSeenRecently(sig) {\n var now = Date.now();\n for (var i = recentErrorSigs.length - 1; i >= 0; i--) {\n if (now - recentErrorSigs[i].t > 3000) { recentErrorSigs.splice(i, 1); continue; }\n if (recentErrorSigs[i].sig === sig) return true;\n }\n return false;\n }\n\n LEVELS.forEach(function (level) {\n var orig = typeof consoleRef[level] === \"function\"\n ? consoleRef[level].bind(consoleRef)\n : function () {};\n consoleRef[level] = function () {\n try {\n if (level === \"error\") {\n for (var ai = 0; ai < arguments.length; ai++) {\n if (arguments[ai] instanceof Error) noteErrorSig(errorSig(arguments[ai].message, arguments[ai].stack));\n }\n }\n if (!isDevServerChatter(level, arguments)) send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: level,\n context: CONTEXT,\n messageParts: sanitize([].slice.call(arguments)),\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n return orig.apply(consoleRef, arguments);\n };\n });\n\n // Forward uncaught throws / unhandled rejections as level:\"error\", deduped\n // so a logged-then-rethrown Error emits once.\n function shipUncaughtError(message, stack, url) {\n try {\n var sig = errorSig(message, stack);\n if (errorSigSeenRecently(sig)) return;\n noteErrorSig(sig);\n send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: \"error\",\n context: CONTEXT,\n messageParts: sanitize([String(message) + (stack ? \"\\n\" + stack : \"\")]),\n url: url,\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n try {\n if (typeof g.addEventListener === \"function\") {\n g.addEventListener(\"error\", function (ev) {\n var err = ev && ev.error;\n var message = (err && err.message) || (ev && ev.message) || \"Uncaught error\";\n shipUncaughtError(message, err && err.stack, ev && ev.filename);\n });\n g.addEventListener(\"unhandledrejection\", function (ev) {\n var reason = ev && ev.reason;\n var message = (reason && reason.message) || (reason != null ? String(reason) : \"Unhandled rejection\");\n shipUncaughtError(\"Unhandled promise rejection: \" + message, reason && reason.stack, undefined);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // Other contexts relay console logs to this SW over a NAMED runtime.Port:\n // they can't open the WS under page CSP, and sendMessage can echo-loop.\n function shipRelayedLog(ev, sender) {\n try {\n send({\n type: \"log\",\n event: {\n v: 1,\n id: nowId(),\n timestamp: Date.now(),\n level: ev.level || \"log\",\n context: ev.context || \"content\",\n messageParts: Array.isArray(ev.messageParts) ? ev.messageParts : [],\n url: ev.url || (sender ? sender.url : undefined),\n tabId: sender && sender.tab ? sender.tab.id : undefined,\n frameId: sender ? sender.frameId : undefined,\n runId: INSTANCE_ID\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n try {\n var rtPort = g.chrome;\n if (rtPort && rtPort.runtime && rtPort.runtime.onConnect) {\n rtPort.runtime.onConnect.addListener(function (port) {\n if (!port || port.name !== \"__extjs-bridge-log__\") return;\n try {\n port.onMessage.addListener(function (msg) {\n if (!msg || !msg.__extjsBridgeLog) return;\n shipRelayedLog(msg.__extjsBridgeLog, port.sender);\n });\n } catch (e) {\n // Ignore\n }\n });\n }\n } catch (e) {\n // Ignore\n }\n // sendMessage path: how the devtools page relays, since its port would be\n // mistaken for the extension's own devtools connection. Also accepts any\n // surface still relaying the old way.\n try {\n var rt = g.chrome;\n if (rt && rt.runtime && rt.runtime.onMessage) {\n rt.runtime.onMessage.addListener(function (msg, sender) {\n if (!msg || !msg.__extjsBridgeLog) return;\n shipRelayedLog(msg.__extjsBridgeLog, sender);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // Dev registrations outlive runtime.reload(), while the new generation's\n // static manifest already names the current files: drop them first, or\n // every navigation from here on runs the content script twice.\n function unregisterDevContentScripts(onDone) {\n var chrome = g.chrome;\n var done = function () { if (onDone) { try { onDone(); } catch (e) {\n // Ignore\n } } };\n try {\n if (\n !chrome.scripting ||\n !chrome.scripting.getRegisteredContentScripts ||\n !chrome.scripting.unregisterContentScripts\n ) return done();\n chrome.scripting.getRegisteredContentScripts(function (existing) {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n var ids = [];\n if (existing) {\n for (var i = 0; i < existing.length; i++) {\n var id = existing[i] && existing[i].id;\n if (typeof id === \"string\" && id.indexOf(\"extjs-dev-cs-\") === 0) ids.push(id);\n }\n }\n if (!ids.length) return done();\n try {\n chrome.scripting.unregisterContentScripts({ids: ids}, function () { noopLastError(); done(); });\n } catch (e) { done(); }\n });\n } catch (e) { done(); }\n }\n\n // One heal per producer generation: onInstalled and the pre-reload storage\n // flag can both fire on the same boot, and each would inject once more.\n var bootHealDone = false;\n function healOpenTabsAtBoot() {\n if (bootHealDone) return;\n bootHealDone = true;\n // Firefox injects declared content scripts into open tabs on a reload\n // itself, so a heal there runs every script a second time.\n try { if (engineName() === \"firefox\") return; } catch (e) {\n // Ignore\n }\n setTimeout(function () {\n var dev = devContentScripts();\n if (dev && typeof dev.heal === \"function\") {\n try { dev.heal(); return; } catch (e) {\n // Ignore\n }\n }\n unregisterDevContentScripts(function () {\n try { reinjectContentScripts(undefined, {register: false, completeOnly: true}); } catch (e) {\n // Ignore\n }\n });\n }, 250);\n }\n\n // Chrome never injects manifest content scripts into already-open tabs, so\n // fire one reinject on onInstalled (which skips idle-stop SW wakes). Not\n // on the first install: the tabs the browser launched with load beside\n // the extension and Chrome injects them itself.\n try {\n var rtBoot = g.chrome;\n if (rtBoot && rtBoot.runtime && rtBoot.runtime.onInstalled) {\n rtBoot.runtime.onInstalled.addListener(function (details) {\n if (details && details.reason === \"install\") return;\n try { healOpenTabsAtBoot(); } catch (e) {\n // Ignore\n }\n });\n }\n } catch (e) {\n // Ignore\n }\n\n try { installScriptAddresses(); } catch (e) {\n // Ignore\n }\n\n try { watchBootRegistrations(); } catch (e) {\n // Ignore\n }\n\n try { restoreOverrideTabsAtBoot(); } catch (e) {\n // Ignore\n }\n\n try { restorePageTabsAtBoot(); } catch (e) {\n // Ignore\n }\n\n try { reloadRegisteredScriptTabsAtBoot(); } catch (e) {\n // Ignore\n }\n\n try { checkSheetSession(); } catch (e) {\n sheetSessionChecked = true;\n }\n\n try {\n if (engineName() === \"firefox\" && g.chrome && g.chrome.runtime && g.chrome.runtime.onMessage) {\n g.chrome.runtime.onMessage.addListener(function (msg, sender) {\n if (msg && msg[SHEET_SIGNAL]) correctSheetsFor(sender, msg[SHEET_SIGNAL]);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // Chromium 146 fires no onInstalled on runtime.reload() while 151 reports\n // an \"update\": the pre-reload storage flag (fresh only) covers the former.\n try {\n var stBoot = g.chrome;\n if (stBoot && stBoot.storage && stBoot.storage.local) {\n stBoot.storage.local.get(\"__extjsDevPendingReinject\", function (res) {\n noopLastError();\n var ts = res && res.__extjsDevPendingReinject;\n if (ts == null) return;\n try { stBoot.storage.local.remove(\"__extjsDevPendingReinject\", noopLastError); } catch (e) {\n // Ignore\n }\n if (typeof ts !== \"number\" || Date.now() - ts > 30000) return;\n healOpenTabsAtBoot();\n });\n }\n } catch (e) {\n // Ignore\n }\n\n adoptInheritedParked();\n if (SESSION_FROM_FILE) refreshControlPort(dial);\n else connect();\n } catch (e) {\n // Ignore\n }\n})();\n";
|
|
3
|
+
export declare const BRIDGE_RELAY_SOURCE = ";(function () {\n try {\n var g = (typeof globalThis === \"object\" && globalThis) ? globalThis : this;\n if (!g || g.__extjsBridgeRelayInstalled) return;\n\n var CONTEXT = \"__EXTJS_CONTEXT__\";\n var chrome = g.chrome;\n if (!chrome || !chrome.runtime) return;\n var canRelay = typeof chrome.runtime.connect === \"function\";\n\n g.__extjsBridgeRelayInstalled = true;\n\n var consoleRef = g.console || {};\n var LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\", \"trace\"];\n // Same filter as the producer: HMR chatter is not the page's output.\n function isDevServerChatter(level, args) {\n if (level === \"warn\" || level === \"error\") return false;\n var first = args && args[0];\n return typeof first === \"string\" && /^\\[(?:HMR|webpack-dev-server|rspack-dev-server)\\] /.test(first);\n }\n\n // Every engine's wording for \"this document's CSP forbids eval\". Gecko\n // says \"call to eval() blocked by CSP\", Chromium quotes the directive.\n function cspBlocksEval(message) {\n return /call to eval\\(\\)|blocked by (?:the )?CSP|Content Security Policy|unsafe-eval/i.test(String(message == null ? \"\" : message));\n }\n\n function sanitize(args) {\n var out = [];\n for (var i = 0; i < args.length; i++) {\n var p = args[i];\n try {\n if (typeof p === \"string\") out.push(p.length > 2048 ? p.slice(0, 2048) + \"...\" : p);\n else if (p instanceof Error) out.push(p.name + \": \" + p.message);\n else out.push(JSON.stringify(p));\n } catch (e) { out.push(String(p)); }\n if (out.join(\" \").length > 8192) break;\n }\n return out;\n }\n\n function here() { try { return g.location ? g.location.href : undefined; } catch (e) { return undefined; } }\n\n // The devtools page is the one surface whose port carries no sender.tab,\n // which is how a devtools extension recognizes its own devtools connection.\n // Ours would arrive first and be taken for it, so that surface sends\n // messages instead and the extension's port topology matches production.\n var relayOverPort = canRelay && CONTEXT !== \"devtools\";\n var canSend = typeof chrome.runtime.sendMessage === \"function\";\n\n function sendLog(payload) {\n if (!canSend) return;\n try {\n chrome.runtime.sendMessage({__extjsBridgeLog: payload}, function () {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n // Lazy named port to the SW producer: connecting wakes an idle SW, but\n // port frames never reach the extension's own onMessage listeners.\n var logPort = null;\n function getLogPort() {\n if (!relayOverPort) return null;\n if (logPort) return logPort;\n try {\n logPort = chrome.runtime.connect({name: \"__extjs-bridge-log__\"});\n logPort.onDisconnect.addListener(function () {\n try { void chrome.runtime.lastError; } catch (e) {\n // Ignore\n }\n logPort = null;\n });\n } catch (e) { logPort = null; }\n return logPort;\n }\n\n // Relay one log payload to the SW producer over the named port, redialing\n // once if the port went stale (SW restarted).\n function postLog(payload) {\n if (!relayOverPort) return sendLog(payload);\n\n var p = getLogPort();\n if (!p) return;\n try {\n p.postMessage({__extjsBridgeLog: payload});\n } catch (e) {\n logPort = null;\n var p2 = getLogPort();\n if (p2) { try { p2.postMessage({__extjsBridgeLog: payload}); } catch (e2) {\n // Ignore\n } }\n }\n }\n\n // Uncaught throws / unhandled rejections never route through the patched\n // console; forward them, deduped against console.error Error signatures.\n var recentErrorSigs = [];\n function errorSig(message, stack) {\n return String(message == null ? \"\" : message) + \"::\" + String(stack == null ? \"\" : stack).slice(0, 200);\n }\n function noteErrorSig(sig) {\n recentErrorSigs.push({sig: sig, t: Date.now()});\n if (recentErrorSigs.length > 50) recentErrorSigs.shift();\n }\n function errorSigSeenRecently(sig) {\n var now = Date.now();\n for (var i = recentErrorSigs.length - 1; i >= 0; i--) {\n if (now - recentErrorSigs[i].t > 3000) { recentErrorSigs.splice(i, 1); continue; }\n if (recentErrorSigs[i].sig === sig) return true;\n }\n return false;\n }\n\n LEVELS.forEach(function (level) {\n var orig = typeof consoleRef[level] === \"function\" ? consoleRef[level].bind(consoleRef) : function () {};\n consoleRef[level] = function () {\n try {\n if (level === \"error\") {\n for (var ai = 0; ai < arguments.length; ai++) {\n if (arguments[ai] instanceof Error) noteErrorSig(errorSig(arguments[ai].message, arguments[ai].stack));\n }\n }\n if (!isDevServerChatter(level, arguments)) postLog({level: level, context: CONTEXT, messageParts: sanitize([].slice.call(arguments)), url: here()});\n } catch (e) {\n // Ignore\n }\n return orig.apply(consoleRef, arguments);\n };\n });\n\n function shipUncaughtError(message, stack, url) {\n try {\n var sig = errorSig(message, stack);\n if (errorSigSeenRecently(sig)) return;\n noteErrorSig(sig);\n postLog({level: \"error\", context: CONTEXT, messageParts: sanitize([String(message) + (stack ? \"\\n\" + stack : \"\")]), url: url || here()});\n } catch (e) {\n // Ignore\n }\n }\n try {\n if (typeof g.addEventListener === \"function\") {\n g.addEventListener(\"error\", function (ev) {\n var err = ev && ev.error;\n var message = (err && err.message) || (ev && ev.message) || \"Uncaught error\";\n shipUncaughtError(message, err && err.stack, (ev && ev.filename) || undefined);\n });\n g.addEventListener(\"unhandledrejection\", function (ev) {\n var reason = ev && ev.reason;\n var message = (reason && reason.message) || (reason != null ? String(reason) : \"Unhandled rejection\");\n shipUncaughtError(\"Unhandled promise rejection: \" + message, reason && reason.stack, undefined);\n });\n }\n } catch (e) {\n // Ignore\n }\n\n // The SW executor can't reach another extension page's DOM or eval there,\n // so THIS surface answers inspect/eval requests for its own context.\n try {\n if (chrome.runtime && chrome.runtime.onMessage) {\n chrome.runtime.onMessage.addListener(function (msg, _sender, sendResponse) {\n if (!msg || !msg.__extjsEvalRequest) return;\n if (!msg.target || msg.target.context !== CONTEXT) return; // not for me\n // The reply crosses as JSON on Chromium and as a clone on Firefox.\n // Its JSON form, with each cycle nulled, reads the same on both.\n var jsonForm = function (v) {\n var stack = [];\n try {\n var json = JSON.stringify(v, function (_key, val) {\n while (stack.length && stack[stack.length - 1] !== this) stack.pop();\n if (typeof val === \"bigint\") val = {__type: \"bigint\", value: String(val)};\n if (val && typeof val === \"object\") {\n if (stack.indexOf(val) !== -1) return null;\n stack.push(val);\n }\n return val;\n });\n return json === undefined ? undefined : JSON.parse(json);\n } catch (e) { return v; }\n };\n var respondValue = function (value) {\n try { sendResponse({ok: true, value: jsonForm(value)}); }\n catch (eSend) { sendResponse({ok: true, value: String(value)}); }\n };\n var respondError = function (e) {\n var emsg = (e && e.message) || String(e);\n if (cspBlocksEval(emsg)) {\n sendResponse({ok: false, error: {name: \"Unsupported\", code: \"csp_blocks_eval\", message: \"eval of a string is blocked in the \" + CONTEXT + \" page by the extension's content_security_policy. Use extension inspect --context \" + CONTEXT + \" to read its DOM instead. Original: \" + emsg}});\n } else {\n sendResponse({ok: false, error: {name: (e && e.name) || \"EvalError\", message: emsg}});\n }\n };\n try {\n var value = (0, eval)(String((msg.args && msg.args.expression) || \"\"));\n // A promise is not structured-cloneable: Chrome throws on the reply\n // and Firefox drops it on the way out, which the background read as\n // \"surface is not open\" while the page kept running the expression.\n // Settle it first, the way the background eval already does.\n if (value && typeof value.then === \"function\") {\n value.then(respondValue, respondError);\n } else {\n respondValue(value);\n }\n } catch (e) {\n respondError(e);\n }\n return true; // responded, possibly later\n });\n }\n } catch (e) {\n // Ignore\n }\n\n try {\n if (chrome.runtime && chrome.runtime.onMessage) {\n chrome.runtime.onMessage.addListener(function (msg, _sender, sendResponse) {\n if (!msg || !msg.__extjsInspectRequest) return;\n if (!msg.target || msg.target.context !== CONTEXT) return; // not for me\n try {\n var args = msg.args || {};\n var wantHtml = !args.include || args.include.indexOf(\"html\") !== -1;\n var cap = args.maxBytes || 262144;\n function countShadow(root) {\n var n = 0, els = root.querySelectorAll(\"*\");\n for (var i = 0; i < els.length; i++) { if (els[i].shadowRoot) { n++; n += countShadow(els[i].shadowRoot); } }\n return n;\n }\n var doc = g.document;\n var roots = doc.querySelectorAll('#extension-root,[data-extension-root]');\n var snap = {\n context: CONTEXT,\n url: here(),\n title: doc.title,\n summary: {\n htmlLength: doc.documentElement.outerHTML.length,\n scriptCount: doc.querySelectorAll(\"script\").length,\n styleCount: doc.querySelectorAll(\"style,link[rel=stylesheet]\").length,\n extensionRootCount: roots.length,\n openShadowRoots: countShadow(doc),\n bodyChildCount: doc.body ? doc.body.children.length : 0\n }\n };\n if (wantHtml) {\n var html = doc.documentElement.outerHTML;\n if (cap > 0 && html.length > cap) { snap.html = html.slice(0, cap); snap.htmlTruncated = true; }\n else { snap.html = html; }\n }\n sendResponse({ok: true, value: snap});\n } catch (e) {\n sendResponse({ok: false, error: {name: \"InspectError\", message: String(e)}});\n }\n return true; // responded\n });\n }\n } catch (e) {\n // Ignore\n }\n } catch (e) {\n // Ignore\n }\n})();\n";
|
|
4
|
+
export declare function buildDeclaredSheetSignalSource(assetName: string): string;
|
|
4
5
|
export interface BuildRelayOptions {
|
|
5
6
|
context: string;
|
|
6
7
|
}
|
|
@@ -8,7 +9,9 @@ export declare function buildBridgeRelaySource(opts: BuildRelayOptions): string;
|
|
|
8
9
|
export interface BuildProducerOptions {
|
|
9
10
|
controlPort: number | null | undefined;
|
|
10
11
|
instanceId: string;
|
|
12
|
+
sessionFromFile?: boolean;
|
|
11
13
|
context?: string;
|
|
12
14
|
host?: string;
|
|
13
15
|
}
|
|
16
|
+
export declare const DEV_BOOT_REGISTERS_GLOBAL = "__extjsDevBootRegisters";
|
|
14
17
|
export declare function buildBridgeProducerSource(opts: BuildProducerOptions): string;
|