Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions docs/app/docs-infra/hooks/use-demo/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,20 +376,19 @@ type ExportConfig = {
globals?: VariantExtraFiles,
) => { variant?: VariantCode; globals?: VariantExtraFiles } | undefined;
/**
* Version overrides for core packages (react, react-dom,
* @types /react,
* @types /react-dom)
* Version overrides for exported packages, including React and its type packages.
* @example
* versions: {
* '@types/react': '^19',
* '@types/react-dom': '^19',
* react: '^19',
* 'react-dom': '^19',
* '@types/react': '^19',
* '@types/react-dom': '^19',
* react: '^19',
* 'react-dom': '^19',
* }
*/
versions?: Record<string, string>;
/**
* Custom dependency resolution function
* Resolves imported packages and their peers, including packages pinned in `versions`.
* `importedModules` contains the complete imports belonging to each package.
* @example
* resolveDependencies: (packageName, envVars) => {
* if (packageName === '@mui/material') {
Expand All @@ -401,6 +400,7 @@ type ExportConfig = {
resolveDependencies?: (
packageName: string,
envVars?: Record<string, string>,
importedModules?: string[],
) => Record<string, string>;
};
```
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
import { performance } from 'node:perf_hooks';
import { fileURLToPath } from 'node:url';
import { afterEach, expect, it } from 'vitest';
import { webpack as nextWebpack } from 'next/dist/compiled/webpack/webpack';
import type webpackCompiler from 'webpack';
import type { Configuration, NormalModule, Stats, Watching } from 'webpack';

const webpack: typeof webpackCompiler = nextWebpack;
const require = createRequire(import.meta.url);
const directories: string[] = [];
const DEFERRED_QUERY = '?mui-deferred-precompute';
const WATCH_TIMEOUT_MS = 30_000;
const WATCH_AGGREGATE_MS = 20;
const VARIANT_MEASURE =
'| Load Precomputed Code Highlighter | Complete Variants Loading - index.ts';

afterEach(async () => {
await Promise.all(
directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
);
});

/** Runs the source loader in webpack rather than substituting its context. */
async function createFixture() {
const directory = await realpath(await mkdtemp(path.join(tmpdir(), 'docs-precompute-')));
directories.push(directory);
const loader = path.join(directory, 'loader.mjs');
const source = fileURLToPath(new URL('./loadPrecomputedCodeHighlighter.ts', import.meta.url));
await writeFile(
loader,
`import { createJiti } from ${JSON.stringify(require.resolve('jiti'))};\nconst jiti = createJiti(import.meta.url);\nconst { loadPrecomputedCodeHighlighter } = await jiti.import(${JSON.stringify(source)});\nexport default loadPrecomputedCodeHighlighter;\n`,
);
await writeFile(path.join(directory, 'helper.js'), 'export const label = "Before";\n');
await writeFile(
path.join(directory, 'Demo.js'),
'import { label } from "./helper";\nexport default function Demo() { return label; }\n',
);
await writeFile(
path.join(directory, 'factory.js'),
'export function createDemo(url, demo, options) { return options; }\n',
);
await writeFile(
path.join(directory, 'index.ts'),
'import { createDemo } from "./factory";\nimport Demo from "./Demo";\nexport default createDemo(import.meta.url, Demo, {});\n',
);
return { directory, loader };
}

/** Keeps compilation and output settings identical across invalidation tests. */
function createConfig(
directory: string,
rule: NonNullable<Configuration['module']>['rules'],
): Configuration {
return {
mode: 'development',
target: 'node',
context: directory,
entry: './index.ts',
output: {
path: path.join(directory, 'dist'),
filename: 'main.cjs',
chunkFilename: '[id].[contenthash].cjs',
library: { type: 'commonjs2' },
},
resolve: { extensions: ['.ts', '.js'] },
module: { rules: rule },
optimization: { minimize: false },
devtool: false,
};
}

/** Fails on loader errors before attempting to read emitted demo source. */
function checkStats(
error: Error | null | undefined,
stats: Stats | undefined,
): asserts stats is Stats {
if (error) {
throw error;
}
if (!stats || stats.hasErrors()) {
throw new Error(stats?.toString({ all: false, errors: true }) ?? 'Missing webpack stats');
}
}

