All files / src/rollup index.ts

94.76% Statements 163/172
82.89% Branches 63/76
90% Functions 27/30
95.06% Lines 154/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 4611x                             1x 1x 1x     1x 1x 1x 1x                                               1x 28x       1x 28x 28x 28x     1x 42x 40x 40x 40x       40x   2x           1x       42x 42x                     1x 16x 16x 16x 32x     42x 30x 30x     16x         17x 16x 1x 1x   16x                 1x 9x             1x 9x 9x 9x 180x                       1x                                           1x       40x   40x     18x 18x     17x 17x     19x 1x 1x 18x     2x 2x     17x 17x         13x 13x 12x 12x         12x     5x         8x   8x 12x 3x 9x   9x   9x 9x 9x 9x   9x 9x 9x 9x     9x 9x 1x 1x 1x 1x         8x 8x 12x 11x 14x                       1x 26x 26x 27x   26x                           1x 40x 40x 40x                             1x           18x       16x 16x 32x 32x 2x 30x     32x 32x                     32x 32x   16x     18x         2x           16x 1x       15x     2x 1x       1x         1x 29x 1x             28x                 28x 26x 26x 26x 44x 18x   26x           26x 8x 8x 8x   8x     8x                         18x               2x     1x 5x 1x   4x 1x       3x         3x       3x           1x 29x     1x 5x     1x  
import {
  rollup as bareRollup,
  watch as rollupWatch,
  RollupBuild,
  InputOptions,
  OutputOptions,
  InputPluginOption,
  RollupWatchOptions,
  RollupWatcher,
  RollupOutput,
  OutputChunk,
  OutputAsset,
  Plugin,
} from "rollup";
import { FileSystem } from "@servicenow/sdk-build-core";
import path from "path";
import fluentToRollupfs from "./fluent-to-rollupfs";
import { RollupFsAdapter } from "./rollup-fs-adapter";
import type { IsomorphicRollupFs } from "../fs-iface";
import type { RollupFsModule } from "rollup";
import webFsLoader from "../web-fs-loader";
import { isBrowserOrWorkerEnvironment } from "../utils/browser";
import { glob } from "../glob";
import { subtle } from "../crypto";
 
interface RollupOptions extends Omit<InputOptions, "fs"> {
  fs: FileSystem;
  // This is included for compatibility with config files but ignored by rollup.rollup
  output?: OutputOptions | OutputOptions[];
  /** Minimum module size in bytes above which a node_modules dependency is
   *  extracted into its own vendor chunk. Defaults to 200 000 (≈200 KB). */
  vendorChunkThreshold?: number;
}
 
interface WatchOptions extends Omit<RollupWatchOptions, "fs"> {
  fs: FileSystem;
}
 
declare global {
  var __rollupFs: IsomorphicRollupFs | undefined;
}
 
/**
 * Checks whether the input looks like a glob pattern targeting HTML or XML
 * files (e.g. "src/client/**\/*.html"). When true, the wrapper resolves the
 * glob and runs one rollup build per file to prevent code-splitting.
 */
const isHtmlGlobInput = (input: unknown): input is string =>
  typeof input === "string" &&
  (input.includes("*") || input.includes("?")) &&
  (input.endsWith(".html") || input.endsWith(".xml"));
 
const setupRollupFs = (fs: FileSystem): RollupFsModule => {
  const rollupFs = fluentToRollupfs(fs);
  globalThis.__rollupFs = new RollupFsAdapter(fs);
  return rollupFs;
};
 
const injectBrowserPlugins = (options: RollupOptions): RollupOptions => {
  if (isBrowserOrWorkerEnvironment()) {
    const existing: InputPluginOption[] = [];
    if (Array.isArray(options.plugins)) {
      existing.push(...options.plugins);
    } else Eif (options.plugins) {
      existing.push(options.plugins);
    }
    return { ...options, plugins: [...existing, webFsLoader()] };
  }
  return options;
};
 
/**
 * Build a single rollup bundle (one or more entries in a single invocation).
 */
const invokeSingleRollup = (
  options: RollupOptions,
  rollupFs: RollupFsModule,
): Promise<RollupBuild> => {
  const opts = injectBrowserPlugins(options);
  return bareRollup({
    ...opts,
    fs: rollupFs,
  });
};
 
/**
 * Merges multiple RollupOutput arrays into one, concatenating all chunks
 * and assets. The first entry of the first output is used as the leading
 * OutputChunk (required by the RollupOutput tuple type).
 */
