Skip to content

feat: support import.meta.glob - #937

Open
fengmk2 wants to merge 9 commits into
mainfrom
feat/watch-glob-report
Open

fengmk2 wants to merge 9 commits into
mainfrom
feat/watch-glob-report

Conversation

@fengmk2

@fengmk2 fengmk2 commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Vite's import.meta.glob finds modules by pattern. Server code that runs through Vite uses it to discover route files, for example:

  • HonoX finds its route files and its _404, _error, _renderer, and _middleware files.
  • nimara-ecommerce finds the entry of each service in its Stripe app's dev server.
  • beaver builds its router from ./admin/**/*.ts and ./public/**/*.ts, without test files.

Code like this cannot run under oxc-node today: the call reaches Node.js as written, and Node.js throws TypeError: (intermediate value).glob is not a function.

This PR expands the call in oxc-node's transform, and lets watch mode restart when a matching file appears or goes.

Switch

import.meta.glob is not Node.js syntax, and a script may test for it, so the expansion is off by default.

  • OXC_IMPORT_GLOB=1 turns it on. The binding reads it as it reads OXC_TRANSFORM_ALL, with the same grammar, so every entry point follows it: oxnode, @oxc-node/core/register, @oxc-node/core/importer, OxcTransformer, transform, and transformAsync.
  • setImportGlob(enabled) overrides the variable for the calling thread, in both directions. A loader passes getImportGlob() to its module.register() hooks.
  • A file without import.meta costs nothing more. A file with import.meta costs one substring search unless its source contains glob.

Interface

The forms that oxc-node accepts, as a subset of Vite's ImportGlobFunction (vite/types/importGlob.d.ts):

interface ImportMeta {
  glob: ImportGlobFunction;
}

interface ImportGlobFunction {
  /** Lazy: each value imports its module on the first call. */
  <M = unknown>(
    glob: string | string[],
    options?: ImportGlobOptions<false>,
  ): Record<string, () => Promise<M>>;
  /** Eager: each value is the module, imported before the importer's own imports. */
  <M = unknown>(glob: string | string[], options: ImportGlobOptions<true>): Record<string, M>;
}

interface ImportGlobOptions<Eager extends boolean> {
  /** Import each file with a static import instead of `() => import()`. Default: `false`. */
  eager?: Eager;
  /** Take one export of each module: a name, or `"default"`. `"*"` is the whole module. */
  import?: string;
  /** A folder relative to the importer (`./` or `../`). Relative patterns and the keys start from it. */
  base?: string;
  /** Also match names that start with `.`, and files in `node_modules`. Default: `false`. */
  exhaustive?: boolean;
  /** Default: `true`. */
  caseSensitive?: boolean;
  // `query` and `as` are errors: Node.js loads each file as a module, not as text or a URL.
}
  • glob is one pattern or an array. Each pattern starts with ./ or ../, or with ! for a negative pattern (!**/x is valid).
  • Both arguments must be literals. A template literal without ${} counts as a string.
  • A key is the path of a matched file relative to the importer, or to base, and starts with ./ or ../. Keys are sorted, and the importer is never a key.
  • Object.keys(import.meta.glob(...)) and Object.values(import.meta.glob(...)) import nothing for the part that they drop, as in Vite.
  • oxc-node ships no type declaration for import.meta.glob. A TypeScript project gets the type from vite/client.

Expansion

The pass runs in transform_program, after the TypeScript transform, as Vite's plugin runs after Vite's TypeScript transform. Every load path goes through it: the CommonJS hook, the ESM load, and the module-runner importer.