function expectDeferredDependencies(stats: Stats, directory: string) {
const deferred = [...stats.compilation.modules].find(
(module): module is NormalModule =>
'resource' in module &&
typeof module.resource === 'string' &&
module.resource.endsWith(DEFERRED_QUERY),
);
expect(deferred).toBeDefined();
const dependencies = new Set(deferred?.buildInfo?.snapshot?.getFileIterable());
expect(dependencies.has(path.join(directory, 'Demo.js'))).toBe(true);
expect(dependencies.has(path.join(directory, 'helper.js'))).toBe(true);
}

function runCompiler(compiler: webpackCompiler.Compiler) {
return new Promise<Stats>((resolve, reject) => {
compiler.run((error, stats) => {
try {
checkStats(error, stats);
resolve(stats);
} catch (failure) {
reject(failure);
}
});
});
}

/** Loads the new bundle without reusing the previous watch build's module. */
async function readVariants(directory: string) {
const outputPath = path.join(directory, 'dist/main.cjs');
delete require.cache[outputPath];
// eslint-disable-next-line import/no-dynamic-require -- Loads the emitted fixture bundle.
return require(outputPath).default.loadPrecompute();
}

it(
'invalidates deferred source when a transitive dependency changes',
async () => {
const { directory, loader } = await createFixture();
const compiler = webpack(
createConfig(directory, [
{
test: /index\.ts$/,
use: [{ loader, options: { deferPrecompute: true, output: 'hast' } }],
},
]),
);
let watching: Watching | undefined;
let builds = 0;
const priorMeasures = performance.getEntriesByName(VARIANT_MEASURE).length;
try {
await new Promise<void>((resolve, reject) => {
watching = compiler.watch({ aggregateTimeout: WATCH_AGGREGATE_MS }, (error, stats) => {
void (async () => {
checkStats(error, stats);
expectDeferredDependencies(stats, directory);
const serialized = JSON.stringify(await readVariants(directory));
builds += 1;
expect(performance.getEntriesByName(VARIANT_MEASURE).length - priorMeasures).toBe(
builds,
);
if (builds === 1) {
expect(serialized).toContain('Before');
await writeFile(path.join(directory, 'helper.js'), 'export const label = "After";\n');
return;
}
expect(serialized).toContain('After');
expect(serialized).not.toContain('Before');
resolve();
})().catch(reject);
});
});
} finally {
await new Promise<void>((resolve) => {
if (watching) {
watching.close(() => resolve());
} else {
resolve();
}
});
await new Promise<void>((resolve) => {
compiler.close(() => resolve());
});
}
},
WATCH_TIMEOUT_MS,
);

it('preserves deferred options omitted by JSON serialization', async () => {
const { directory, loader } = await createFixture();
const deferredOptions = { deferPrecompute: true };
Object.defineProperty(deferredOptions, 'output', { value: 'hast' });
const compiler = webpack(
createConfig(directory, [
{
test: /index\.ts$/,
oneOf: [
{ resourceQuery: /mui-deferred-precompute/, use: [{ loader, options: deferredOptions }] },
{ use: [{ loader, options: { deferPrecompute: true } }] },
],
},
]),
);
try {
expectDeferredDependencies(await runCompiler(compiler), directory);
const variants = await readVariants(directory);
expect(variants.Default.source.type).toBe('root');
} finally {
await new Promise<void>((resolve) => {
compiler.close(() => resolve());
});
}
});