const mergeOutputs = (outputs: RollupOutput[]): RollupOutput => {
  const seen = new Set<string>();
  const allItems: (OutputChunk | OutputAsset)[] = [];
  for (const o of outputs) {
    for (const item of o.output) {
      // Hash-named vendor chunks are identical across page builds;
      // keep only the first occurrence of each fileName.
      if (seen.has(item.fileName)) continue;
      seen.add(item.fileName);
      allItems.push(item);
    }
  }
  Iif (allItems.length === 0) {
    throw new Error("No output was generated from any rollup build.");
  }
  // RollupOutput requires the first element to be an OutputChunk.
  // Ensure a chunk leads the array even if the first output item is an asset.
  const firstChunkIdx = allItems.findIndex((o) => o.type === "chunk");
  if (firstChunkIdx > 0) {
    const [chunk] = allItems.splice(firstChunkIdx, 1);
    allItems.unshift(chunk);
  }
  return {
    output: allItems as [OutputChunk, ...(OutputChunk | OutputAsset)[]],
  };
};
 
/**
 * Strips the trailing sourceMappingURL comment from chunk code so that two
 * chunks with identical logic but different sourcemap filenames compare equal.
 */
const stripSourcemapComment = (code: string): string =>
  code.replace(/\/\/[#@]\s*sourceMappingURL=[^\n]*\s*$/, "");
 
/**
 * Computes a content hash using SHA-1 via the Web Crypto API. Produces an
 * 8-character hex digest suitable for content-based naming of vendor chunks.
 * Consistent with the hashing approach used by the URL plugin.
 */
const contentHash = async (str: string): Promise<string> => {
  const bytes = new TextEncoder().encode(str);
  const digest = await subtle.digest("SHA-1", bytes);
  return Array.from(new Uint8Array(digest))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")
    .substring(0, 8);
};
 
/**
 * Default minimum module size (in bytes of transformed source) above which the
 * module is extracted into its own chunk rather than inlined into the entry
 * bundle. 200 KB raw ≈ 50–60 KB gzipped — the point where a separate HTTP
 * request costs less than re-downloading the bytes in every entry.
 * Configurable via `vendorChunkThreshold` in RollupOptions.
 */
const DEFAULT_VENDOR_CHUNK_THRESHOLD = 200_000;
 
/**
 * Rollup plugin that extracts large node_modules into their own named chunks.
 *
 * In per-entry isolated builds every static dependency is inlined into the
 * entry chunk. When multiple pages share a large dependency (e.g. React),
 * each page duplicates it. This plugin records module sizes during
 * `transform` and uses `manualChunks` to extract node_modules that exceed
 * LARGE_MODULE_THRESHOLD into deterministic named chunks that the browser
 * can cache across page navigations.
 *
 * Only node_modules are extracted — user source code stays inlined per
 * entry to preserve build isolation. Extracting user code would create
 * shared chunks that re-introduce version skew when only one page is
 * rebuilt.
 *
 * Vendor chunks are named `vendor-<pkg>--<contentHash>` where the hash is
 * derived from the chunk's code. Identical vendor code across page builds
 * produces the same filename, so `mergeOutputs` deduplicates by fileName
 * and the filesystem naturally consolidates them during `write`.
 */
const extractLargeModules = (
  entryTag: string,
  threshold = DEFAULT_VENDOR_CHUNK_THRESHOLD,
): Plugin => {
  const moduleSizes = new Map<string, number>();
 
  return {
    name: "extract-large-modules",
    transform(code, id) {
      moduleSizes.set(id, code.length);
      return null;
    },
    outputOptions(options) {
      const existing = options.manualChunks;
      return {
        ...options,
        manualChunks(id, api) {
          if (typeof existing === "function") {
            const result = existing.call(this, id, api);
            Eif (result) return result;
          } else if (typeof existing === "object" && existing !== null) {
            // Rollup accepts manualChunks as Record<string, string[]>.
            // Check if the module belongs to any user-defined chunk.
            for (const [chunkName, moduleIds] of Object.entries(existing)) {
              if (moduleIds.includes(id)) return chunkName;
            }
          }
          const size = moduleSizes.get(id);
          if (size && size > threshold) {
            // Only extract node_modules — user source code stays inlined
            // per entry to preserve build isolation. Extracting user code
            // would re-introduce shared-chunk version skew: modifying
            // the file and rebuilding one page silently affects others.
            const nmIdx = id.lastIndexOf("node_modules/");
            if (nmIdx !== -1) {
              const afterNm = id.slice(nmIdx + "node_modules/".length);
              const pkgName = afterNm.startsWith("@")
                ? afterNm.split("/").slice(0, 2).join("-")
                : afterNm.split("/")[0];
              // Use entryTag as a temporary unique name; generateBundle
              // renames to a content hash once the code is known.
              return `vendor-${pkgName}--${entryTag}`;
            }
          }
          return undefined;
        },
      };
    },
    async generateBundle(_options, bundle) {
      const renames = new Map<string, string>();
 
      for (const [fileName, chunk] of Object.entries(bundle)) {
        if (chunk.type !== "chunk" || !chunk.name?.startsWith("vendor-"))
          continue;
        const hash = await contentHash(stripSourcemapComment(chunk.code));
        // vendor-react-dom--entryTag → vendor-react-dom--<hash>
        const dashDashIdx = chunk.name.lastIndexOf("--");
        const vendorPrefix =
          dashDashIdx !== -1 ? chunk.name.slice(0, dashDashIdx) : chunk.name;
        const ext = path.extname(fileName);
        const newFileName = `${vendorPrefix}--${hash}${ext}`;
        Iif (newFileName === fileName) continue;
 
        renames.set(fileName, newFileName);
        chunk.fileName = newFileName;
        bundle[newFileName] = chunk;
        delete bundle[fileName];
 
        // Rename accompanying sourcemap
        const mapKey = fileName + ".map";
        if (bundle[mapKey]) {
          const newMapKey = newFileName + ".map";
          bundle[mapKey].fileName = newMapKey;
          bundle[newMapKey] = bundle[mapKey];
          delete bundle[mapKey];
        }
      }
 
      // Rewrite import references in entry / other chunks
      Eif (renames.size > 0) {
        for (const chunk of Object.values(bundle)) {
          if (chunk.type !== "chunk") continue;
          for (const [oldName, newName] of renames) {
            chunk.code = chunk.code.replaceAll(oldName, newName);
          }
        }
      }
    },
  };
};
 
/**
 * Extracts the non-glob base directory from a glob pattern.
 * e.g. "/project/src/client/**\/*.html" → "/project/src/client"
 */
const globBase = (pattern: string): string => {
  let dir = pattern;
  while (path.basename(dir).includes("*") || path.basename(dir).includes("?")) {
    dir = path.dirname(dir);
  }
  return dir;
};
 
/**
 * Derives a deterministic entry tag from an HTML file path by kebab-casing
 * the full relative path (without extension) from `baseDir`. Used as a
 * temporary discriminator for vendor chunk names before content-hash renaming.
 *
 * Examples:
 *   deriveEntryTag("/p/src/client/index.html", "/p/src/client")                → "index"
 *   deriveEntryTag("/p/src/client/llama-page/index.html", "/p/src/client")     → "llama-page-index"
 *   deriveEntryTag("/p/src/client/admin/settings.html", "/p/src/client")       → "admin-settings"
 *   deriveEntryTag("/p/src/client/admin/deep/page.html", "/p/src/client")      → "admin-deep-page"
 */
const deriveEntryTag = (filePath: string, baseDir: string): string => {
  const relative = path.relative(baseDir, filePath).replace(/\\/g, "/");
  const withoutExt = relative.replace(/\.[^.]+$/, "");
  return withoutExt.replace(/\//g, "-");
};
 
/**
 * Creates a deferred composite RollupBuild from a list of input files.
 * Unlike building upfront, this defers `bareRollup()` to write/generate
 * time so that each file gets a fully isolated build cycle (options →
 * buildStart → transform → generateBundle) with no shared plugin state.
 *
 * This is necessary because rollup plugins are stateful objects — the
 * options hook runs during bareRollup() and mutates plugin state (e.g.
 * uiPage's htmlRegistry). Building all files upfront and writing later
 * causes all options hooks to run before any generateBundle, breaking
 * per-entry isolation.
 */
const createDeferredCompositeRollupBuild = (
  files: string[],
  options: RollupOptions,
  rollupFs: RollupFsModule,
  baseDir: string,
): RollupBuild => {
  const buildEach = async (
    outputOptions: OutputOptions,
    method: "generate" | "write",
  ): Promise<RollupOutput> => {
    const outputs: RollupOutput[] = [];
    for (const file of files) {
      const existingPlugins: InputPluginOption[] = [];
      if (Array.isArray(options.plugins)) {
        existingPlugins.push(...options.plugins);
      } else Iif (options.plugins) {
        existingPlugins.push(options.plugins);
      }
      const entryTag = deriveEntryTag(file, baseDir);
      const build = await invokeSingleRollup(
        {
          ...options,
          input: file,
          plugins: [
            extractLargeModules(entryTag, options.vendorChunkThreshold),
            ...existingPlugins,
          ],
        },
        rollupFs,
      );
      outputs.push(await build[method](outputOptions));
      await build.close();
    }
    return mergeOutputs(outputs);
  };
 
  return {
    cache: undefined,
    closed: false,
    watchFiles: [],
    async close() {
      this.closed = true;
    },
    async [Symbol.asyncDispose]() {
      await this.close();
    },
    async generate(outputOptions: OutputOptions): Promise<RollupOutput> {
      if (this.closed) {
        throw new Error(
          "Bundle is already closed, no more calls to 'generate' are allowed.",
        );
      }
      return buildEach(outputOptions, "generate");
    },
    async write(outputOptions: OutputOptions): Promise<RollupOutput> {
      if (this.closed) {
        throw new Error(
          "Bundle is already closed, no more calls to 'write' are allowed.",
        );
      }
      return buildEach(outputOptions, "write");
    },
  };
};
 
const invokeRollup = async (options: RollupOptions): Promise<RollupBuild> => {
  if (!options.fs) {
    return Promise.reject(
      new Error(
        "A filesystem must be provided, but none was found on options.fs",
      ),
    );
  }
 
  const rollupFs = setupRollupFs(options.fs);
 
  // When input is a glob matching HTML/XML files, build each file as a
  // separate rollup invocation. This prevents code-splitting: each entry
  // gets a fully self-contained bundle with all dependencies inlined.
  //
  // UI Pages load independently on separate .do endpoints — shared chunks
  // provide no runtime benefit and can break during partial rebuilds when
  // only some pages are reconfigured.
  if (isHtmlGlobInput(options.input)) {
    const baseDir = globBase(options.input);
    const files = await glob(options.input, { fs: options.fs });
    const sortedFiles = files
      .map((f) => String(f))
      .sort((a, b) => a.localeCompare(b, "en"));
 
    Iif (sortedFiles.length === 0) {
      // No files matched — fall through to single build so rollup can
      // report its own error or plugins can handle the empty input.
      return invokeSingleRollup(options, rollupFs);
    }
 
    if (sortedFiles.length === 1) {
      const entryTag = deriveEntryTag(sortedFiles[0], baseDir);
      const existingPlugins: InputPluginOption[] = [];
      Iif (Array.isArray(options.plugins)) {
        existingPlugins.push(...options.plugins);
      } else Iif (options.plugins) {
        existingPlugins.push(options.plugins);
      }
      return invokeSingleRollup(
        {
          ...options,
          input: sortedFiles[0],
          plugins: [
            extractLargeModules(entryTag, options.vendorChunkThreshold),
            ...existingPlugins,
          ],
        },
        rollupFs,
      );
    }
 
    return createDeferredCompositeRollupBuild(
      sortedFiles,
      options,
      rollupFs,
      baseDir,
    );
  }
 
  return invokeSingleRollup(options, rollupFs);
};
 
const invokeWatch = (options: WatchOptions): RollupWatcher => {
  if (isBrowserOrWorkerEnvironment()) {
    throw new Error("watch() is not supported in browser/worker environments");
  }
  if (!options.fs) {
    throw new Error(
      "A filesystem must be provided, but none was found on options.fs",
    );
  }
  const rollupFs = fluentToRollupfs(options.fs);
  /**
   * Creates a global that's accessible to all other plugins that we know of
   * that can use our passed in filesystem.
   */
  globalThis.__rollupFs = new RollupFsAdapter(options.fs);
 
  // webFsLoader is intentionally not injected here: watch is a dev/Node-only
  // feature and is never invoked in browser or worker environments.
  return rollupWatch({
    ...options,
    fs: rollupFs,
  });
};
 
export const rollup = (options: RollupOptions): Promise<RollupBuild> => {
  return invokeRollup(options);
};
 
export const watch = (options: WatchOptions): RollupWatcher => {
  return invokeWatch(options);
};
 
export { defineConfig, VERSION } from "rollup";