// src/server.ts, next to src/routes/health.ts
const routes = import.meta.glob("./routes/*.ts");
console.log(Object.keys(routes)); // [ './routes/health.ts' ]
  • The generated code has Vite's shape: Object.assign({ "./routes/health.ts": () => import("./routes/health.ts") }) replaces the call, and eager imports are the first statements. oxc's code generator makes the source map, so positions outside a call do not move.
  • Supported: relative patterns, arrays, ! patterns, eager, import, a relative base, exhaustive, caseSensitive, Object.keys() and Object.values().
  • Errors, as diagnostics with a code frame and Vite's messages where Vite has one: /-rooted patterns and positive patterns that start with ** (oxc-node has no project root), aliases and bare patterns, query and as (Node.js loads a module, not text), non-literal arguments and option values, unknown options, and wrong option types.
  • Matching: the globstar crate, pinned to =0.0.6, the version that Rolldown pins. Rolldown's glob plugin uses it for its dev-mode watch matcher.
    • The picomatch forms that Vite reads and globstar lacks are rewritten first: (a|b) groups, ranges of two characters ({1..3}), and POSIX classes ([[:digit:]]). A pattern whose only glob syntax is a group also matches its literal text, as picomatch does.
    • A wildcard does not take a name that starts with ., but a part of the pattern that spells the . does (./*/.config/*.ts), as in picomatch. The walk asks globstar's match_dir() which folders to enter.
    • node_modules is skipped unless exhaustive is set, the importer is removed, and keys are sorted. Extglob stays off, as Vite sets it.
  • A file whose only module syntax was the glob call gets export {}, so it stays an ES module on the CommonJS path.
  • A specifier is a URL, so the generated specifiers percent-encode %, #, ?, \, tabs, and line breaks, as pathToFileURL does. ./routes/name#part.ts loads that file, not ./routes/name. The keys stay the file names.
  • The names of eager imports (__vite_glob_<call>_<file>) get more _ until no name in the source starts with them, also a name spelled with a \u escape.

Watch mode

  • { "watch:glob": [...] } is a new report. Each entry has roots (folders to walk, with an optional depth), include and exclude (absolute patterns with /), dot, nocase, and files (what the app listed).
  • The binding records each expansion while watch recording is on. takeWatchGlobs() returns the records, and flush, withFlush, and createRelay in @oxc-node/core/watch-report take it as a new optional argument.
  • runWatch has a new option, globMatcher: (glob) => { matches(file): boolean; mayEnter?(dir): boolean }. oxnode watch passes the binding's GlobMatcher, the same rules that listed the files and chose the folders to walk. Without the option, the watcher uses path.matchesGlob, and @oxc-node/cli/watch still loads no binding.
  • The watcher walks the reported roots for one run, in the same walker as the --include roots. It enters the folders that mayEnter allows, as the transform's walk does, so a new file in ./*/.config/ restarts the app. It always skips .git and what --exclude covers. A listed file is watched by the same rule as a walked one. Without mayEnter, it skips node_modules and dot folders unless dot is set.
    • A matching file that appears is a change. A listed or found file that goes is a change. A rename is one restart.
    • An edit is not a change, unless the app loaded the file, as Vite's hotUpdate ignores edits for glob importers.
    • A listed file that is already gone, or a matching file that the list does not have, is a change at once. The watcher does not do this again in the next run for the same file in the same state, so a list that never agrees with the matcher cannot restart the app without end.
  • --exclude holds for the listed files as for new ones: removing an excluded file restarts nothing.
  • Before each rerun, the watcher drops the globs, as it drops the files that the last run imported.

The README describes the switch, the forms, the errors, and the embedding API.

🤖 Generated with Claude Code

fengmk2 and others added 2 commits November 24, 2026 17:38
A loader that expands globs, such as import.meta.glob, can now send
{ "watch:glob": [...] } through @oxc-node/core/watch-report. The watcher
walks the reported roots and restarts the app when a matching file
appears or goes. An edit is no change unless the app loaded the file.
The new runWatch option globMatcher lets the embedder match the files as
its loader does; the default uses path.matchesGlob.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a pass to the transform that expands import.meta.glob calls as
Vite's plugin for unbundled code does. It runs after the TypeScript
transform, on every load path, and only for files that contain
import.meta while the switch is on (setImportGlob, OXC_IMPORT_GLOB).

Patterns must be relative, because oxc-node has no project root and no
aliases. The fast-glob crate matches the files. The binding records each
expansion for watch mode (takeWatchGlobs), and GlobMatcher lets the
watcher test new files with the same rules. oxnode watch uses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fengmk2 fengmk2 changed the title feat(cli): restart on globs that an embedding loader reports feat: expand import.meta.glob, and restart watch mode on its matches Nov 24, 2026
@fengmk2 fengmk2 changed the title feat: expand import.meta.glob, and restart watch mode on its matches feat: support import.meta.glob Nov 24, 2026
The guard skipped an at-once change for a file that caused one for the
run before. A file that the first walk found new, and that was gone at
the next report, was then skipped, so removing it did not restart the
app. The guard now keys on the path and whether the file exists.

Also build file URLs in the glob report tests that are absolute on
Windows, and match the code frame path as join_errors prints it there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fengmk2 and others added 5 commits November 24, 2026 21:15
Replace fast-glob with globstar, pinned to the version that Rolldown
pins. Its dot option reads a pattern part that spells the dot as
picomatch does, so ./*/.config/*.ts now lists what Vite lists, and the
walk asks match_dir() which folders to enter.

Rewrite the picomatch forms that Vite reads and globstar lacks before
matching: (a|b) groups, ranges of two characters, and POSIX classes. A
pattern whose only glob syntax is a group also matches its literal
text, as picomatch does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Encode the import specifiers of matched files. A specifier is a URL,
  so `#` started a fragment and `%20` loaded `name part.ts`. `%`, `#`,
  `?`, `\`, tabs, and line breaks are percent-encoded, as
  pathToFileURL encodes them. The keys stay the file names.
- Apply --exclude to the files that a glob report lists. Before, the
  watcher registered them without the check, so removing an excluded
  file restarted the app.
- Choose the prefix of generated names against the identifiers of the
  syntax tree when the source has a \u escape, so a name spelled
  `__vite_glob_0_0` is not declared twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pass ran only when the source contained the text "glob", but the
call check read the decoded name. So `import.meta.glob()` threw
on its own and expanded once an unrelated `/* glob */` comment was in
the file. Vite finds the calls in the source text and never expands
the escaped form, so a call now counts only when the source spells
`glob` as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
oxc 0.160 removed `ObjectProperty::computed` and gave static string and
number keys variants of their own, so the option parser did not compile
against oxc-node's main. Tell a computed key by its span, which starts
after the `[` of its property, and read the name with `static_name()`.
Both work with oxc 0.156, which Vite+ builds with, and with 0.160.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Take main's oxc 0.160, which the glob option parser now compiles with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fengmk2
fengmk2 marked this pull request as ready for review November 25, 2026 10:10
@fengmk2
fengmk2 requested a review from Brooooooklyn November 25, 2026 10:10
One folder rule:
- GlobSet::enters() is the walk's folder test, and GlobMatcher.mayEnter()
  exposes it. runWatch's globMatcher returns { matches, mayEnter? }, so
  the watcher prunes folders as the transform walks them: a new file in
  ./*/.config/ restarts, and exhaustive admits node_modules.
- A listed file is watched by the walk's rule (root, depth, pruned
  folders, counts) instead of hard-coded names and a separate --exclude
  filter. A `{` in a pattern no longer makes the depth unlimited.

One walker in DirWatcher:
- The --include roots and each glob are owners of one root list and one
  walked map, instead of a second copy of the walker. `fire` is one
  value, and `own: "run"` with a `presence` flag replaces `own: "glob"`.
  Walks and events take fewer stats.

Smaller cleanups:
- OXC_IMPORT_GLOB is read in Rust like OXC_TRANSFORM_ALL, with
  setImportGlob() as an override, so every entry point follows it.
- Shared helpers: parse_generated_program, scheme_len, posix_name_end,
  toPaths, nodeMatchesGlob, Matcher.excludes, and encode_file_url_path
  for specifiers. A relative path resolves against the transformer's
  cwd. The pre-check needs `glob` as a word, resolve flushes skip
  takeWatchGlobs, and dead state is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant