// ██████╗ ███████╗██╗ ██████╗ █████╗ ██████╗ // ██╔══██╗██╔════╝██║ ██╔═══██╗██╔══██╗██╔══██╗ // ██████╔╝█████╗ ██║ ██║ ██║███████║██║ ██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██╔══██║██║ ██║ // ██║ ██║███████╗███████╗╚██████╔╝██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ // MIT License (c) 2020–present Cezar Augusto & the Extension.js authors, presence implies inheritance import {createHash} from 'node:crypto' import * as fs from 'node:fs' import * as path from 'node:path' import {isChildBundleChunkName} from '../lib/child-bundle-chunk' import {debugLine, isDebug} from '../lib/messaging' import {parseAuthoredJson} from '../lib/parse-json-safe' import {hasPrivateFileName} from '../lib/public-private-files' import {getCanonicalContentScriptEntryName} from '../plugin-web-extension/feature-scripts/contracts' import {relativePublicRootsOf} from './build-reads' import * as reloadMessages from './messages' import {projectRelative} from './project-relative' import {DEV_CONTENT_SCRIPT_REGISTRY_ASSET} from './reload-lib/dev-content-scripts' export type ReloadType = 'full' | 'service-worker' | 'content-scripts' interface RefreshedStylesheet { file: string digest: string } export interface ReloadInstruction { // 'page' is notify-only: livereload refreshes the surface, but the signal // still travels the bridge so every announcing surface reflects it. type: ReloadType | 'page' changedContentScriptEntries?: string[] // The changed entries the dev manifest keeps static, so the extension // reloads for them and the announcement says why. staticContentScriptEntries?: string[] changedAssets?: string[] // Emitted scripts/ bundles a changed source lands in, so the SW replays // the programmatic executeScript calls that named them. changedScriptFiles?: string[] // Stylesheets the loaded manifest names that kept their name and changed // their bytes, for a browser that can swap them on open tabs in place. refreshedStylesheets?: RefreshedStylesheet[] // Changed pages the build ships as written. They carry no dev client, so // the producer reloads the open tabs that show them. standalonePages?: string[] // Human context label shared VERBATIM by every announcing surface, so they // can never disagree. e.g. "content_script (content/scripts.tsx)". label?: string } /** "context (fileA, fileB +2 more)", the one label every reload surface shows. */ export function formatReloadContextLabel( context: string, files: string[] ): string { if (!files.length) return context const shown = files.slice(0, 2).join(', ') const extra = files.length > 2 ? ` +${files.length - 2} more` : '' return `${context} (${shown}${extra})` } // The emitted manifest decides what the background is called: a gecko MV2 // build ships background.scripts, so its edit is not a service worker one. function backgroundContextFromOutput(outputPath?: string): string { if (!outputPath) return 'service_worker' try { const manifest = parseAuthoredJson( fs.readFileSync(path.join(outputPath, 'manifest.json'), 'utf8') ) as { background?: {service_worker?: unknown; scripts?: unknown; page?: unknown} } const background = manifest?.background if (background?.service_worker) return 'service_worker' if (Array.isArray(background?.scripts)) return 'background_script' if (background?.page) return 'background_page' } catch { // A manifest that does not parse names no background kind } return 'service_worker' } // Best-effort page-context name for a page-only edit. Only used for the // label, never for the reload decision. function pageContextFromSources(changedSources: string[]): string { const rules: Array<[RegExp, string]> = [ [/(^|\/)(sidebar|side[-_]?panel)(\.|\/)/i, 'sidebar page'], [/(^|\/)(action|popup)(\.|\/)/i, 'popup page'], [/(^|\/)options(\.|\/)/i, 'options page'], [/(^|\/)devtools(\.|\/)/i, 'devtools page'], [/(^|\/)(newtab|new[-_]?tab)(\.|\/)/i, 'new tab page'], [/(^|\/)(history|bookmarks)(\.|\/)/i, 'page'] ] for (const rel of changedSources) { for (const [re, name] of rules) { if (re.test(rel)) return name } } return 'page' } // Which dev-reload feature owns each source file, from the chunk graph. // Name-pattern heuristics are NOT trustworthy for this decision. export interface SourceFeatureIndex { swSources: Set /** Source → canonical content_scripts entry names whose chunks contain it. */ contentEntriesBySource: Map> pageSources: Set /** Source → emitted scripts/ bundle names whose chunks contain it. */ scriptFilesBySource?: Map> /** Project-relative public/ roots the copier ships at the dist root. */ publicRoots?: string[] } // The dist-relative path a changed source gets when a public/ root ships it, // or undefined when no root contains it. The root itself is not a file. export function publicOutputPath( rel: string, publicRoots: string[] | undefined ): string | undefined { for (const root of publicRoots || []) { const prefix = root.replace(/\/+$/, '') if (!prefix) continue if (rel.startsWith(`${prefix}/`)) return rel.slice(prefix.length + 1) } return undefined } // A public/ file the copier leaves out is never in the output, so its edit // changes nothing the browser runs. function isLeftOutPublicSource(rel: string, publicRoots?: string[]) { const output = publicOutputPath(rel, publicRoots) return output !== undefined && hasPrivateFileName(output) } // Loader-prefixed module identifier to project-relative resource path(s). // Classic-concat member files hide in the resource query; expand those too. function moduleResourcesFromIdentifier( identifier: string, contextDir: string ): string[] { const afterLoaders = identifier.slice(identifier.lastIndexOf('!') + 1) // rspack writes `||` for an asset or a stylesheet and // the bare request for JavaScript, so the request is the segment with a path. const segments = afterLoaders.split('|') const noLayer = segments.find((segment) => path.isAbsolute(segment.split('?')[0])) ?? segments[0] const queryIndex = noLayer.indexOf('?') const resourcePath = queryIndex === -1 ? noLayer : noLayer.slice(0, queryIndex) const query = queryIndex === -1 ? '' : noLayer.slice(queryIndex) const out: string[] = [] const push = (absolute: string) => { if (!absolute || !path.isAbsolute(absolute)) return out.push(projectRelative(contextDir, absolute)) } push(resourcePath) const concatMatch = query.match(/[?&]__extensionjs_classic_concat__=([^&]+)/) if (concatMatch) { try { const data = JSON.parse(decodeURIComponent(concatMatch[1])) for (const file of data?.js || []) push(String(file)) } catch { // malformed query, the first file alone still classifies the entry } } return out } type IndexChunk = { name?: string | null runtime?: Iterable | string files?: Iterable groupsIterable?: Iterable<{ origins?: Array<{module?: {identifier(): string} | null}> }> } function chunkModuleResources( compilation: import('@rspack/core').Compilation, chunk: IndexChunk, contextDir: string ): string[] { const out: string[] = [] let modules: Iterable<{identifier(): string}> = [] try { modules = compilation.chunkGraph.getChunkModulesIterable(chunk as never) } catch { // A chunk whose compilation is gone names no source } for (const module of modules) { try { out.push( ...moduleResourcesFromIdentifier( String(module.identifier()), contextDir ) ) } catch { // A module without an identifier names no source } } return out } // A nameless chunk belongs to the entries it runs under: a lazy chunk shares // its entry's runtime, a worker has its own and names the module that made it. function ownersOfNamelessChunk( chunk: IndexChunk, entryNames: Set, ownersBySource: Map>, contextDir: string ): Set { const owners = new Set() const runtime = chunk.runtime const runtimes = typeof runtime === 'string' ? [runtime] : runtime ? [...runtime] : [] for (const name of runtimes) { if (entryNames.has(name)) owners.add(name) } if (owners.size > 0) return owners for (const group of chunk.groupsIterable || []) { for (const origin of group.origins || []) { let identifier = '' try { identifier = origin.module ? String(origin.module.identifier()) : '' } catch { // A module without an identifier names no origin identifier = '' } for (const rel of moduleResourcesFromIdentifier(identifier, contextDir)) { for (const owner of ownersBySource.get(rel) || []) owners.add(owner) } } } return owners } function chunksByCompilation( compilation: import('@rspack/core').Compilation ): Map { const out = new Map() const seen = new Set() const walk = (each: import('@rspack/core').Compilation) => { if (!each || seen.has(each)) return seen.add(each) for (const chunk of each.chunks || []) { const isBundle = isChildBundleChunkName(String(chunk?.name || '')) if (each === compilation || isBundle) out.set(chunk as IndexChunk, each) } let children: import('@rspack/core').Compilation[] = [] try { children = [...(each.children || [])] } catch { // A compilation that cannot list its children has none to walk } for (const child of children) walk(child) } walk(compilation) return out } // Walk the finished compilation and record, for every bundled source file, // which reload feature its chunks belong to, nameless chunks by their owners. export function buildSourceFeatureIndex( compilation: import('@rspack/core').Compilation, contextDir: string ): SourceFeatureIndex { const scriptFilesBySource = new Map>() const index: SourceFeatureIndex = { swSources: new Set(), contentEntriesBySource: new Map(), pageSources: new Set(), scriptFilesBySource, publicRoots: relativePublicRootsOf(compilation.compiler, contextDir) } const compilationOf = chunksByCompilation(compilation) const chunks = [...compilationOf.keys()] const entryNames = new Set( chunks.map((chunk) => String(chunk?.name || '')).filter(Boolean) ) const ownersBySource = new Map>() const sourcesByChunk = new Map() const ownersByChunk = new Map>() const own = (chunk: IndexChunk, owners: Set) => { ownersByChunk.set(chunk, owners) for (const rel of sourcesByChunk.get(chunk) || []) { let known = ownersBySource.get(rel) if (!known) { known = new Set() ownersBySource.set(rel, known) } for (const owner of owners) known.add(owner) } } for (const chunk of chunks) { sourcesByChunk.set( chunk, chunkModuleResources( compilationOf.get(chunk) ?? compilation, chunk, contextDir ) ) const name = String(chunk?.name || '') if (name) own(chunk, new Set([name])) } // A worker made from another nameless chunk resolves once that one has // owners, so settle in a few passes. for (let pass = 0; pass < 3; pass++) { let settled = true for (const chunk of chunks) { if (ownersByChunk.has(chunk)) continue const owners = ownersOfNamelessChunk( chunk, entryNames, ownersBySource, contextDir ) if (owners.size === 0) continue own(chunk, owners) settled = false } if (settled) break } for (const chunk of chunks) { const owners = ownersByChunk.get(chunk) if (!owners) continue const name = String(chunk?.name || '') const scriptFiles = /^scripts\//.test(name) ? emittedScriptFiles(chunk, name) : [] for (const rel of sourcesByChunk.get(chunk) || []) { for (const owner of owners) { if (/^background\//.test(owner)) { index.swSources.add(rel) } else if (/^content_scripts\//.test(owner)) { let entries = index.contentEntriesBySource.get(rel) if (!entries) { entries = new Set() index.contentEntriesBySource.set(rel, entries) } entries.add(owner) } else { index.pageSources.add(rel) } } if (scriptFiles.length > 0) { let files = scriptFilesBySource.get(rel) if (!files) { files = new Set() scriptFilesBySource.set(rel, files) } for (const file of scriptFiles) files.add(file) } } } return index } // The scripts/ bundle names the SW's executeScript calls refer to; the // chunk's emitted files when known, else the unhashed [name].js form. function emittedScriptFiles( chunk: {files?: Iterable}, name: string ): string[] { const files = chunk?.files ? [...chunk.files] : [] const js = files.filter((file) => /\.js$/i.test(file)) return js.length > 0 ? js : [`${name}.js`] } function isHtmlSource(rel: string): boolean { return /\.html?$/i.test(rel) } // True when the emitted file is the source byte for byte. The html feature // rewrites every page it bundles, so such a page was only copied. function isShippedAsWritten( rel: string, contextDir: string | undefined, outputPath: string | undefined ): boolean { if (!contextDir || !outputPath) return false try { return fs .readFileSync(path.join(outputPath, rel)) .equals(fs.readFileSync(path.join(contextDir, rel))) } catch { // A file missing on either side is not a byte copy return false } } function changedScriptFilesFor( changedSources: string[], index: SourceFeatureIndex | null ): string[] { const out = new Set() for (const rel of changedSources) { const files = index?.scriptFilesBySource?.get(rel) if (!files) continue for (const file of files) out.add(file) } return [...out].sort() } // Pure reload classifier shared by the launched-browser and --no-browser // paths, so the same change always resolves to the same reload type. export function classifyReloadFromSources(opts: { changedSources: string[] forcedFull?: boolean getContentScriptCount: () => number getSourceFeatureIndex?: () => SourceFeatureIndex | null outputPath?: string // The project root, to tell a page the build copied from one it bundled. contextDir?: string }): ReloadInstruction | undefined { const { changedSources: allChangedSources, forcedFull, getContentScriptCount, getSourceFeatureIndex, outputPath, contextDir } = opts if (allChangedSources.length === 0) return undefined if (forcedFull) { return { type: 'full', changedAssets: allChangedSources, label: formatReloadContextLabel('extension', allChangedSources) } } let index: SourceFeatureIndex | null = null try { index = getSourceFeatureIndex ? getSourceFeatureIndex() : null } catch (error) { index = null if (isDebug()) debugLine(reloadMessages.debugSourceIndexUnreadable(error)) } const changedSources = allChangedSources.filter( (rel) => !isLeftOutPublicSource(rel, index?.publicRoots) ) if (changedSources.length === 0) return undefined // A scripts/ bundle edit rides along whichever reload wins, so the SW can // replay the injections that named it. const scriptFiles = changedScriptFilesFor(changedSources, index) const standalonePages: string[] = [] const withScripts = (instruction: ReloadInstruction): ReloadInstruction => ({ ...instruction, ...(scriptFiles.length > 0 ? {changedScriptFiles: scriptFiles} : {}), ...(standalonePages.length > 0 ? {standalonePages} : {}) }) const swChanged: string[] = [] const contentEntries = new Set() const contentChanged: string[] = [] const pageChanged: string[] = [] const unknown: string[] = [] for (const rel of changedSources) { // A source can live in MORE than one chunk family; record every // membership so the instruction can fan out to both reload paths. let known = false if (index?.swSources.has(rel)) { swChanged.push(rel) known = true } const entriesOfSource = index?.contentEntriesBySource.get(rel) if (entriesOfSource) { contentChanged.push(rel) for (const entry of entriesOfSource) { contentEntries.add(entry) } known = true } if (!known && index?.pageSources.has(rel)) { pageChanged.push(rel) known = true } // A page's markup is a file dependency of the html feature, never a chunk // module, so no index set names it; it still can only be a page edit. if (!known && isHtmlSource(rel)) { pageChanged.push(rel) known = true if (isShippedAsWritten(rel, contextDir, outputPath)) { standalonePages.push(rel) } } if (!known) { unknown.push(rel) } } // A changed emitted static asset (icon, web-accessible resource, DNR // ruleset…) needs a full extension reload to be re-read from disk. A file // under public/ ships at the dist root, so it is one whether or not the // manifest names it. const publicRoots = index?.publicRoots const publicAssetChanged = changedSources.some( (rel) => publicOutputPath(rel, publicRoots) !== undefined ) const staticAssetChanged = publicAssetChanged || (outputPath && unknown.some((rel) => { try { return fs.existsSync(path.join(outputPath, rel)) } catch { // A path the disk refuses is not a static asset return false } })) if (swChanged.length > 0) { // A shared module (SW chunk + content chunk) needs BOTH paths: the SW // restart carries the instruction plus the stale content-script entries. return withScripts({ type: 'service-worker', ...(contentEntries.size > 0 ? {changedContentScriptEntries: [...contentEntries].sort()} : {}), changedAssets: changedSources, label: formatReloadContextLabel( contentEntries.size > 0 ? `${backgroundContextFromOutput(outputPath)} + content_script` : backgroundContextFromOutput(outputPath), swChanged ) }) } if (staticAssetChanged) { return withScripts({ type: 'full', changedAssets: changedSources, label: formatReloadContextLabel('extension', changedSources) }) } if (contentChanged.length > 0) { return withScripts( withStaticEntries( { type: 'content-scripts', changedContentScriptEntries: [...contentEntries].sort(), changedAssets: changedSources, label: formatReloadContextLabel('content_script', contentChanged) }, outputPath ) ) } if (pageChanged.length > 0 && unknown.length === 0) { return withScripts({ type: 'page', changedAssets: changedSources, label: formatReloadContextLabel( pageContextFromSources(pageChanged), pageChanged ) }) } const isServiceWorkerSource = (rel: string) => /(^|\/)background(\.|\/)/i.test(rel) || /service[-_.]?worker/i.test(rel) if (unknown.some(isServiceWorkerSource)) { return withScripts({ type: 'service-worker', changedAssets: changedSources, label: formatReloadContextLabel( backgroundContextFromOutput(outputPath), changedSources ) }) } const contentScriptCount = getContentScriptCount() if (contentScriptCount > 0) { const entries: string[] = [] for (let i = 0; i < contentScriptCount; i++) { entries.push(getCanonicalContentScriptEntryName(i)) } return withScripts( withStaticEntries( { type: 'content-scripts', changedContentScriptEntries: entries, changedAssets: changedSources, label: formatReloadContextLabel('content_script', changedSources) }, outputPath ) ) } // Page-only edit: livereload owns the actual refresh; emit a notify-only // instruction so the reload announcement surfaces still fire. return withScripts({ type: 'page', changedAssets: changedSources, label: formatReloadContextLabel( pageContextFromSources(changedSources), changedSources ) }) } // The entries the emitted registry marks static: those the dev manifest // names as emitted, which only an extension reload can update. function readStaticContentScriptEntries(outputPath?: string): string[] { if (!outputPath) return [] try { const registry = parseAuthoredJson( fs.readFileSync( path.join(outputPath, DEV_CONTENT_SCRIPT_REGISTRY_ASSET), 'utf8' ) ) as {entries?: Array<{entry?: unknown; static?: unknown}>} return (registry?.entries || []) .filter( (entry) => entry?.static === true && typeof entry.entry === 'string' ) .map((entry) => entry.entry as string) } catch { // An unreadable registry names no static entry return [] } } function withStaticEntries( instruction: ReloadInstruction, outputPath?: string ): ReloadInstruction { const changed = new Set(instruction.changedContentScriptEntries || []) const statics = readStaticContentScriptEntries(outputPath).filter((entry) => changed.has(entry) ) return statics.length > 0 ? {...instruction, staticContentScriptEntries: statics} : instruction } // The bundles the emitted manifest's content_scripts name. Without the dev // stubs (Gecko, MV2) these are the hashed names, and the browser keeps the // list it read at load until the extension reloads. export function readContentScriptFiles( compilation: import('@rspack/core').Compilation ): string[] { try { const asset = compilation.getAsset('manifest.json') if (!asset?.source) return [] const manifest = JSON.parse(String(asset.source.source())) const groups = manifest?.content_scripts if (!Array.isArray(groups)) return [] return groups .flatMap((group: {js?: unknown; css?: unknown}) => [ ...(Array.isArray(group?.js) ? group.js : []), ...(Array.isArray(group?.css) ? group.css : []) ]) .filter((file: unknown): file is string => typeof file === 'string') } catch { // A manifest that does not parse declares no content script files return [] } } // A digest of each stylesheet the manifest's content_scripts name, as this // compile emits it: a bundle is renamed by its hash, a stylesheet is not. export function readContentScriptDigests( compilation: import('@rspack/core').Compilation, files: string[] ): Record { const digests: Record = {} for (const file of files) { if (!/\.css$/i.test(file)) continue try { const source = compilation.getAsset(file)?.source.source() if (source === undefined || source === null) continue digests[file] = createHash('sha256').update(source).digest('hex') } catch { // A file that cannot be read is not compared } } return digests } // The browser keeps a file the loaded manifest names under its address. Only // a reload reads it again, or with refreshInPlace a swap on the open tabs. export function reloadForRewrittenContentScripts( instruction: ReloadInstruction | undefined, loadedDigests: Record, emittedDigests: Record, options?: {refreshInPlace?: boolean} ): ReloadInstruction | undefined { if (instruction?.type === 'full' || instruction?.type === 'service-worker') { return instruction } // The worker reloads the extension and the tabs for a static entry itself. if (instruction?.staticContentScriptEntries?.length) return instruction const rewrittenFiles = Object.keys(emittedDigests).filter( (file) => loadedDigests[file] !== undefined && loadedDigests[file] !== emittedDigests[file] ) if (rewrittenFiles.length === 0) return instruction // A changed script renames its bundle, which is a full reload before this // point, so what is left here changed stylesheets and nothing else. if (options?.refreshInPlace) { const sheetAssets = instruction?.changedAssets?.length ? instruction.changedAssets : rewrittenFiles return { ...instruction, type: 'content-scripts', changedAssets: sheetAssets, refreshedStylesheets: rewrittenFiles.map((file) => ({ file, digest: emittedDigests[file] })), label: instruction?.label ?? formatReloadContextLabel('content_script', sheetAssets) } } const changedAssets = instruction?.changedAssets?.length ? instruction.changedAssets : ['manifest.json'] return { ...instruction, type: 'full', changedAssets, label: instruction?.type === 'content-scripts' && instruction.label ? instruction.label : formatReloadContextLabel('extension', changedAssets) } } // A compile that renames a bundle deletes the file the loaded manifest names, // and only an extension reload makes the browser read the new names. A // reinject alone left every page after it without the content script. export function reloadForRenamedContentScripts( instruction: ReloadInstruction | undefined, loadedFiles: string[], emittedFiles: string[] ): ReloadInstruction | undefined { if (instruction?.type === 'full' || instruction?.type === 'service-worker') { return instruction } const renamed = emittedFiles.length !== loadedFiles.length || emittedFiles.some((file, index) => file !== loadedFiles[index]) if (!renamed) return instruction const changedAssets = instruction?.changedAssets?.length ? instruction.changedAssets : ['manifest.json'] return { ...instruction, type: 'full', changedAssets, label: instruction?.type === 'content-scripts' && instruction.label ? instruction.label : formatReloadContextLabel('extension', changedAssets) } } // Every file the emitted manifest lets a web page load, patterns included. // MV3 groups them by the pages allowed to ask, MV2 lists them flat. export function readWebAccessibleResources( compilation: import('@rspack/core').Compilation ): string[] { try { const asset = compilation.getAsset('manifest.json') if (!asset?.source) return [] const manifest = JSON.parse(String(asset.source.source())) const groups = manifest?.web_accessible_resources if (!Array.isArray(groups)) return [] const out = new Set() for (const group of groups) { const resources = typeof group === 'string' ? [group] : Array.isArray(group?.resources) ? group.resources : [] for (const resource of resources) { if (typeof resource === 'string') out.add(resource) } } return [...out].sort() } catch { // A manifest that does not parse declares no accessible resources return [] } } // An imported asset is listed under a name that holds its content hash. The // browser keeps the list it loaded, so a page is refused the renamed file. export function reloadForNewWebResources( instruction: ReloadInstruction | undefined, loadedResources: string[], emittedResources: string[] ): ReloadInstruction | undefined { if (instruction?.type === 'full' || instruction?.type === 'service-worker') { return instruction } const loaded = new Set(loadedResources) if (emittedResources.every((resource) => loaded.has(resource))) { return instruction } const changedAssets = instruction?.changedAssets?.length ? instruction.changedAssets : ['manifest.json'] return { ...instruction, type: 'full', changedAssets, label: instruction?.type === 'content-scripts' && instruction.label ? instruction.label : formatReloadContextLabel('extension', changedAssets) } } // What the browser last read through the manifest: the build a caller notes // as loaded, then each reload of the extension or its worker after it. export function createLoadedContentScripts(options: {refreshInPlace: boolean}) { let files: string[] = [] let digests: Record = {} let resources: string[] = [] let handedOver: Record | undefined return { noteLoaded(compilation: import('@rspack/core').Compilation): void { files = readContentScriptFiles(compilation) digests = readContentScriptDigests(compilation, files) resources = readWebAccessibleResources(compilation) }, resolve( compilation: import('@rspack/core').Compilation, classified: ReloadInstruction | undefined ): ReloadInstruction | undefined { const emittedFiles = readContentScriptFiles(compilation) const emittedDigests = readContentScriptDigests(compilation, emittedFiles) const emittedResources = readWebAccessibleResources(compilation) const instruction = reloadForRewrittenContentScripts( reloadForNewWebResources( reloadForRenamedContentScripts(classified, files, emittedFiles), resources, emittedResources ), digests, emittedDigests, options ) if ( instruction?.type === 'full' || instruction?.type === 'service-worker' ) { files = emittedFiles digests = emittedDigests resources = emittedResources handedOver = undefined } else { handedOver = instruction?.refreshedStylesheets?.length ? emittedDigests : undefined } return instruction }, // The open tabs hold a swapped sheet only once a producer took it. An // edit nobody received is compared again, and named again, next compile. settle(delivered: boolean): void { if (delivered && handedOver) digests = handedOver handedOver = undefined } } } export function readContentScriptCount( compilation: import('@rspack/core').Compilation, outputPath: string ): number { try { const asset = compilation.getAsset('manifest.json') if (asset?.source) { const manifest = JSON.parse(String(asset.source.source())) const list = manifest?.content_scripts if (Array.isArray(list)) return list.length } } catch { // An unparsed manifest asset leaves the count to the file on disk } try { const manifestPath = path.join(outputPath, 'manifest.json') if (fs.existsSync(manifestPath)) { const manifest = parseAuthoredJson<{content_scripts?: unknown} | null>( fs.readFileSync(manifestPath, 'utf8') ) const list = manifest?.content_scripts if (Array.isArray(list)) return list.length } } catch { // An unparsed manifest on disk leaves the count unknown } return 0 }