MUI Docs Infra

Warning

This is an internal project, and is not intended for public use. No support or stability guarantees are provided.

Parse Create Factory Call

The parseCreateFactoryCall utility is a generic source-code parser for createX(import.meta.url, …)-style factory calls. Given the source of a file, it locates the first createSomething(import.meta.url, …) call, resolves any imported variants against the file's URL, and returns a structured result describing the variants, options, named exports, and surrounding imports.

It is the shared primitive that powers all of the docs-infra server loaders (loadServerCodeMeta, loadServerSitemap, loadPrecomputedTypes, and the precomputed code highlighter). It can also be used directly inside a custom CodeProvider — for example, to discover the variants of a remote demo from raw text fetched over HTTP.

Basic Usage

import { parseCreateFactoryCall } from '@mui/internal-docs-infra/pipeline/parseCreateFactoryCall';

const source = `
  import Button from './Button';
  import Checkbox from './Checkbox';
  export const demo = createDemo(import.meta.url, { Button, Checkbox });
`;

const factory = await parseCreateFactoryCall(source, 'file:///src/demo.ts');

factory?.functionName; // 'createDemo'
factory?.variants;
// {
//   Button: 'file:///src/Button',
//   Checkbox: 'file:///src/Checkbox',
// }
factory?.options; // {}

The function returns null when no createX(…) call is found.

The second argument is the URL (or absolute path) of the file the source came from. It is used to resolve relative imports — every variant URL in the result is the import specifier resolved against this URL. Both file:// URLs and http(s):// URLs are accepted, so the function can run anywhere: at build time against local files, in the browser against fetched remote sources, or on the edge.


Common Patterns

Single component shorthand

When a factory is called with a single component instead of a variants object, the result exposes a single Default variant:

const source = `
  import Component from './Component';
  export const demo = createDemo(import.meta.url, Component);
`;

const factory = await parseCreateFactoryCall(source, 'file:///src/demo.ts');

factory?.variants; // { Default: 'file:///src/Component' }

Named exports

When variants come from named imports, the original export name is captured in namedExports. Default imports map to undefined:

const source = `
  import DefaultComp from './default';
  import { NamedComp as Aliased } from './named';
  export const demo = createDemo(import.meta.url, {
    Default: DefaultComp,
    Aliased,
  });
`;

const factory = await parseCreateFactoryCall(source, 'file:///src/demo.ts');

factory?.namedExports;
// {
//   Default: undefined,    // default import — re-export uses the variant name
//   Aliased: 'NamedComp',  // re-export must use the original named export
// }

This is what lets server loaders reconstruct a working module that re-exports each variant.

Factory options

The third argument to a factory — when present — is parsed as a plain object literal:

const source = `
  import Component from './Component';
  export const demo = createDemo(
    import.meta.url,
    Component,
    { name: 'My demo', skipPrecompute: true },
  );
`;

const factory = await parseCreateFactoryCall(source, 'file:///src/demo.ts');

factory?.options; // { name: 'My demo', skipPrecompute: true }

Fetching demos from a remote source

parseCreateFactoryCall doesn't care where the source came from — it accepts file://, http://, and https:// URLs and uses WHATWG URL resolution for the latter. That makes it the natural building block for a CodeProvider that fetches demos from GitHub or any other HTTP source:

import { parseCreateFactoryCall } from '@mui/internal-docs-infra/pipeline/parseCreateFactoryCall';

async function loadDemoVariants(remoteUrl: string) {
  const source = await fetch(remoteUrl).then((response) => response.text());
  // Pass the remote URL straight through — every variant URL comes back
  // resolved against it (e.g. `https://.../Component`).
  const factory = await parseCreateFactoryCall(source, remoteUrl);

  if (!factory?.variants) {
    throw new Error(`No createX factory call found in ${remoteUrl}`);
  }

  return factory.variants;
}

See the GitHub fetch demo for the full pattern.

Replacing precomputed values

replacePrecomputeValue is a companion utility (also exported from this module) that splices a precompute value into the options argument of a parsed factory call without re-printing the rest of the file. The byte offsets recorded on ParsedCreateFactory (argumentsStartIndex / argumentsEndIndex) make this a pure string replacement — comments, whitespace, and surrounding code are preserved.

import {
  parseCreateFactoryCall,
  replacePrecomputeValue,
} from '@mui/internal-docs-infra/pipeline/parseCreateFactoryCall';

const factory = await parseCreateFactoryCall(source, 'file:///src/demo.ts');
const updated = replacePrecomputeValue(
  source,
  {
    Default: {
      /* …precomputed payload… */
    },
  },
  factory!,
);

This is the same primitive that powers the precomputed loaders (loadPrecomputedCodeHighlighter, loadPrecomputedTypes, loadPrecomputedSitemap) and is exposed here so custom precompute pipelines can reuse it.


How It Works

  1. Find call — Scans the source for the first identifier matching create[A-Z]…( and validates that it is a real call expression (not inside a comment or string).
  2. Parse arguments — Splits the argument list using an internal TypeScript-aware tokenizer that understands generics, type assertions, arrow functions, and nested object literals.
  3. Resolve imports — Cross-references the variant identifiers against the file's import statements, then resolves each relative path against fileUrl. file:// URLs use POSIX path.resolve (preserving cross-platform behavior); http:// and https:// URLs use WHATWG URL resolution.
  4. Collect metadata — Extracts namedExports (so consumers can re-emit working ES module code), options (the third argument), and externals (for runtime resolution).
  5. Return positions — Records the byte offsets of the call's argument list so callers can rewrite the call without re-printing the file.

The function is fully isomorphic — it never touches the filesystem and works in browsers, Node.js, and edge runtimes.

Types

parseCreateFactoryCall

Parses a file to extract a single create* factory call and its variants and options Returns the parsed result with remaining content included Returns null if no create* call is found

ParameterTypeDescription
code
string
filePath
string
parseOptions
ParseOptions | undefined
importsAndComments
ImportsAndComments | undefined
Return Type
Promise<ParsedCreateFactory | null>

parseAllCreateFactoryCalls

Parses all create* factory calls in a file sequentially Returns a record of export names mapped to their parsed factory calls

ParameterTypeDescription
code
string
filePath
string
parseOptions
| Omit<ParseOptions, 'allowMultipleFactories'>
| undefined
Return Type
Promise<Record<string, ParsedCreateFactory>>

replacePrecomputeValue

Adds or replaces precompute data in createDemo function calls.

ParameterTypeDescription
source
string

The source code string containing createDemo calls

precomputeData
Record<string, any>

The data object to inject

demoCallInfo
ParsedCreateFactory | undefined

Information about the parsed demo call structure from parseCreateFactoryCall

options
{ passPrecomputeAsIs?: boolean } | undefined

Optional configuration

Return Type
string

The modified source code with precompute data injected

Additional Types

FactoryOptions
type FactoryOptions = { name?: string; slug?: string; skipPrecompute?: boolean; precompute?: any }
ParsedCreateFactory
type ParsedCreateFactory = {
  functionName: string;
  url: string;
  variants: Record<string, string> | undefined;
  namedExports: Record<string, string | undefined> | undefined;
  options: FactoryOptions;
  fullMatch: string;
  hasOptions: boolean;
  externals: Externals;
  argumentsStartIndex: number;
  argumentsEndIndex: number;
  structuredUrl: string;
  structuredVariants:
    | string
    | (string | any[] | Record<string, any>)[]
    | Record<string, string>
    | undefined;
  structuredOptions?: Record<string, any>;
  hasGenerics: boolean;
  structuredGenerics?: Record<string, any>;
  remaining?: string;
  importsAndComments?: ImportsAndComments;
}
ParseOptions

Parse options for create* factory call parsing

type ParseOptions = {
  metadataOnly?: boolean;
  allowExternalVariants?: boolean;
  allowMultipleFactories?: boolean;
}