it('reuses deferred output when options contain undefined values', async () => {
const { directory, loader } = await createFixture();
const compiler = webpack(
createConfig(directory, [
{
test: /index\.ts$/,
use: [
{ loader, options: { deferPrecompute: true, output: 'hast', performance: undefined } },
],
},
]),
);
const priorMeasures = performance.getEntriesByName(VARIANT_MEASURE).length;
try {
expectDeferredDependencies(await runCompiler(compiler), directory);
expect(performance.getEntriesByName(VARIANT_MEASURE).length - priorMeasures).toBe(1);
const variants = await readVariants(directory);
expect(variants.Default.source.type).toBe('root');
} finally {
await new Promise<void>((resolve) => {
compiler.close(() => resolve());
});
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,80 @@ import { getFileNameFromUrl, IGNORE_COMMENT_PREFIXES } from '../loaderUtils';
import { createPerformanceLogger, logPerformance, performanceMeasure } from './performanceLogger';
import { fallbackToHast } from '../../CodeHighlighter/fallbackFormat';

type DeferredOutput = { source: string; dependencies: string[] };

// Compilation identity prevents reuse across compilers and watch rebuilds.
const deferredCaches = new WeakMap<object, Map<string, DeferredOutput>>();

/** Rejects options whose behavior would be lost in a JSON cache key. */
function isSerializable(value: unknown, ancestors = new Set<object>()): boolean {
if (value === null || typeof value === 'string' || typeof value === 'boolean') {
return true;
}
if (typeof value === 'number') {
return Number.isFinite(value);
}
if (
typeof value !== 'object' ||
ancestors.has(value) ||
Object.getOwnPropertySymbols(value).length
) {
return false;
}

const prototype = Object.getPrototypeOf(value);
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
return false;
}

ancestors.add(value);
const supported = Object.entries(Object.getOwnPropertyDescriptors(value)).every(
([name, descriptor]) => {
if (Array.isArray(value) && name === 'length') {
return true;
}
return (
descriptor.enumerable &&
'value' in descriptor &&
// JSON drops undefined properties, matching how the loader treats absent options.
// Arrays serialize undefined as null, so elements still have to be serializable.
((descriptor.value === undefined && !Array.isArray(value)) ||
isSerializable(descriptor.value, ancestors))
);
},
);
ancestors.delete(value);
return supported;
}

/** Shares completed source only when webpack provides a compilation boundary. */
function getDeferredCache(
context: LoaderContext<LoaderOptions>,
source: string,
options: LoaderOptions,
) {
const { _compilation: compilation } = context;
if (!options.deferPrecompute || !compilation || !isSerializable(options)) {
return undefined;
}

let entries = deferredCaches.get(compilation);
if (!entries) {
entries = new Map();
deferredCaches.set(compilation, entries);
}
return { entries, key: JSON.stringify([context.resourcePath, source, options]) };
}

/** Both the shell and deferred module must invalidate when imported source changes. */
function registerDependencies(context: LoaderContext<LoaderOptions>, dependencies: string[]) {
dependencies.forEach((dependency) => {
context.addDependency(
dependency.startsWith('file://') ? fileURLToPath(dependency) : dependency,
);
});
}

/**
* Extracts a string array from structured options data.
* Handles the parser's array format: [[element1, element2, ...]]
Expand Down Expand Up @@ -195,6 +269,15 @@ export async function loadPrecomputedCodeHighlighter(
this.cacheable();

const options = this.getOptions();
const isDeferredRequest = this.resourceQuery === '?mui-deferred-precompute';
const deferredCache = getDeferredCache(this, source, options);
const cached = isDeferredRequest ? deferredCache?.entries.get(deferredCache.key) : undefined;
if (cached) {
registerDependencies(this, cached.dependencies);
callback(null, cached.source);
return;
}

const performanceNotableMs = options.performance?.notableMs ?? 100;
const performanceShowWrapperMeasures = options.performance?.showWrapperMeasures ?? false;

Expand Down Expand Up @@ -390,9 +473,19 @@ export async function loadPrecomputedCodeHighlighter(
);

const deferredRequest = `./${path.basename(this.resourcePath)}?mui-deferred-precompute`;
const isDeferredRequest = this.resourceQuery === '?mui-deferred-precompute';
const deferredSource =
isDeferredRequest || deferredCache
? `export default ${JSON.stringify(variantData)};`
: undefined;
registerDependencies(this, allDependencies);
if (deferredCache && deferredSource) {
deferredCache.entries.set(deferredCache.key, {
source: deferredSource,
dependencies: allDependencies,
});
}
if (isDeferredRequest) {
callback(null, `export default ${JSON.stringify(variantData)};`);
callback(null, deferredSource);
return;
}

Expand All @@ -418,13 +511,6 @@ export async function loadPrecomputedCodeHighlighter(
[functionName, relativePath],
);

// Add all dependencies to webpack's watch list
allDependencies.forEach((dep) => {
// Convert file:// URLs to proper file system paths for webpack's dependency tracking
// Using fileURLToPath handles Windows drive letters correctly (e.g., file:///C:/... → C:\...)
this.addDependency(dep.startsWith('file://') ? fileURLToPath(dep) : dep);
});

// log any pending performance entries before completing
observer
?.takeRecords()
Expand Down
Loading
Loading