Repository navigation
feat(runtime): warn in debug when an ES module passes a relative specifier to the global require - #610
Draft
edusperoni wants to merge 18 commits into
Draft
feat(runtime): warn in debug when an ES module passes a relative specifier to the global require#610edusperoni wants to merge 18 commits into
edusperoni wants to merge 18 commits into
Conversation
Records what the loader does today for the URL shapes dev servers emit, both as registry keys (with and without a tooling-shaped canonicalization vocabulary) and as loaded modules reached from a file module directly and through an import-map entry: import.meta.url, getLoadedModuleUrls(), the request target the server saw, and eviction by invalidateModules.
IsHttpRegistryKey, ParseModuleUrl and the written-authority rule move out of ModuleInternalCallbacks.mm into ModuleUrl, which also gains NormalizeHttpModuleUrl: the spelling the loader gives an absolute http(s) module URL, falling back to the input itself for an HTTP-prefixed string the URL parser rejects. ParseModuleUrl now rebuilds the written-authority href by replacing only the authority inside the parser's href. Rebuilding from the pathname, search and hash getters lost a bare trailing '?' or '#', so the re-parse check failed and the parser's lowercased host replaced the written one.
…rser Every route by which an absolute http(s) URL enters the loader now classifies and spells it with NormalizeHttpModuleUrl: the registry key (CanonicalizeHttpUrlKey and CanonicalizeRegistryKey, hence invalidateModules, import.meta.url and getLoadedModuleUrls), a specifier or import-map target from any importer, a dynamic import()'s query handling and HTTP branch, the graph-walk root, the synchronous fallback fetch, LoadESModule/RunModule roots and the require() URL guard. The fetched URL and the registry key derive from the same string. From a file module, HTTP://h/x and http:/h/x are now http URLs as they already were from an HTTP module, dot segments resolve before the fetch, and characters the parser percent-encodes are encoded in the key. The authority keeps its written spelling. An HTTP-prefixed string the parser rejects stays an HTTP URL in its raw spelling.
Nothing in the runtime feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the unwraps in CanonicalizeHttpUrlKey, CanonicalizeRegistryKey and ModuleInternal, HttpUrlEmbeddedInPath and RepairCollapsedUrlScheme go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://… is a file: URL that names no file, so import() of it rejects without fetching. A dynamic import() from an HTTP module that the resolver left unresolved now rejects instead of re-resolving in the tail, which path-joined an http referrer the URL parser rejects (an IPv6 zone id) into a collapsed URL. An http(s) worker script is labelled with its own URL in the inspector. The unused adjustedRegistryKey is gone.
…y gate The allowlist compares fetched URLs, which the loader now spells with the URL parser (dot segments resolved, characters such as non-ASCII percent-encoded). Each security.remoteModuleAllowlist entry is spelled the same way once, when the allowlist is loaded, with the written authority kept; an entry that is not an http(s) URL stays verbatim. The prefix-and-boundary rule is unchanged. The rule is factored into RemoteUrlMatchesAllowlist, which IsRemoteUrlAllowed applies, and debug builds expose it on ns:module as remoteUrlMatchesAllowlist(url, entries) so it can be tested; release builds omit the member.
…eys they match A scope key matches the importing module's registry key by plain prefix, and http(s) registry keys are spelled by the URL parser, so a scope written with dot segments or a non-ASCII segment matched nothing. An http(s) scope key is now spelled the same way when the map is installed, ending in '/' exactly when it was written so; other scope keys (app paths) and imports keys stay as written.
NormalizeHttpModuleUrl rejects a string that cannot be an http(s) URL from its first character instead of attempting a parse, so file paths pay nothing for it. ParseModuleUrl returns the parser's href unchanged when the written authority already matches it, skipping the rebuild and its re-parse. CanonicalizeHttpUrlKey splits into the spelling step and CanonicalizeNormalizedHttpUrlKey, which applies the vocabulary to an already spelled URL. CanonicalizeRegistryKey, the graph walk (enqueue, fetch completion, root), the dynamic-import HTTP branch, LoadESModule and LoadHttpModuleForUrl, whose callers pass resolved URLs, spell a URL at most once.
Script origins of classic scripts, file ES modules and JSON modules, import.meta.url and the worker inspector URL each built their own file:// URL from a path. ReportedModuleUrl in ModuleUrl now does it for all of them: an http(s) URL in the loader's spelling, any other string that carries a scheme unchanged, and otherwise file:// plus the path with the base directory removed (file:///app/ when empty). The outputs are unchanged except the worker inspector URL, which for an http(s) script is now the normalized URL and for any other scheme-carrying script is the script string itself rather than a file:// prefix glued onto it. The docs no longer describe the file://http… string, which is not a form the loader accepts.
ReportedModuleUrl tested for a URL scheme before asking whether the string is an http(s) URL, so one the loader accepts with leading whitespace or C0 controls failed the scheme test and was prefixed with file://. It now spells http(s) URLs first; other inputs are reported as before.
…ifier to the global require
…' into feat/global-require-esm-diagnostic # Conflicts: # NativeScript/runtime/Runtime.mm
… ReportedModuleUrl
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
…read it exactly A security.remoteModuleAllowlist array with at least one item is now in force: every URL is allowed only when the key is absent, not an array, or an empty array. An item that is not a string, is empty, or has no exact UTF-8 form matches nothing instead of being dropped, so a list of unusable items no longer becomes allow-all. Items are converted to UTF-8 by length through the new tns::ToExactUtf8, so an embedded U+0000 no longer truncates an entry to a broader prefix, and a string with a lone surrogate is reported as unconvertible instead of being read through a NULL -UTF8String. RemoteModuleAllowlistFromConfig and RemoteUrlAllowedByAllowlist hold the policy; the release gate and the debug remoteUrlMatchesAllowlist member both use them, so the member answers what the gate would for a list of entries, including true for [].
The import-map parser read keys, targets, scope keys and section names through -UTF8String, so an embedded U+0000 cut them short, and a cut-short target or scope key is broader than written. They now go through tns::ToExactUtf8 and are kept whole: a specifier key or scope key containing U+0000 matches only those exact bytes. A target containing U+0000 is rejected with a TypeError when the map is validated, since resolving it as a path or fetching it as a URL would end it there.
…' into feat/global-require-esm-diagnostic
NathanWalker
reviewed
Dec 2, 2026
| return; | ||
| } | ||
|
|
||
| const std::string moduleKey = LookupModuleKeyForScriptId(isolate, callerScriptId); |
Contributor
There was a problem hiding this comment.
In @nativescript/vite apps the entry replaces globalThis.require with an _nsReq wrapper defined in bundle.mjs (packages/vite/helpers/main-entry.ts ~498–534), so the first non-factory frame here is always bundle.mjs. Every relative global require then gets one warning naming bundle.mjs, which sits in the app root where both resolutions agree, and never the real caller. Skipping callers whose key is directly in the app root would avoid that.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #609 (it uses the
ReportedModuleUrlhelper that PR adds); the base branch is #609's and this retargets tomainonce that merges.What
Docs: the global
requireis available in ES modules for compatibility and resolves a relative specifier (./x,../x) against the app root, whichever module calls it. An ES module that needs module-relative resolution usescreateRequire(import.meta.url), or, when it was loaded overhttp(s),createRequirewith an app file path.Debug-build warning: when the global
requireis called from an ES module with a relative specifier, the runtime logs once per module (per isolate):requireitself does not change in any build: same resolution, same errors, same return values.Why
A CommonJS module gets a
requirebound to its own folder through the module wrapper. An ES module cannot be wrapped, sorequire(...)inside one is the global function, which is bound to the app root.require("./sibling")from an ES module in a subfolder therefore loads<app>/sibling, or fails, and nothing says why. The module-relativerequirefor ES modules iscreateRequire(import.meta.url), as in Node; the global one stays because the unwrapped main bundle, classic scripts and existing ES-module code use it.How
requiregets a native half of its own (DebugGlobalRequireCallback), which checks the call and then runs the unchangedRequireCallback. The bound directory cannot identify the globalrequire(a CommonJS module in the app root is bound to the same directory), and release builds never create the debug variant, so the globalrequirethere is exactly what it was..,..,./…(other than exactly./, which everyrequireresolves to the app's main entry) or../…. It takes the first stack frame outside the require factory script and looks its script id up among the registered ES modules (LookupModuleKeyForScriptId), so classic scripts,new Function/eval code and CommonJS modules never match, and file andhttp(s)ES modules both do.How it was verified
require("./sibling")still resolves against the app root (twice, and with../),~/…andns:specifiers load,createRequire(import.meta.url)("./sibling")loads the sibling, and classic-script and CommonJS callers of the globalrequireresolve against the app root; the same from a module served over HTTP.createRequirerequire or the classic-script caller. No existing spec triggers the warning.-Werror.Not covered by a spec or a captured line:
./..as whole specifiers warning, exactly./and.xnot warning; a release build was compiled but the suite was not run against it.