import { composeSourcemap } from "../utils/compose-sourcemap"; import { isolateExternalImports } from "../utils/isolate-external-imports"; import type { ExportAllDeclaration, ExportNamedDeclaration, ImportAttribute, ImportDeclaration, ImportExpression, Literal, Node, ObjectExpression, Property, } from "estree"; import type { Plugin } from "vite"; import { walk } from "estree-walker"; /** * The Vite counterpart of the rollup `seismic` plugin, and its replacement in * `servicenowVitePlugins` -- it owns uxasset external resolution in both dev and * build, so the rollup plugin is no longer in the Vite list at all. * * import "@servicenow/now-button" assert { external: "uxasset" }; * * becomes * * import "/uxasset/externals/@servicenow/now-button/index.jsdbx"; * * marked external, so in dev the browser fetches it through the dev proxy * (`/uxasset/externals` is in `DEFAULT_PROXY_PATHS`) rather than Vite trying to * bundle it, and in build it is left as an external import. */ import { UXASSET_EXTERNAL_PREFIX } from "../utils/constants"; const EXTENSION_FILTER = /\.(js|jsx|ts|tsx|mjs|mts|cjs|cts)($|\?)/; /** * Prefixes Vite's `base` onto an absolute path. A relative base (`"./"`) * cannot be combined with an absolute path, so it is left alone. * Only exported for testability. */ export const withBase = (base: string, absolutePath: string): string => !base || base === "/" || base.startsWith(".") ? absolutePath : `${base.replace(/\/+$/, "")}${absolutePath}`; export type ServicenowSeismicPluginOptions = { filter?: (id: string) => boolean; }; /** * Vite plugin that rewrites `assert { external: "uxasset" }` / * `with { external: "uxasset" }` imports to the ServiceNow externals path * (`/uxasset/externals//index.jsdbx`). * * **Important:** packages that contain uxasset-external imports must be added * to {@link https://vite.dev/config/dep-optimization-options.html#optimizedeps-exclude optimizeDeps.exclude} * in the consuming project's Vite config. The dep optimizer runs its own * Rolldown pipeline that does **not** invoke environment plugin `transform` * hooks, so without the exclusion the import attributes are silently stripped * and the imports are left un-transformed in dev. */ export function servicenowSeismicPlugin( options: ServicenowSeismicPluginOptions = {}, ): Plugin { const { filter = (id: string) => EXTENSION_FILTER.test(id) } = options; let externalPrefix = UXASSET_EXTERNAL_PREFIX; // Separate plugin injected via the options hook so its generateBundle // runs after all minifiers (SWC, esbuild, Vite's internal esbuild). const isolateImportsPlugin: Plugin = { name: "seismic:isolate-imports", enforce: "post", async generateBundle(_options, bundle) { for (const chunk of Object.values(bundle)) { if (chunk.type !== "chunk") continue; const result = await isolateExternalImports(chunk.code, externalPrefix); if (result) { chunk.code = result.code; composeSourcemap(chunk, result.map, bundle); } } }, }; return { name: "seismic", enforce: "pre", options(config) { const plugins = config.plugins ?? []; (plugins as Plugin[]).unshift(isolateImportsPlugin); return { ...config, plugins }; }, configResolved(config) { /** * The externals prefix, including `base` in a build. In dev the dev server's * import-analysis prefixes `base` onto every root-relative url it rewrites, * so here it is only applied for builds. */ externalPrefix = config.command === "build" ? withBase(config.base, UXASSET_EXTERNAL_PREFIX) : UXASSET_EXTERNAL_PREFIX; }, transform(code, id) { if (!filter(id)) return null; // Cheap bail before paying for a parse. if (!code.includes("assert") && !code.includes("with")) return null; let parsed; try { parsed = this.parse(code); } catch { // Leave malformed input to Vite's own parse, which reports it properly. return null; } return rewriteExternals(code, parsed as Node, externalPrefix); }, resolveId(source: string) { if (!source.startsWith(externalPrefix)) { return null; } return { id: source, external: true, resolvedBy: "seismic" }; }, // In build, `external: true` prevents load from ever being called. // In dev, Vite still tries to load the module for its module graph; // return an empty module so it doesn't error -- the browser fetches the // real module through the dev proxy. load(id) { if (id.startsWith(UXASSET_EXTERNAL_PREFIX)) { return ""; } }, }; } /** * Rollup and Rolldown attach byte offsets to every AST node; `@types/estree` * models positions as the optional `range`/`loc` instead, so the offsets are * layered back on here. */ type Position = T & { start: number; end: number }; /** A static import or re-export -- the declarations that take an attribute clause. */ type AttributeDeclaration = | ImportDeclaration | ExportAllDeclaration | ExportNamedDeclaration; const isAttributeDeclaration = (node: Node): node is AttributeDeclaration => node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration"; const propertyKeyName = (property: Property): string | undefined => { const { key } = property; if (key.type === "Identifier") return key.name; if (key.type === "Literal" && typeof key.value === "string") return key.value; return undefined; }; /** The attribute marking an import as a uxasset external. */ const externalAttribute = { key: "external", value: "uxasset" } as const; /** The keys holding attributes on a dynamic `import(spec, { ... })`. */ const attributeSpecifiers: Set = new Set([ "with", "assert", ]); /** True when an `ImportAttribute` list carries `external: "uxasset"`. */ const importHasExternal = (attributes: readonly ImportAttribute[]): boolean => attributes.some((attribute) => { const { key, value } = attribute; let name: string | undefined; if (key.type === "Identifier") { name = key.name; } else if (key.type === "Literal" && typeof key.value === "string") { name = key.value; } return ( name === externalAttribute.key && value.value === externalAttribute.value ); }); /** The same check for a dynamic import's `{ with: { ... } }` options object. */ const dynamicImportHasExternal = (options: ObjectExpression): boolean => options.properties.some((property) => { if (property.type !== "Property") return false; if (!attributeSpecifiers.has(propertyKeyName(property))) { return false; } const value = property.value; if (value.type !== "ObjectExpression") return false; return value.properties.some((attribute) => { if (attribute.type !== "Property") return false; if (propertyKeyName(attribute) !== externalAttribute.key) return false; return ( attribute.value.type === "Literal" && attribute.value.value === externalAttribute.value ); }); }); /** * Walks `program`, rewriting every uxasset-external import/re-export so the * specifier points at its externals path and the attribute clause is removed. * * Returns `{ code, map }` when at least one node was rewritten, `null` otherwise. */ function rewriteExternals( code: string, program: Node, externalPrefix: string, ): { code: string; map: null } | null { /** Edits collected during the walk, applied back-to-front afterwards. */ const edits: { start: number; end: number; replacement: string }[] = []; /** * Repoints a specifier at its externals path and removes the attributes * that follow it, up to `removeThrough`. */ const externalize = (source: Position, removeThrough: number) => { if (typeof source.value !== "string") return; edits.push({ start: source.start, end: removeThrough, replacement: JSON.stringify( `${externalPrefix}${source.value}/index.jsdbx`, ), }); }; walk(program, { enter(n) { const node = n as Node; if (isAttributeDeclaration(node)) { const attributes = node.attributes as Position[]; const source = node.source as Position | null; if (source && attributes.length && importHasExternal(attributes)) { // The clause-closing `}` sits between the last attribute and the // declaration end. Search backward from the declaration end so we // skip any `}` that might appear inside a comment between the two. const lastEnd = attributes[attributes.length - 1].end; const declEnd = (node as Position).end; let clauseEnd = declEnd - 1; while (clauseEnd >= lastEnd && code[clauseEnd] !== "}") clauseEnd--; if (clauseEnd >= lastEnd) { externalize(source, clauseEnd + 1); } } } else if (node.type === "ImportExpression") { const expression = node as Position; const optionsArgument = expression.options as | Position | undefined; const { source } = expression; // A non-literal specifier -- `import(name, ...)` -- cannot be rewritten // statically, and is left for the runtime, as in a rollup build. if ( optionsArgument?.type === "ObjectExpression" && source.type === "Literal" && dynamicImportHasExternal(optionsArgument) ) { // Drop the whole options argument, comma included. externalize(source as Position, optionsArgument.end); } } }, }); if (!edits.length) return null; // Apply edits back-to-front so earlier offsets stay valid. edits.sort((a, b) => b.start - a.start); let result = code; for (const { start, end, replacement } of edits) { result = result.slice(0, start) + replacement + result.slice(end); } return { code: result, map: null }; }