From 9a2e81538c872ec87f8aa4c442fbea03700734b8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 19 Nov 2026 23:38:09 -0300 Subject: [PATCH 1/8] fix(runtime): resolve specifiers from HTTP modules against the importer URL Dynamic import() from a module loaded over http(s) now resolves the way a static import already did: './x', '../x', '/x' and '//host/x' resolve against the importer's URL with NSURL, the query kept, and the resolved URL continues through the HTTP path (async graph load, coalescing, waiters, volatile handling). The query and fragment are no longer stripped before resolution, and the root- and scheme-relative forms are no longer looked up in the app bundle with an empty referrer. An http(s) importer also no longer reaches the filesystem implicitly, for import and import() alike. The shared resolver reports a blocked specifier, with no stat or extension probing, for a relative form that does not yield an http(s) URL, a bare specifier the import map (scopes included) does not cover, and '~/x'. Static imports throw from the resolve callback, dynamic imports reject, both with an Error naming the specifier, the importer and what to use instead. An unmapped specifier with another URL scheme is not read from '/' either. Builtins, absolute http(s) URLs, explicit file:/// URLs, blob:nativescript URLs and import-map entries (whatever their target) keep working; createRequire and file importers are unchanged. Documents specifier resolution for file and http(s) importers in docs/ns-builtin-modules.md. --- .../runtime/ModuleInternalCallbacks.mm | 148 +++++++++--- TestRunner/app/tests/HttpEsmLoaderTests.js | 224 ++++++++++++++++++ .../tests/esm/http-importer/bare-dynamic.mjs | 2 + .../tests/esm/http-importer/bare-static.mjs | 2 + .../app/tests/esm/http-importer/file-url.mjs | 1 + .../app/tests/esm/http-importer/mapped.mjs | 1 + .../app/tests/esm/http-importer/tilde.mjs | 2 + TestRunnerTests/TestRunnerTests.swift | 40 +++- docs/ns-builtin-modules.md | 30 +++ types/ns-module.d.ts | 3 +- 10 files changed, 417 insertions(+), 36 deletions(-) create mode 100644 TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/bare-static.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/file-url.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/mapped.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/tilde.mjs diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 51f41ebe9..8e63a5ea4 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1111,8 +1111,42 @@ static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) { std::string path; // kFile std::string specifier; // the specifier after import-map rewriting std::string attempted; // kUnresolved: the last candidate tried + // kUnresolved: non-empty when a rule forbids the specifier outright. It is + // the complete error message, and nothing was probed on disk for it. + std::string blocked; }; +static std::string UnresolvedModuleMessage(const ModuleResolution& resolution) { + if (!resolution.blocked.empty()) { + return resolution.blocked; + } + return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; +} + +// RFC 3986 scheme followed by ':' — a specifier with one is an absolute URL, +// never a bare name. +static bool HasUrlScheme(const std::string& spec) { + if (spec.empty() || !isalpha(static_cast(spec[0]))) { + return false; + } + for (size_t i = 1; i < spec.size(); i++) { + const unsigned char c = static_cast(spec[i]); + if (c == ':') { + return true; + } + if (!isalnum(c) && c != '+' && c != '-' && c != '.') { + return false; + } + } + return false; +} + +static std::string BlockedFromHttpMessage(const std::string& rawSpec, + const std::string& referrerKey, const char* reason) { + return "Cannot resolve module specifier \"" + rawSpec + "\" imported from " + referrerKey + ": " + + reason; +} + static bool IsRegularFile(const std::string& p) { std::string normalized = NormalizePath(p); struct stat st; @@ -1172,15 +1206,17 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, // specifiers must map every form it emits — keys are matched literally. const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); const bool hasImportMap = vocabulary != nullptr && !vocabulary->importMap.empty(); + bool mappedByImportMap = false; if (hasImportMap) { std::string mapped = LookupImportMap(spec, referrerKey); if (!mapped.empty()) { TNS_DEBUG(Esm, "[resolver][import-map] rewrite: %s -> %s", spec.c_str(), mapped.c_str()); spec = mapped; + mappedByImportMap = true; } else if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - // A bare-looking specifier the map didn't match is about to fall back to - // filesystem resolution and almost certainly fail; surface the missing - // entry before the more cryptic `Cannot find module` follow-on. + // A bare-looking specifier the map didn't match either falls back to + // filesystem resolution and almost certainly fails, or — from an HTTP + // importer — is refused; surface the missing entry before that error. bool looksBare = spec[0] != '/' && spec[0] != '.' && spec.find("://") == std::string::npos && spec.find('\\') == std::string::npos; if (looksBare) { @@ -1254,6 +1290,30 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } + // An HTTP importer reaches the filesystem only explicitly: through an + // import-map entry (whatever its target) or a file:// URL. Every other form + // is refused here, before anything is probed on disk. + if (referrerIsHttp && !mappedByImportMap && !StartsWith(spec, "file://")) { + if (specIsRelative || specIsRootAbs) { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); + } else if (spec[0] == '~') { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "app-relative \"~/\" paths are not available to modules loaded over HTTP (use a " + "file:// URL, an import-map entry, or createRequire)."); + } else if (!HasUrlScheme(spec)) { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "it is not in the import map (bare specifiers from an HTTP module must be mapped)."); + } else { + // Another URL scheme (blob:, data:, …): not a file, and import() serves + // blob: itself. + result.attempted = spec; + } + return result; + } + // A query or fragment is URL syntax, never part of a file name, so // `import './x.js?v=1'` names x.js. Stripped here rather than at the // import() entry point, so a static import from a local referrer resolves @@ -1418,11 +1478,12 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr& continue; } // Builtins are served by the resolver from the builtin registry, and an - // unresolved specifier (typically a bare name with no import-map entry) - // stays on the resolver's lazy path — where it either resolves later or - // fails with the resolver's own message. An unmapped bare specifier's - // subtree is therefore not discovered here; any HTTP edge inside it is - // pathological and lands on the synchronous anomaly guard. + // unresolved specifier (typically a bare name with no import-map entry, + // or one an HTTP importer may not use) stays on the resolver's lazy path — + // where it either resolves later or fails with the resolver's own + // message. An unmapped bare specifier's subtree is therefore not + // discovered here; any HTTP edge inside it is pathological and lands on + // the synchronous anomaly guard. const ModuleResolution resolution = ResolveSpecifierToPath(*specUtf8, moduleKey); if (resolution.kind == ModuleResolution::Kind::kBuiltin || resolution.kind == ModuleResolution::Kind::kUnresolved) { @@ -2273,9 +2334,8 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, case ModuleResolution::Kind::kUnresolved: { // Surfaced as an exception rather than left to ReadModule(), which would // abort the process trying to open a directory. - std::string msg = - "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; - isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, msg))); + isolate->ThrowException( + v8::Exception::Error(tns::ToV8String(isolate, UnresolvedModuleMessage(resolution)))); return v8::MaybeLocal(); } case ModuleResolution::Kind::kFile: @@ -2496,8 +2556,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } - // Normalize spec: only strip ?query/hash for non-HTTP specs so SFC HTTP keys keep - // version tags std::string rawSpec = cSpec ? std::string(cSpec) : std::string(); // Builtin modules never reach the loader below; the namespace comes straight @@ -2525,21 +2583,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } std::string normalizedSpec = rawSpec; - // remove query/hash ONLY for non-HTTP specs - bool isHttpLike = (!normalizedSpec.empty() && (StartsWith(normalizedSpec, "http://") || - StartsWith(normalizedSpec, "https://"))); - if (!isHttpLike) { - size_t qpos = normalizedSpec.find_first_of("?#"); - if (qpos != std::string::npos) { - normalizedSpec = normalizedSpec.substr(0, qpos); - } - } - if (normalizedSpec != rawSpec) { - // Rebuild V8 string only if changed - specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); - specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; - TNS_DEBUG(Esm, "[dyn-import][normalize] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); - } v8::EscapableHandleScope scope(isolate); // Create a Promise resolver we'll resolve/reject synchronously for now. @@ -2577,9 +2620,36 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } + const bool importerIsHttp = + StartsWith(dynamicReferrerKey, "http://") || StartsWith(dynamicReferrerKey, "https://"); + + // A file importer's query/fragment never names part of a file, so it is + // dropped up front; an absolute http(s) specifier keeps it as identity. For + // an HTTP importer the seam resolves the specifier as a URL, query included. + const bool isHttpLike = + StartsWith(normalizedSpec, "http://") || StartsWith(normalizedSpec, "https://"); + if (!isHttpLike && !importerIsHttp) { + size_t qpos = normalizedSpec.find_first_of("?#"); + if (qpos != std::string::npos) { + normalizedSpec = normalizedSpec.substr(0, qpos); + } + } + if (normalizedSpec != rawSpec) { + specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); + specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; + TNS_DEBUG(Esm, "[dyn-import][normalize] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); + } + ModuleResolution dynamicResolution; if (!normalizedSpec.empty()) { dynamicResolution = ResolveSpecifierToPath(normalizedSpec, dynamicReferrerKey); + if (!dynamicResolution.blocked.empty()) { + resolver + ->Reject(context, v8::Exception::Error(tns::ToV8String( + isolate, UnresolvedModuleMessage(dynamicResolution)))) + .FromMaybe(false); + return scope.Escape(resolver->GetPromise()); + } if (!dynamicResolution.specifier.empty() && dynamicResolution.specifier != normalizedSpec) { normalizedSpec = dynamicResolution.specifier; specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); @@ -2587,6 +2657,15 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); } + // An HTTP importer's relative, root-relative and scheme-relative imports + // continue as the absolute URL the seam resolved, through the HTTP path. + if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kHttp && + dynamicResolution.url != normalizedSpec) { + normalizedSpec = dynamicResolution.url; + specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); + specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; + TNS_DEBUG(Esm, "[dyn-import][http-rel] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); + } } // Re-use the static resolver to locate / compile the module. @@ -3123,6 +3202,19 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local return scope.Escape(resolver->GetPromise()); } + // The tail below re-resolves with no referrer, which would let an HTTP + // importer's unmapped other-scheme specifier ('data:', 'file:/x') reach + // '/' on disk. Only explicit file:// URLs and import-map + // targets may continue into it. + if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kUnresolved && + normalizedSpec == rawSpec && !StartsWith(normalizedSpec, "file://")) { + resolver + ->Reject(context, v8::Exception::Error(tns::ToV8String( + isolate, UnresolvedModuleMessage(dynamicResolution)))) + .FromMaybe(false); + return scope.Escape(resolver->GetPromise()); + } + // Attempt to resolve relative specs against the referrer's resource URL if available. // This reduces reliance on app-root fallback and ensures ../ segments are collapsed. v8::Local refMod; diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 8f398dea0..f07908d94 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1113,6 +1113,230 @@ describe("HTTP ESM Loader", function() { }); }); + // A module served over HTTP resolves specifiers the way a browser does, + // against its own URL, and reaches the filesystem only explicitly. The + // bundled fixtures named by refused specifiers exist, so an implicit + // filesystem fallback would have loaded them. + describe("specifier resolution from an HTTP importer", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + function importer(origin, dir) { + return import(origin + "/esm/resolve/" + dir + "/importer.mjs"); + } + + function expectRefused(promise, done, check) { + promise.then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (error) { + check(String((error && error.message) || error)); + done(); + }); + } + + it("resolves ./, ../, root- and scheme-relative import() against the importer's URL", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var schemeRelative = origin.replace(/^https?:/, "") + "/esm/resolve/rel/scheme.mjs"; + importer(origin, "rel/dir").then(function (mod) { + return Promise.all([ + mod.load("./sibling.mjs"), + mod.load("../parent.mjs"), + mod.load("/esm/resolve/rel/rooted.mjs"), + mod.load(schemeRelative), + ]); + }).then(function (mods) { + expect(mods.map(function (m) { return m.path; })).toEqual([ + "/esm/resolve/rel/dir/sibling.mjs", + "/esm/resolve/rel/parent.mjs", + "/esm/resolve/rel/rooted.mjs", + "/esm/resolve/rel/scheme.mjs", + ]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("keeps an import()'s query as part of the module's identity", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "query").then(function (mod) { + return Promise.all([mod.load("./target.mjs?k=1"), mod.load("./target.mjs?k=2")]); + }).then(function (mods) { + expect([mods[0].query, mods[1].query]).toEqual(["k=1", "k=2"]); + expect(mods[0]).not.toBe(mods[1]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("refuses a static bare import the import map does not cover", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "tests/esm/http-importer/bare-static.mjs"; + expectRefused( + import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)), + done, + function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("not in the import map"); + expect(globalThis.__nsHttpImporterDiskRead_bareStatic).toBeUndefined(); + }); + }); + + it("refuses a dynamic bare import the import map does not cover", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "tests/esm/http-importer/bare-dynamic.mjs"; + expectRefused(importer(origin, "bare").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain(origin + "/esm/resolve/bare/importer.mjs"); + expect(message).toContain("not in the import map"); + expect(globalThis.__nsHttpImporterDiskRead_bareDynamic).toBeUndefined(); + }); + }); + + it("refuses an app-relative ~/ import", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "~/tests/esm/http-importer/tilde.mjs"; + expectRefused(importer(origin, "tilde").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("\"~/\" paths are not available"); + expect(globalThis.__nsHttpImporterDiskRead_tilde).toBeUndefined(); + }); + }); + + // The fixture is written at run time: a colon in a checked-in file + // name cannot be checked out on Windows. + describe("with a module at the app root named like an other-scheme URL", function () { + var spec = "x-ns-test:other-scheme.mjs"; + var fixturePath = NSBundle.mainBundle.resourcePath + "/app/" + spec; + + afterEach(function () { + var fileManager = NSFileManager.defaultManager; + if (fileManager.fileExistsAtPath(fixturePath)) { + fileManager.removeItemAtPathError(fixturePath); + } + }); + + it("refuses the import() instead of reading the app root", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var body = "globalThis.__nsHttpImporterDiskRead_otherScheme = true;\n" + + "export const name = \"other-scheme\";\n"; + var data = NSString.stringWithString(body).dataUsingEncoding(NSUTF8StringEncoding); + var written = NSFileManager.defaultManager + .createFileAtPathContentsAttributes(fixturePath, data, null); + expect(written).toBe(true); + expect(NSFileManager.defaultManager.fileExistsAtPath(fixturePath)).toBe(true); + expectRefused(importer(origin, "other-scheme").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain(spec); + expect(globalThis.__nsHttpImporterDiskRead_otherScheme).toBeUndefined(); + }); + }); + }); + + it("imports a builtin", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "builtin").then(function (mod) { + return mod.load("ns:module"); + }).then(function (ns) { + expect(ns.createRequire).toBe(nsModule.createRequire); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a bundled module named by an explicit file:// URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "file-url").then(function (mod) { + return mod.load("file:///app/tests/esm/http-importer/file-url.mjs"); + }).then(function (ns) { + expect(ns.name).toBe("file-url"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a bare specifier through its import-map entry, whatever the target", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { + imports: { "ns-http-importer-mapped": "~/tests/esm/http-importer/mapped.mjs" }, + }, + }); + importer(origin, "mapped").then(function (mod) { + return mod.load("ns-http-importer-mapped"); + }).then(function (ns) { + expect(ns.name).toBe("mapped"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); + describe("URL Key Canonicalization", function () { it("preserves query for non-dev/public URLs", function (done) { var origin = getHostOrigin(); diff --git a/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs b/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs new file mode 100644 index 000000000..02d67cde6 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_bareDynamic = true; +export const name = "bare-dynamic"; diff --git a/TestRunner/app/tests/esm/http-importer/bare-static.mjs b/TestRunner/app/tests/esm/http-importer/bare-static.mjs new file mode 100644 index 000000000..ebd447ab8 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/bare-static.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_bareStatic = true; +export const name = "bare-static"; diff --git a/TestRunner/app/tests/esm/http-importer/file-url.mjs b/TestRunner/app/tests/esm/http-importer/file-url.mjs new file mode 100644 index 000000000..9db4aa188 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/file-url.mjs @@ -0,0 +1 @@ +export const name = "file-url"; diff --git a/TestRunner/app/tests/esm/http-importer/mapped.mjs b/TestRunner/app/tests/esm/http-importer/mapped.mjs new file mode 100644 index 000000000..739080868 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/mapped.mjs @@ -0,0 +1 @@ +export const name = "mapped"; diff --git a/TestRunner/app/tests/esm/http-importer/tilde.mjs b/TestRunner/app/tests/esm/http-importer/tilde.mjs new file mode 100644 index 000000000..fbc1c5cae --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/tilde.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_tilde = true; +export const name = "tilde"; diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 24593e0c6..391fa61b8 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -35,6 +35,14 @@ class TestRunnerTests: XCTestCase { let path = (environ["PATH_INFO"] as? String) ?? "/" let query = (environ["QUERY_STRING"] as? String) ?? "" + func jsStringLiteral(_ s: String) -> String { + return s + .replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + .replacingOccurrences(of: "\r", with: "\\r") + } + // Progress beacon from the in-app Jasmine reporter (fire-and-forget): // records the spec currently running so a hang/timeout can report // where the JS suite stalled, even though no JUnit report is POSTed. @@ -111,13 +119,6 @@ class TestRunnerTests: XCTestCase { } if path == "/esm/query.mjs" || path == "/ns/m/query.mjs" { - func jsStringLiteral(_ s: String) -> String { - return s - .replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - .replacingOccurrences(of: "\n", with: "\\n") - .replacingOccurrences(of: "\r", with: "\\r") - } let nowMs = Int(Date().timeIntervalSince1970 * 1000.0) let body = """ export const path = \"\(jsStringLiteral(path))\"; @@ -130,6 +131,31 @@ class TestRunnerTests: XCTestCase { return } + // ── Specifier resolution from an HTTP importer ── + // `…/importer.mjs` exports `load(spec)`, an import() issued + // from its own URL; `…/static.mjs` statically imports the + // specifier in its `spec` param; any other path answers with + // the request target it was reached at. + if path.hasPrefix("/esm/resolve/") { + let body: String + if path.hasSuffix("/importer.mjs") { + body = "export function load(spec) { return import(spec); }\n" + } else if path.hasSuffix("/static.mjs") { + var spec = "" + if let pair = query.split(separator: "&").first(where: { $0.hasPrefix("spec=") }), + let decoded = String(pair.dropFirst("spec=".count)).removingPercentEncoding { + spec = decoded + } + body = "export * as dep from \"\(jsStringLiteral(spec))\";\n" + } else { + body = "export const path = \"\(jsStringLiteral(path))\";\n" + + "export const query = \"\(jsStringLiteral(query))\";\n" + } + startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + // ── MIME-gate routes ────────────────────────────── if path == "/esm/html-fallback.mjs" { // The SPA-fallback shape: an unknown path answered with the diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 72030cab8..e2fde946b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -759,6 +759,36 @@ unmodified where a shim exists: ## Loading ES modules +### Specifier resolution + +`import` and `import()` resolve a specifier the same way, by the kind of the +importing module. `ns:`/`node:` builtins resolve first, and the +[import map](#import-maps-and-scopes) is consulted next for every importer; +the table covers a specifier the map does not match. + +| specifier | file importer | http(s) importer | +|---|---|---| +| `./x`, `../x` | the importer's directory on disk | the importer's URL, query kept | +| `/x` | the app root | the importer's origin, query kept | +| `//host/x` | the app root | the importer's scheme, query kept | +| `~/x` | the app root | refused | +| bare (`pkg`, `pkg/x`) | the app root | refused: it needs an import-map entry | +| `file:///app/x` | the app root | the app root | +| `http(s)://…` | fetched | fetched | + +On disk, the query and fragment are dropped and a missing extension or a +directory is completed with `.mjs`, `.js`, `/index.mjs`, `/index.js`, in that +order. An import-map target is never refused — an entry is explicit +configuration, so it may point an HTTP module at a `~/` path — though a +relative or root-relative target still resolves against an HTTP importer's +URL. From an HTTP importer, a specifier with any other URL scheme (`data:`, +`file:/x`) is never looked up on disk; `import()` of a `blob:nativescript/…` +URL loads from the blob store whatever the importer. A refused specifier fails +before anything is fetched or read from disk, with an `Error` whose message +names the specifier, the importer and what to use instead; +`createRequire()` is the explicit way for an HTTP module to reach +CommonJS or ES modules on disk. + ### The `require()` specifier Every `require` — the global one and any minted by `createRequire` / diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index 348f4485a..00f15997a 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -6,7 +6,8 @@ declare module "ns:module" { * resolved on demand. * * A key ending in `/` maps a whole subtree and its target must end in `/` - * too; longest match wins. The map is validated in full before it is + * too; longest match wins. A module loaded over `http(s)` can use a bare + * specifier only through this map. The map is validated in full before it is * installed — an invalid map throws a `TypeError` out of * {@link configureLoader} and leaves the previously installed map in place. */ From 69b842813fea8c0746fe1fd7676b93cf2db2beea Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 25 Nov 2026 15:39:55 -0300 Subject: [PATCH 2/8] fix(runtime): resolve HTTP importers' specifiers with the WHATWG URL parser A specifier from a module loaded over http(s) now resolves through ada, the parser behind JS `new URL()`, following the HTML module-specifier rules: only '/', './' and '../' prefixes are relative ('//host/x' is a '/' form), anything else is an absolute URL if it parses as one and bare otherwise. So '.x', '.' and '..' are bare and refused without an import-map entry, an absolute 'HTTP://host/x' is an http URL, and dot segments, '\', scheme and host case and default ports are normalized as in a browser: `new URL(spec, importerUrl).href` and `spec` name one module. The NSURL join and the hand-written scheme check are gone from this path; relative import-map targets join through the same parser. File importers are unchanged. A dynamic import() takes an HTTP module's referrer key from its URL directly. Running that URL through the import map let an entry keyed by the module's own URL turn it into a file importer, dropping its queries and resolving its bare and '~/' specifiers on disk. The specifier-resolution docs list the dot-prefixed forms, the URL parser, and the two places import() differs from a static import: a file module's import() drops the query before the import-map lookup, and an import-map target that is not an http(s) URL is looked up once more. --- .../runtime/ModuleInternalCallbacks.mm | 170 +++++++++++------- TestRunner/app/tests/HttpEsmLoaderTests.js | 164 +++++++++++++++++ .../esm/http-importer/self-mapped-bare.mjs | 2 + .../esm/http-importer/self-mapped-tilde.mjs | 2 + .../tests/esm/http-importer/self-mapped.mjs | 1 + docs/ns-builtin-modules.md | 24 ++- 6 files changed, 292 insertions(+), 71 deletions(-) create mode 100644 TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs create mode 100644 TestRunner/app/tests/esm/http-importer/self-mapped.mjs diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index c173d51ae..cb6578f78 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -33,6 +33,7 @@ #include "NsBuiltinModules.h" #include "Runtime.h" // for GetAppConfigValue #include "RuntimeConfig.h" +#include "ada/ada.h" // Do NOT pull all v8 symbols into namespace here; String would clash with // other typedefs inside the NativeScript codebase. We refer to v8 symbols @@ -1546,22 +1547,52 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; } -// RFC 3986 scheme followed by ':' — a specifier with one is an absolute URL, -// never a bare name. -static bool HasUrlScheme(const std::string& spec) { - if (spec.empty() || !isalpha(static_cast(spec[0]))) { - return false; +// The WHATWG URL parse of `input` against `base` (none when empty) — the +// parser behind JS `new URL()`, so a module's URL is spelled the way script +// computes it. Empty when the input does not parse. +static std::string ParseUrlHref(const std::string& input, const std::string& base) { + if (base.empty()) { + auto url = ada::parse(input, nullptr); + return url ? std::string(url->get_href()) : std::string(); } - for (size_t i = 1; i < spec.size(); i++) { - const unsigned char c = static_cast(spec[i]); - if (c == ':') { - return true; - } - if (!isalnum(c) && c != '+' && c != '-' && c != '.') { - return false; - } + auto baseUrl = ada::parse(base, nullptr); + if (!baseUrl) { + return std::string(); } - return false; + auto url = ada::parse(input, &baseUrl.value()); + return url ? std::string(url->get_href()) : std::string(); +} + +static bool IsHttpHref(const std::string& href) { + return StartsWith(href, "http://") || StartsWith(href, "https://"); +} + +struct UrlSpecifier { + enum class Kind { + kHttpUrl, // an http(s) URL + kOtherUrl, // an absolute URL with another scheme + kInvalid, // a relative form that does not parse against the base + kBare, // neither relative nor an absolute URL + }; + Kind kind = Kind::kBare; + std::string href; // kHttpUrl, kOtherUrl +}; + +// HTML "resolve a module specifier", import map aside, against an importer +// whose URL is `baseUrl`. Only '/', './' and '../' prefixes are relative +// ('//host/x' is a '/' form); '.x', '.' and '..' are bare. +static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec, + const std::string& baseUrl) { + UrlSpecifier result; + const bool relative = StartsWith(spec, "/") || StartsWith(spec, "./") || StartsWith(spec, "../"); + result.href = ParseUrlHref(spec, relative ? baseUrl : std::string()); + if (result.href.empty()) { + result.kind = relative ? UrlSpecifier::Kind::kInvalid : UrlSpecifier::Kind::kBare; + } else { + result.kind = + IsHttpHref(result.href) ? UrlSpecifier::Kind::kHttpUrl : UrlSpecifier::Kind::kOtherUrl; + } + return result; } static std::string BlockedFromHttpMessage(const std::string& rawSpec, @@ -1663,6 +1694,48 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, result.specifier = spec; + // An HTTP importer resolves the way a browser does and reaches the + // filesystem only explicitly: through an import-map entry (whatever its + // target, handled below) or a file:// URL. Every other form is refused + // here, before anything is probed on disk. + const bool referrerIsHttp = + StartsWith(referrerKey, "http://") || StartsWith(referrerKey, "https://"); + if (referrerIsHttp && !mappedByImportMap) { + const UrlSpecifier url = ResolveModuleSpecifierAgainstUrl(spec, referrerKey); + switch (url.kind) { + case UrlSpecifier::Kind::kHttpUrl: + TNS_DEBUG(Esm, "[resolver][http-importer] base=%s spec=%s -> %s", referrerKey.c_str(), + spec.c_str(), url.href.c_str()); + result.kind = ModuleResolution::Kind::kHttp; + result.url = url.href; + return result; + case UrlSpecifier::Kind::kInvalid: + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); + return result; + case UrlSpecifier::Kind::kBare: + if (spec[0] == '~') { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "app-relative \"~/\" paths are not available to modules loaded over HTTP (use a " + "file:// URL, an import-map entry, or createRequire)."); + } else { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "it is not in the import map (bare specifiers from an HTTP module must be " + "mapped)."); + } + return result; + case UrlSpecifier::Kind::kOtherUrl: + if (StartsWith(spec, "file://")) { + break; + } + // Not a file (blob:, data:, …); import() serves blob: itself. + result.attempted = spec; + return result; + } + } + if (StartsWith(spec, "http://") || StartsWith(spec, "https://")) { result.kind = ModuleResolution::Kind::kHttp; result.url = spec; @@ -1683,28 +1756,11 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, baseDir = RuntimeConfig.ApplicationPath + "/"; } - // A referrer fetched over HTTP makes its relative and root-absolute imports - // HTTP too, the way a browser resolves them. - const bool referrerIsHttp = - StartsWith(referrerKey, "http://") || StartsWith(referrerKey, "https://"); + // An HTTP importer's relative or root-absolute import-map target resolves + // against the importer's URL. if (referrerIsHttp && (specIsRelative || specIsRootAbs)) { - std::string resolvedHttp; - @autoreleasepool { - NSString* baseStr = [NSString stringWithUTF8String:referrerKey.c_str()]; - NSString* specStr = [NSString stringWithUTF8String:spec.c_str()]; - if (baseStr && specStr) { - NSURL* baseURL = [NSURL URLWithString:baseStr]; - NSURL* rel = [NSURL URLWithString:specStr relativeToURL:baseURL]; - NSURL* absURL = [rel absoluteURL]; - if (absURL) { - NSString* absStr = [absURL absoluteString]; - if (absStr) { - resolvedHttp = std::string([absStr UTF8String] ?: ""); - } - } - } - } - if (StartsWith(resolvedHttp, "http://") || StartsWith(resolvedHttp, "https://")) { + const std::string resolvedHttp = ParseUrlHref(spec, referrerKey); + if (IsHttpHref(resolvedHttp)) { TNS_DEBUG(Esm, "[resolver][http-rel] base=%s spec=%s -> %s", referrerKey.c_str(), spec.c_str(), resolvedHttp.c_str()); result.kind = ModuleResolution::Kind::kHttp; @@ -1713,30 +1769,6 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } - // An HTTP importer reaches the filesystem only explicitly: through an - // import-map entry (whatever its target) or a file:// URL. Every other form - // is refused here, before anything is probed on disk. - if (referrerIsHttp && !mappedByImportMap && !StartsWith(spec, "file://")) { - if (specIsRelative || specIsRootAbs) { - result.blocked = BlockedFromHttpMessage( - rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); - } else if (spec[0] == '~') { - result.blocked = BlockedFromHttpMessage( - rawSpec, referrerKey, - "app-relative \"~/\" paths are not available to modules loaded over HTTP (use a " - "file:// URL, an import-map entry, or createRequire)."); - } else if (!HasUrlScheme(spec)) { - result.blocked = BlockedFromHttpMessage( - rawSpec, referrerKey, - "it is not in the import map (bare specifiers from an HTTP module must be mapped)."); - } else { - // Another URL scheme (blob:, data:, …): not a file, and import() serves - // blob: itself. - result.attempted = spec; - } - return result; - } - // A query or fragment is URL syntax, never part of a file name, so // `import './x.js?v=1'` names x.js. Stripped here rather than at the // import() entry point, so a static import from a local referrer resolves @@ -3052,15 +3084,21 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // a local module — while scopes are matched against the registry key, an // absolute app path. Canonicalizing the origin alone stops at `/app/…` // and matches no scope, so the origin goes through the same resolution - // the registry keys by first. + // the registry keys by first. An HTTP module's origin is its URL + // already, and an identity: it must not go through the import map. const std::string resourceName(*resourceUtf8); - const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); - if (referrer.kind == ModuleResolution::Kind::kFile) { - dynamicReferrerKey = CanonicalizeRegistryKey(referrer.path); - } else if (referrer.kind == ModuleResolution::Kind::kHttp) { - dynamicReferrerKey = CanonicalizeRegistryKey(referrer.url); + const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); + if (IsHttpHref(resourceUrl)) { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { - dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); + const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); + if (referrer.kind == ModuleResolution::Kind::kFile) { + dynamicReferrerKey = CanonicalizeRegistryKey(referrer.path); + } else if (referrer.kind == ModuleResolution::Kind::kHttp) { + dynamicReferrerKey = CanonicalizeRegistryKey(referrer.url); + } else { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); + } } } } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index b2a150d68..0a27ebb09 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1681,6 +1681,170 @@ describe("HTTP ESM Loader", function() { done(); }); }); + + function rejectionMessage(promise) { + return promise.then(function () { + return "resolved"; + }, function (error) { + return String((error && error.message) || error); + }); + } + + it("stays an HTTP importer when the import map maps its own URL to a file", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var importerUrl = origin + "/esm/resolve/self-mapped/importer.mjs"; + var mod; + import(importerUrl).then(function (loaded) { + mod = loaded; + var imports = {}; + imports[importerUrl] = "~/tests/esm/http-importer/self-mapped.mjs"; + nsModule.configureLoader({ importMap: { imports: imports } }); + return mod.load("./target.mjs?k=self"); + }).then(function (target) { + expect([target.path, target.query]) + .toEqual(["/esm/resolve/self-mapped/target.mjs", "k=self"]); + return rejectionMessage(mod.load("tests/esm/http-importer/self-mapped-bare.mjs")); + }).then(function (bareMessage) { + expect(bareMessage).toContain("not in the import map"); + return rejectionMessage(mod.load("~/tests/esm/http-importer/self-mapped-tilde.mjs")); + }).then(function (tildeMessage) { + expect(tildeMessage).toContain("\"~/\" paths are not available"); + expect(globalThis.__nsHttpImporterDiskRead_selfMappedBare).toBeUndefined(); + expect(globalThis.__nsHttpImporterDiskRead_selfMappedTilde).toBeUndefined(); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("refuses a static import of a dot-prefixed bare specifier", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = ".hidden/static.mjs"; + expectRefused( + import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)), + done, + function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("not in the import map"); + }); + }); + + it("refuses a dynamic import of '.x', '.' and '..' as bare specifiers", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "dot-bare/dir").then(function (mod) { + return Promise.all([".hidden/dynamic.mjs", ".", ".."].map(function (spec) { + return rejectionMessage(mod.load(spec)); + })); + }).then(function (messages) { + messages.forEach(function (message) { + expect(message).toContain("not in the import map"); + }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + // `new URL()` and the loader share the WHATWG URL parser, so every + // spelling of one URL names one module. + it("imports one module for every spelling of its URL from import()", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var importerUrl = origin + "/esm/resolve/identity/importer.mjs"; + import(importerUrl).then(function (mod) { + return Promise.all([ + mod.load("./x.mjs?v=1"), + mod.load("./sub/../x.mjs?v=1"), + mod.load("/esm/resolve/identity/./x.mjs?v=1"), + import(origin + "/esm/resolve/identity/x.mjs?v=1"), + import(new URL("./x.mjs?v=1", importerUrl).href), + ]); + }).then(function (namespaces) { + expect(namespaces[0].query).toBe("v=1"); + namespaces.forEach(function (ns) { + expect(ns).toBe(namespaces[0]); + }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports one module for every spelling of its URL from a static import", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + function staticImporter(spec) { + return import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)); + } + Promise.all([ + staticImporter("./identity-static/x.mjs?v=1"), + staticImporter("/esm/resolve/identity-static/./x.mjs?v=1"), + import(origin + "/esm/resolve/identity-static/x.mjs?v=1"), + ]).then(function (namespaces) { + expect(namespaces[2].query).toBe("v=1"); + expect(namespaces[0].dep).toBe(namespaces[2]); + expect(namespaces[1].dep).toBe(namespaces[2]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "norm").then(function (mod) { + return Promise.all([ + mod.load("/esm/resolve/norm/./a/../dots.mjs"), + mod.load("../../../../../esm/resolve/norm/climb.mjs"), + mod.load("./sub\\back.mjs"), + mod.load(origin.replace(/^http:/, "HTTP:") + "/esm/resolve/norm/upper.mjs"), + ]); + }).then(function (mods) { + expect(mods.map(function (m) { return m.path; })).toEqual([ + "/esm/resolve/norm/dots.mjs", + "/esm/resolve/norm/climb.mjs", + "/esm/resolve/norm/sub/back.mjs", + "/esm/resolve/norm/upper.mjs", + ]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); }); describe("URL Key Canonicalization", function () { diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs new file mode 100644 index 000000000..990b057f0 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_selfMappedBare = true; +export const name = "self-mapped-bare"; diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs new file mode 100644 index 000000000..d9c28d9a8 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_selfMappedTilde = true; +export const name = "self-mapped-tilde"; diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped.mjs new file mode 100644 index 000000000..d2d45bb7b --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped.mjs @@ -0,0 +1 @@ +export const name = "self-mapped"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index a48be8bb6..f830698c9 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -946,20 +946,34 @@ unmodified where a shim exists: ### Specifier resolution -`import` and `import()` resolve a specifier the same way, by the kind of the -importing module. `ns:`/`node:` builtins resolve first, and the -[import map](#import-maps-and-scopes) is consulted next for every importer; -the table covers a specifier the map does not match. +A specifier resolves by the kind of the importing module. `ns:`/`node:` +builtins resolve first, and the [import map](#import-maps-and-scopes) is +consulted next for every importer; the table covers a specifier the map does +not match. | specifier | file importer | http(s) importer | |---|---|---| | `./x`, `../x` | the importer's directory on disk | the importer's URL, query kept | +| `.x`, `.`, `..` | the importer's directory on disk; the app root for `import()` | refused: bare, it needs an import-map entry | | `/x` | the app root | the importer's origin, query kept | | `//host/x` | the app root | the importer's scheme, query kept | | `~/x` | the app root | refused | | bare (`pkg`, `pkg/x`) | the app root | refused: it needs an import-map entry | | `file:///app/x` | the app root | the app root | -| `http(s)://…` | fetched | fetched | +| `http(s)://…` | fetched (lowercase scheme only) | fetched | + +An http(s) importer's specifiers follow the HTML module-specifier rules and +are resolved with the WHATWG URL parser, the one behind `new URL()`: dot +segments, `\`, the case of the scheme and host, and default ports are +normalized as a browser does, so `new URL(spec, importerUrl).href` names the +same module as `spec`. + +`import` and `import()` resolve alike, with two exceptions for `import()`: +from a file module it drops the specifier's query and fragment before the +import-map lookup (a static `import 'pkg?x'` looks up `pkg?x`, `import('pkg?x')` +looks up `pkg`), and an import-map target that is not an http(s) URL is looked +up in the top-level `imports` once more, so a target that is itself a key is +followed to that key's target. On disk, the query and fragment are dropped and a missing extension or a directory is completed with `.mjs`, `.js`, `/index.mjs`, `/index.js`, in that From 12a94005d963bb4b05e193856af12d2fa02bfc9a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 25 Nov 2026 15:52:43 -0300 Subject: [PATCH 3/8] test(runtime): keep the dot-prefixed bare spec off the static-importer route A specifier ending in /static.mjs was answered with the static-importer body, so the spec failed at instantiation instead of at resolution without the fix. The specifier-resolution docs also limit the new URL() equivalence to specifiers that resolve to an http(s) URL, and the import() re-lookup to targets that do not. --- TestRunner/app/tests/HttpEsmLoaderTests.js | 2 +- docs/ns-builtin-modules.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 0a27ebb09..524430e7e 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1731,7 +1731,7 @@ describe("HTTP ESM Loader", function() { done(); return; } - var spec = ".hidden/static.mjs"; + var spec = ".hidden/dep.mjs"; expectRefused( import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)), done, diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index f830698c9..3c6d364ae 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -965,15 +965,15 @@ not match. An http(s) importer's specifiers follow the HTML module-specifier rules and are resolved with the WHATWG URL parser, the one behind `new URL()`: dot segments, `\`, the case of the scheme and host, and default ports are -normalized as a browser does, so `new URL(spec, importerUrl).href` names the -same module as `spec`. +normalized as a browser does. A `spec` that resolves to an http(s) URL +therefore names the same module as `new URL(spec, importerUrl).href`. `import` and `import()` resolve alike, with two exceptions for `import()`: from a file module it drops the specifier's query and fragment before the import-map lookup (a static `import 'pkg?x'` looks up `pkg?x`, `import('pkg?x')` -looks up `pkg`), and an import-map target that is not an http(s) URL is looked -up in the top-level `imports` once more, so a target that is itself a key is -followed to that key's target. +looks up `pkg`), and an import-map target that does not resolve to an http(s) +URL is looked up in the top-level `imports` once more, so a target that is +itself a key is followed to that key's target. On disk, the query and fragment are dropped and a missing extension or a directory is completed with `.mjs`, `.js`, `/index.mjs`, `/index.js`, in that From ba35f2b6d7157cbcea20682d3488600de4053734 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 25 Nov 2026 16:11:00 -0300 Subject: [PATCH 4/8] docs: specify specifier resolution for HTTP importers only The section states only what specs cover: the http(s)-importer rules, the dot-prefixed bare forms, import-map targets and blob URLs from an HTTP importer, and the file-module difference between a static import and import() in the import-map lookup of a query. A target that is itself a key is called out as something to avoid rather than as defined behaviour. --- docs/ns-builtin-modules.md | 68 ++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 36 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 3c6d364ae..44adf39f3 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -946,48 +946,44 @@ unmodified where a shim exists: ### Specifier resolution -A specifier resolves by the kind of the importing module. `ns:`/`node:` -builtins resolve first, and the [import map](#import-maps-and-scopes) is -consulted next for every importer; the table covers a specifier the map does -not match. +A module loaded over http(s) resolves the specifiers it imports, with `import` +and `import()` alike, as below. `ns:`/`node:` builtins resolve first, and the +[import map](#import-maps-and-scopes) is consulted next; the table covers a +specifier the map does not match. -| specifier | file importer | http(s) importer | -|---|---|---| -| `./x`, `../x` | the importer's directory on disk | the importer's URL, query kept | -| `.x`, `.`, `..` | the importer's directory on disk; the app root for `import()` | refused: bare, it needs an import-map entry | -| `/x` | the app root | the importer's origin, query kept | -| `//host/x` | the app root | the importer's scheme, query kept | -| `~/x` | the app root | refused | -| bare (`pkg`, `pkg/x`) | the app root | refused: it needs an import-map entry | -| `file:///app/x` | the app root | the app root | -| `http(s)://…` | fetched (lowercase scheme only) | fetched | - -An http(s) importer's specifiers follow the HTML module-specifier rules and -are resolved with the WHATWG URL parser, the one behind `new URL()`: dot -segments, `\`, the case of the scheme and host, and default ports are -normalized as a browser does. A `spec` that resolves to an http(s) URL -therefore names the same module as `new URL(spec, importerUrl).href`. - -`import` and `import()` resolve alike, with two exceptions for `import()`: -from a file module it drops the specifier's query and fragment before the -import-map lookup (a static `import 'pkg?x'` looks up `pkg?x`, `import('pkg?x')` -looks up `pkg`), and an import-map target that does not resolve to an http(s) -URL is looked up in the top-level `imports` once more, so a target that is -itself a key is followed to that key's target. - -On disk, the query and fragment are dropped and a missing extension or a -directory is completed with `.mjs`, `.js`, `/index.mjs`, `/index.js`, in that -order. An import-map target is never refused — an entry is explicit -configuration, so it may point an HTTP module at a `~/` path — though a -relative or root-relative target still resolves against an HTTP importer's -URL. From an HTTP importer, a specifier with any other URL scheme (`data:`, -`file:/x`) is never looked up on disk; `import()` of a `blob:nativescript/…` -URL loads from the blob store whatever the importer. A refused specifier fails +| specifier | from an http(s) importer | +|---|---| +| `./x`, `../x` | the importer's URL, query kept | +| `/x` | the importer's origin, query kept | +| `//host/x` | the importer's scheme, query kept | +| `http(s)://…` | that URL | +| `file:///app/x` | the app root, on disk | +| `~/x` | refused | +| bare (`pkg`, `pkg/x`) | refused: it needs an import-map entry | + +Only `/`, `./` and `../` prefixes are relative: `.x`, `.` and `..` are bare +specifiers and are refused without an import-map entry. Specifiers follow the +HTML module-specifier rules and are resolved with the WHATWG URL parser, the +one behind `new URL()`: dot segments, `\`, the case of the scheme and host, and +default ports are normalized as a browser does. A specifier that resolves to an +http(s) URL therefore names the same module as +`new URL(specifier, importerUrl).href`. + +An import-map entry is never refused — it is explicit configuration, so it may +point an HTTP module at a `~/` path — though a relative or root-relative target +still resolves against the importer's URL. A specifier with any other URL +scheme (`data:`, `file:/x`) is never looked up on disk, and `import()` of a +`blob:nativescript/…` URL loads from the blob store. A refused specifier fails before anything is fetched or read from disk, with an `Error` whose message names the specifier, the importer and what to use instead; `createRequire()` is the explicit way for an HTTP module to reach CommonJS or ES modules on disk. +From a file module, a static `import 'pkg?x'` looks `pkg?x` up in the import +map, while `import('pkg?x')` drops the query and looks up `pkg`. An import-map +target should not itself be a key of the map: `import()` may look a target up +a second time. + ### The `require()` specifier Every `require` — the global one and any minted by `createRequire` / From 0aef8699bf5ac553e345c4acc172ae6f972dbd8c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 25 Nov 2026 16:22:32 -0300 Subject: [PATCH 5/8] fix(runtime): keep the authority of an HTTP importer's URLs as written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A URL resolved for an http(s) importer takes its path, query and fragment and its lowercase scheme from the WHATWG URL parser, but keeps the authority (userinfo, host, port) as spelled by the importer's URL or, for '//host/x' and absolute URLs, by the specifier. Dev tooling configures the origin as typed and compares module URLs against that string, and file importers, import-map targets and invalidateModules keep URLs as written, so a parser-canonicalized host such as 'LOCALHOST' -> 'localhost' made one module load twice. When the written authority would not name the same URL (no '//' after the scheme, whitespace or '\' in it) the parser's href is used unchanged. Both join sites use it: unmapped specifiers and relative import-map targets. Specs: an HTTP module served from 'LOCALHOST' reaches the same module through './x.mjs', '/…/x.mjs', a static import, '//LOCALHOST…' and 'HTTP://LOCALHOST…' as a raw absolute import from a file module, with import.meta.url, getLoadedModuleUrls() and invalidateModules() using that spelling. Also specs for statements in the specifier-resolution docs: a relative import-map target from an HTTP importer, a blob:nativescript URL from an HTTP importer, and a file module's static import versus import() of 'pkg?x' in the import map. The docs describe the parser and the kept authority, and that a specifier matches new URL(specifier, importer) only when that authority is spelled the way new URL() spells it. --- .../runtime/ModuleInternalCallbacks.mm | 74 +++++++-- TestRunner/app/tests/HttpEsmLoaderTests.js | 147 ++++++++++++++++++ .../app/tests/esm/query-map/literal.mjs | 1 + .../tests/esm/query-map/static-importer.mjs | 1 + .../app/tests/esm/query-map/stripped.mjs | 1 + TestRunnerTests/TestRunnerTests.swift | 5 +- docs/ns-builtin-modules.md | 14 +- 7 files changed, 224 insertions(+), 19 deletions(-) create mode 100644 TestRunner/app/tests/esm/query-map/literal.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-importer.mjs create mode 100644 TestRunner/app/tests/esm/query-map/stripped.mjs diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index cb6578f78..4f3d4f54f 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1547,24 +1547,74 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; } -// The WHATWG URL parse of `input` against `base` (none when empty) — the -// parser behind JS `new URL()`, so a module's URL is spelled the way script -// computes it. Empty when the input does not parse. +static bool IsHttpHref(const std::string& href) { + return StartsWith(href, "http://") || StartsWith(href, "https://"); +} + +// The authority (userinfo, host, port) of an absolute or scheme-relative URL +// exactly as written, or empty when `url` does not spell one plainly. +static std::string WrittenAuthority(const std::string& url) { + size_t start = 0; + if (StartsWith(url, "//")) { + start = 2; + } else { + const size_t colon = url.find(':'); + if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { + return std::string(); + } + start = colon + 3; + } + const size_t end = url.find_first_of("/?#", start); + std::string authority = url.substr(start, end == std::string::npos ? end : end - start); + for (const char c : authority) { + if (static_cast(c) <= 0x20 || c == '\\') { + return std::string(); + } + } + return authority; +} + +// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): +// as an absolute URL when `base` is empty, otherwise as a path- or +// scheme-relative reference against `base`. Empty when it does not parse. +// +// An http(s) result keeps its authority as written by whichever string +// supplied it: tooling compares module URLs against the origin string it was +// configured with, so that spelling is part of a module's identity until every +// loader entry point canonicalizes. The parser's own href is used whenever the +// written authority would not name the same URL. static std::string ParseUrlHref(const std::string& input, const std::string& base) { + ada::result url; if (base.empty()) { - auto url = ada::parse(input, nullptr); - return url ? std::string(url->get_href()) : std::string(); + url = ada::parse(input, nullptr); + } else { + auto baseUrl = ada::parse(base, nullptr); + if (!baseUrl) { + return std::string(); + } + url = ada::parse(input, &baseUrl.value()); } - auto baseUrl = ada::parse(base, nullptr); - if (!baseUrl) { + if (!url) { return std::string(); } - auto url = ada::parse(input, &baseUrl.value()); - return url ? std::string(url->get_href()) : std::string(); -} + const std::string href(url->get_href()); + if (!IsHttpHref(href)) { + return href; + } -static bool IsHttpHref(const std::string& href) { - return StartsWith(href, "http://") || StartsWith(href, "https://"); + const std::string authority = + WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); + if (authority.empty()) { + return href; + } + const std::string written = std::string(url->get_protocol()) + "//" + authority + + std::string(url->get_pathname()) + std::string(url->get_search()) + + std::string(url->get_hash()); + auto reparsed = ada::parse(written, nullptr); + if (!reparsed || reparsed->get_href() != url->get_href()) { + return href; + } + return written; } struct UrlSpecifier { diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 524430e7e..c9e2116aa 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1682,6 +1682,75 @@ describe("HTTP ESM Loader", function() { }); }); + it("resolves a relative import-map target against the importer's URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { imports: { "ns-http-importer-relative": "./mapped-target.mjs?k=map" } }, + }); + Promise.all([ + importer(origin, "map-relative").then(function (mod) { + return mod.load("ns-http-importer-relative"); + }), + import(origin + "/esm/resolve/static.mjs?spec=ns-http-importer-relative"), + ]).then(function (namespaces) { + expect([namespaces[0].path, namespaces[0].query]) + .toEqual(["/esm/resolve/map-relative/mapped-target.mjs", "k=map"]); + expect([namespaces[1].dep.path, namespaces[1].dep.query]) + .toEqual(["/esm/resolve/mapped-target.mjs", "k=map"]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a blob:nativescript URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + // The bare test realm has no Blob; createObjectURL needs an + // instance carrying `type`, and the loader only calls `.text()`. + var previousBlob = globalThis.Blob; + globalThis.Blob = function Blob(parts, options) { + this._text = (parts || []).join(""); + this.type = (options && options.type) || ""; + }; + globalThis.Blob.prototype.text = function () { + return Promise.resolve(this._text); + }; + var url = URL.createObjectURL( + new Blob(["export const name = 'http-importer-blob';\n"], + { type: "text/javascript" }), + { ext: ".mjs" }); + function cleanUp() { + URL.revokeObjectURL(url); + if (typeof previousBlob === "undefined") { + delete globalThis.Blob; + } else { + globalThis.Blob = previousBlob; + } + } + importer(origin, "blob").then(function (mod) { + return mod.load(url); + }).then(function (ns) { + cleanUp(); + expect(ns.name).toBe("http-importer-blob"); + done(); + }).catch(function (error) { + cleanUp(); + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + function rejectionMessage(promise) { return promise.then(function () { return "resolved"; @@ -1818,6 +1887,53 @@ describe("HTTP ESM Loader", function() { }); }); + // `LOCALHOST` reaches the same server as the canonical origin but is + // spelled the way the parser would not spell it. + it("keeps the importer's origin as written in the URLs it resolves", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var childUrl = written + "/esm/resolve/authority/x.mjs"; + var direct; + import(childUrl).then(function (ns) { + direct = ns; + return Promise.all([ + importer(written, "authority").then(function (mod) { + return Promise.all([ + mod.load("./x.mjs"), + mod.load("/esm/resolve/authority/x.mjs"), + ]); + }), + import(written + "/esm/resolve/authority/static.mjs?spec=" + + encodeURIComponent("./x.mjs")), + importer(origin, "authority-own").then(function (mod) { + return Promise.all([ + mod.load(childUrl.replace(/^http:/, "")), + mod.load(childUrl.replace(/^http:/, "HTTP:")), + ]); + }), + ]); + }).then(function (results) { + expect(results[0][0]).toBe(direct); + expect(results[0][1]).toBe(direct); + expect(results[1].dep).toBe(direct); + expect(results[2][0]).toBe(direct); + expect(results[2][1]).toBe(direct); + expect(direct.url).toBe(childUrl); + expect(nsModule.getLoadedModuleUrls()).toContain(childUrl); + nsModule.invalidateModules([childUrl]); + expect(nsModule.getLoadedModuleUrls()).not.toContain(childUrl); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { var origin = getHostOrigin(); if (!origin) { @@ -1839,6 +1955,37 @@ describe("HTTP ESM Loader", function() { "/esm/resolve/norm/sub/back.mjs", "/esm/resolve/norm/upper.mjs", ]); + expect(mods[3].url).toBe(origin + "/esm/resolve/norm/upper.mjs"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); + + describe("import-map lookup of a query from a file module", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("looks a static import's query up in the map and drops an import()'s", function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-query-map-pkg": "~/tests/esm/query-map/stripped.mjs", + "ns-query-map-pkg?x": "~/tests/esm/query-map/literal.mjs", + }, + }, + }); + Promise.all([ + import("~/tests/esm/query-map/static-importer.mjs"), + import("ns-query-map-pkg?x"), + ]).then(function (namespaces) { + expect(namespaces[0].dep.name).toBe("literal"); + expect(namespaces[1].name).toBe("stripped"); done(); }).catch(function (error) { expect("rejected: " + formatError(error)).toBe("resolved"); diff --git a/TestRunner/app/tests/esm/query-map/literal.mjs b/TestRunner/app/tests/esm/query-map/literal.mjs new file mode 100644 index 000000000..2bf324a3b --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/literal.mjs @@ -0,0 +1 @@ +export const name = "literal"; diff --git a/TestRunner/app/tests/esm/query-map/static-importer.mjs b/TestRunner/app/tests/esm/query-map/static-importer.mjs new file mode 100644 index 000000000..8f41c258c --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-importer.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-pkg?x"; diff --git a/TestRunner/app/tests/esm/query-map/stripped.mjs b/TestRunner/app/tests/esm/query-map/stripped.mjs new file mode 100644 index 000000000..9f0af7cd3 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/stripped.mjs @@ -0,0 +1 @@ +export const name = "stripped"; diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 286b0d4f3..079459aee 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -135,7 +135,7 @@ class TestRunnerTests: XCTestCase { // `…/importer.mjs` exports `load(spec)`, an import() issued // from its own URL; `…/static.mjs` statically imports the // specifier in its `spec` param; any other path answers with - // the request target it was reached at. + // the request target it was reached at and its import.meta.url. if path.hasPrefix("/esm/resolve/") { let body: String if path.hasSuffix("/importer.mjs") { @@ -149,7 +149,8 @@ class TestRunnerTests: XCTestCase { body = "export * as dep from \"\(jsStringLiteral(spec))\";\n" } else { body = "export const path = \"\(jsStringLiteral(path))\";\n" + - "export const query = \"\(jsStringLiteral(query))\";\n" + "export const query = \"\(jsStringLiteral(query))\";\n" + + "export const url = import.meta.url;\n" } startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) sendBody(body.data(using: .utf8) ?? Data()) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 44adf39f3..506776a60 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -963,11 +963,15 @@ specifier the map does not match. Only `/`, `./` and `../` prefixes are relative: `.x`, `.` and `..` are bare specifiers and are refused without an import-map entry. Specifiers follow the -HTML module-specifier rules and are resolved with the WHATWG URL parser, the -one behind `new URL()`: dot segments, `\`, the case of the scheme and host, and -default ports are normalized as a browser does. A specifier that resolves to an -http(s) URL therefore names the same module as -`new URL(specifier, importerUrl).href`. +HTML module-specifier rules: the WHATWG URL parser, the one behind +`new URL()`, decides whether a specifier is relative, an absolute URL or bare, +and produces the path, query and fragment, so dot segments and `\` resolve and +the scheme is lowercased as in a browser. The authority (userinfo, host and +port) keeps its spelling from the importer's URL, or from the specifier when it +names one (`//host/x`, `http(s)://…`). A specifier that resolves to an http(s) +URL therefore names the same module as `new URL(specifier, importerUrl).href` +whenever that authority is already spelled the way `new URL()` spells it (a +lowercase host, no default port). An import-map entry is never refused — it is explicit configuration, so it may point an HTTP module at a `~/` path — though a relative or root-relative target From 51c5736224d00f3bc2d75baa0a321da81d8ca961 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 25 Nov 2026 21:13:18 -0300 Subject: [PATCH 6/8] refactor(runtime): take the scheme of an HTTP importer's URLs from the URL parser ParseModuleUrl returns whether the input parsed, whether its scheme is http(s) as the parser typed it, and the href (authority kept as written, as before). The specifier classification, the relative import-map target join and the dynamic-import referrer read the scheme from the parsed URL instead of testing the serialized string's prefix. --- .../runtime/ModuleInternalCallbacks.mm | 54 +++++++++++-------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 4f3d4f54f..df1e4fd0c 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1547,8 +1547,8 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; } -static bool IsHttpHref(const std::string& href) { - return StartsWith(href, "http://") || StartsWith(href, "https://"); +static bool HasHttpScheme(const ada::url_aggregator& url) { + return url.type == ada::scheme::type::HTTP || url.type == ada::scheme::type::HTTPS; } // The authority (userinfo, host, port) of an absolute or scheme-relative URL @@ -1574,47 +1574,56 @@ static bool IsHttpHref(const std::string& href) { return authority; } +struct ModuleUrl { + bool parsed = false; + bool http = false; // the scheme is http or https + std::string href; +}; + // `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): // as an absolute URL when `base` is empty, otherwise as a path- or -// scheme-relative reference against `base`. Empty when it does not parse. +// scheme-relative reference against `base`. // // An http(s) result keeps its authority as written by whichever string // supplied it: tooling compares module URLs against the origin string it was // configured with, so that spelling is part of a module's identity until every // loader entry point canonicalizes. The parser's own href is used whenever the // written authority would not name the same URL. -static std::string ParseUrlHref(const std::string& input, const std::string& base) { +static ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { + ModuleUrl result; ada::result url; if (base.empty()) { url = ada::parse(input, nullptr); } else { auto baseUrl = ada::parse(base, nullptr); if (!baseUrl) { - return std::string(); + return result; } url = ada::parse(input, &baseUrl.value()); } if (!url) { - return std::string(); + return result; } - const std::string href(url->get_href()); - if (!IsHttpHref(href)) { - return href; + result.parsed = true; + result.http = HasHttpScheme(*url); + result.href = std::string(url->get_href()); + if (!result.http) { + return result; } const std::string authority = WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); if (authority.empty()) { - return href; + return result; } const std::string written = std::string(url->get_protocol()) + "//" + authority + std::string(url->get_pathname()) + std::string(url->get_search()) + std::string(url->get_hash()); auto reparsed = ada::parse(written, nullptr); - if (!reparsed || reparsed->get_href() != url->get_href()) { - return href; + if (reparsed && reparsed->get_href() == url->get_href()) { + result.href = written; } - return written; + return result; } struct UrlSpecifier { @@ -1635,12 +1644,12 @@ static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec, const std::string& baseUrl) { UrlSpecifier result; const bool relative = StartsWith(spec, "/") || StartsWith(spec, "./") || StartsWith(spec, "../"); - result.href = ParseUrlHref(spec, relative ? baseUrl : std::string()); - if (result.href.empty()) { + const ModuleUrl url = ParseModuleUrl(spec, relative ? baseUrl : std::string()); + result.href = url.href; + if (!url.parsed) { result.kind = relative ? UrlSpecifier::Kind::kInvalid : UrlSpecifier::Kind::kBare; } else { - result.kind = - IsHttpHref(result.href) ? UrlSpecifier::Kind::kHttpUrl : UrlSpecifier::Kind::kOtherUrl; + result.kind = url.http ? UrlSpecifier::Kind::kHttpUrl : UrlSpecifier::Kind::kOtherUrl; } return result; } @@ -1809,12 +1818,12 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, // An HTTP importer's relative or root-absolute import-map target resolves // against the importer's URL. if (referrerIsHttp && (specIsRelative || specIsRootAbs)) { - const std::string resolvedHttp = ParseUrlHref(spec, referrerKey); - if (IsHttpHref(resolvedHttp)) { + const ModuleUrl resolved = ParseModuleUrl(spec, referrerKey); + if (resolved.http) { TNS_DEBUG(Esm, "[resolver][http-rel] base=%s spec=%s -> %s", referrerKey.c_str(), - spec.c_str(), resolvedHttp.c_str()); + spec.c_str(), resolved.href.c_str()); result.kind = ModuleResolution::Kind::kHttp; - result.url = resolvedHttp; + result.url = resolved.href; return result; } } @@ -3138,7 +3147,8 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // already, and an identity: it must not go through the import map. const std::string resourceName(*resourceUtf8); const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); - if (IsHttpHref(resourceUrl)) { + const auto parsedResource = ada::parse(resourceUrl, nullptr); + if (parsedResource && HasHttpScheme(*parsedResource)) { dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); From 7fae40ff3d287b42ef08bac0db651cf48debcea0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 16:41:55 -0300 Subject: [PATCH 7/8] refactor(runtime): check HTTP registry keys with one prefix helper IsHttpRegistryKey matches a lowercase http:// or https:// prefix in one pass and replaces the paired prefix checks in ModuleInternalCallbacks.mm, including the HTTP-importer gates in the resolver and in import(). --- .../runtime/ModuleInternalCallbacks.mm | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index df1e4fd0c..307716c3c 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -90,6 +90,19 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { return s.size() >= n && s.compare(0, n, prefix) == 0; } +// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase +// `http://` or `https://` prefix, file modules being keyed by absolute paths. +// Deliberately not a URL parse: it gates the rule that an HTTP importer never +// reaches the filesystem implicitly, so a key the URL parser would reject (an +// IPv6 zone id, say) must still count as HTTP. +static bool IsHttpRegistryKey(const std::string& key) { + if (key.compare(0, 4, "http") != 0) { + return false; + } + const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; + return key.compare(schemeEnd, 3, "://") == 0; +} + static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& registryKey); static std::string CanonicalizeRegistryKey(const std::string& key); static const char* ModuleStatusToString(v8::Module::Status status); @@ -779,8 +792,8 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& const char* classification = "path"; bool traceEvenWithoutChange = false; - if (StartsWith(key, "http://") || StartsWith(key, "https://") || - StartsWith(key, "file://http://") || StartsWith(key, "file://https://")) { + if (IsHttpRegistryKey(key) || StartsWith(key, "file://http://") || + StartsWith(key, "file://https://")) { registryKey = CanonicalizeHttpUrlKey(key); classification = "http"; } else if (StartsWith(key, "file://")) { @@ -1685,7 +1698,7 @@ static bool IsRegularFile(const std::string& p) { } else if (StartsWith(tail, "https:/") && !StartsWith(tail, "https://")) { tail.insert(6, "/"); } - if (!(StartsWith(tail, "http://") || StartsWith(tail, "https://"))) { + if (!IsHttpRegistryKey(tail)) { return ""; } return tail; @@ -1757,8 +1770,7 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, // filesystem only explicitly: through an import-map entry (whatever its // target, handled below) or a file:// URL. Every other form is refused // here, before anything is probed on disk. - const bool referrerIsHttp = - StartsWith(referrerKey, "http://") || StartsWith(referrerKey, "https://"); + const bool referrerIsHttp = IsHttpRegistryKey(referrerKey); if (referrerIsHttp && !mappedByImportMap) { const UrlSpecifier url = ResolveModuleSpecifierAgainstUrl(spec, referrerKey); switch (url.kind) { @@ -1795,7 +1807,7 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } - if (StartsWith(spec, "http://") || StartsWith(spec, "https://")) { + if (IsHttpRegistryKey(spec)) { result.kind = ModuleResolution::Kind::kHttp; result.url = spec; return result; @@ -2280,7 +2292,7 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; - if (StartsWith(root, "http://") || StartsWith(root, "https://")) { + if (IsHttpRegistryKey(root)) { resolution.kind = ModuleResolution::Kind::kHttp; resolution.url = root; } else if (IsRegularFile(root)) { @@ -2397,7 +2409,7 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, const std::string& canonical // Classification helper for diagnostics auto classify = [](const std::string& s) -> const char* { - bool http = StartsWith(s, "http://") || StartsWith(s, "https://"); + bool http = IsHttpRegistryKey(s); if (http) { return IsVolatileUrl(s) ? "http:volatile" : "http:other"; } @@ -2420,7 +2432,7 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, const std::string& canonical auto it = registry.find(registryKey); if (it != registry.end()) { // Only log stale removal for non-HTTP keys to avoid noisy dev HTTP churn. - bool isHttpKey = StartsWith(registryKey, "http://") || StartsWith(registryKey, "https://"); + bool isHttpKey = IsHttpRegistryKey(registryKey); if (tns::LogCategoryEnabled(tns::LogCategory::Esm) && !isHttpKey) { TNS_DEBUG(Esm, "[resolver] removing stale module %s", registryKey.c_str()); } @@ -3162,14 +3174,12 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } - const bool importerIsHttp = - StartsWith(dynamicReferrerKey, "http://") || StartsWith(dynamicReferrerKey, "https://"); + const bool importerIsHttp = IsHttpRegistryKey(dynamicReferrerKey); // A file importer's query/fragment never names part of a file, so it is // dropped up front; an absolute http(s) specifier keeps it as identity. For // an HTTP importer the seam resolves the specifier as a URL, query included. - const bool isHttpLike = - StartsWith(normalizedSpec, "http://") || StartsWith(normalizedSpec, "https://"); + const bool isHttpLike = IsHttpRegistryKey(normalizedSpec); if (!isHttpLike && !importerIsHttp) { size_t qpos = normalizedSpec.find_first_of("?#"); if (qpos != std::string::npos) { @@ -3556,8 +3566,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // If spec is an HTTP(S) URL, try HTTP fetch+compile directly // Security: HttpFetchModule gates remote module access centrally. - if (!normalizedSpec.empty() && - (StartsWith(normalizedSpec, "http://") || StartsWith(normalizedSpec, "https://"))) { + if (!normalizedSpec.empty() && IsHttpRegistryKey(normalizedSpec)) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeHttpUrlKey(normalizedSpec); // Volatile pattern check: if the URL matches any configured volatile From ba09f4480dcef7c06ec1dfd615b7ccd5e918c6cc Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 17:36:06 -0300 Subject: [PATCH 8/8] fix(runtime): keep the import map off a file module's own URL in import() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit import() derived a local referrer's key by resolving its file:///app/… origin through the seam with the import map applied, so an entry keyed by that URL, or a prefix of it, could turn a file module into an HTTP importer and refuse its ~/ and bare imports. The origin is now resolved with the import-map lookup skipped; it still becomes the app path the registry keys by, so scopes match as before. Specs cover an exact and a prefix entry mapping the module's own URL to the test server. The import-map docs state that the map rewrites only the specifiers a module imports. --- .../runtime/ModuleInternalCallbacks.mm | 27 ++++++---- TestRunner/app/tests/HttpEsmLoaderTests.js | 53 +++++++++++++++++++ .../tests/esm/self-mapped-file/bare-dep.mjs | 1 + .../app/tests/esm/self-mapped-file/local.mjs | 4 ++ .../tests/esm/self-mapped-file/sibling.mjs | 1 + .../tests/esm/self-mapped-file/tilde-dep.mjs | 1 + .../tests/esm/self-mapped-prefix/bare-dep.mjs | 1 + .../tests/esm/self-mapped-prefix/local.mjs | 4 ++ .../tests/esm/self-mapped-prefix/sibling.mjs | 1 + .../esm/self-mapped-prefix/tilde-dep.mjs | 1 + docs/ns-builtin-modules.md | 3 +- 11 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 TestRunner/app/tests/esm/self-mapped-file/bare-dep.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-file/local.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-file/sibling.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-file/tilde-dep.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-prefix/bare-dep.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-prefix/local.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-prefix/sibling.mjs create mode 100644 TestRunner/app/tests/esm/self-mapped-prefix/tilde-dep.mjs diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 307716c3c..a5f1895cd 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1704,10 +1704,16 @@ static bool IsRegularFile(const std::string& p) { return tail; } +enum class ImportMapLookup { + kApply, + kSkip, // the specifier is an existing module's origin, which the map never rewrites +}; + // `referrerKey` is the registry key of the importing module — empty when the // importer is unknown (a dynamic import with no compiled referrer). -static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, - const std::string& referrerKey) { +static ModuleResolution ResolveSpecifierToPath( + const std::string& rawSpec, const std::string& referrerKey, + ImportMapLookup importMap = ImportMapLookup::kApply) { ModuleResolution result; if (rawSpec.empty()) { return result; @@ -1731,9 +1737,10 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, // resolve through it to vendor or HTTP URLs. A client that rewrites // specifiers must map every form it emits — keys are matched literally. const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); + const bool consultImportMap = importMap == ImportMapLookup::kApply; const bool hasImportMap = vocabulary != nullptr && !vocabulary->importMap.empty(); bool mappedByImportMap = false; - if (hasImportMap) { + if (consultImportMap && hasImportMap) { std::string mapped = LookupImportMap(spec, referrerKey); if (!mapped.empty()) { TNS_DEBUG(Esm, "[resolver][import-map] rewrite: %s -> %s", spec.c_str(), mapped.c_str()); @@ -1752,7 +1759,7 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, vocabulary->importMap.empty() ? 1 : 0); } } - } else if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { + } else if (consultImportMap && tns::LogCategoryEnabled(tns::LogCategory::Esm)) { // Map completely empty — distinct from "populated but no entry". bool looksBare = spec[0] != '/' && spec[0] != '.' && spec.find("://") == std::string::npos && spec.find('\\') == std::string::npos; @@ -3151,19 +3158,17 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local if (!resource_name.IsEmpty() && resource_name->IsString()) { v8::String::Utf8Value resourceUtf8(isolate, resource_name); if (*resourceUtf8) { - // The host names the referrer by its script origin — `file:///app/…` for - // a local module — while scopes are matched against the registry key, an - // absolute app path. Canonicalizing the origin alone stops at `/app/…` - // and matches no scope, so the origin goes through the same resolution - // the registry keys by first. An HTTP module's origin is its URL - // already, and an identity: it must not go through the import map. + // A module's origin is its identity and never goes through the import + // map. A local origin (`file:///app/…`) still has to become the absolute + // app path the registry keys by, or no scope would match it. const std::string resourceName(*resourceUtf8); const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); const auto parsedResource = ada::parse(resourceUrl, nullptr); if (parsedResource && HasHttpScheme(*parsedResource)) { dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { - const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); + const ModuleResolution referrer = + ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); if (referrer.kind == ModuleResolution::Kind::kFile) { dynamicReferrerKey = CanonicalizeRegistryKey(referrer.path); } else if (referrer.kind == ModuleResolution::Kind::kHttp) { diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index c9e2116aa..ad4511f43 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1964,6 +1964,59 @@ describe("HTTP ESM Loader", function() { }); }); + describe("an import-map entry keyed by a file module's own URL", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // `mapKey` derives the entry key from the loaded module's own URL; the + // entry points at the test server. + function expectStaysFileImporter(dir, mapKey, done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + import("~/tests/esm/" + dir + "/local.mjs").then(function (mod) { + var imports = {}; + var key = mapKey(mod.url); + imports[key] = origin + "/esm/resolve/" + dir + "/" + + (key.charAt(key.length - 1) === "/" ? "" : "local.mjs"); + nsModule.configureLoader({ importMap: { imports: imports } }); + return Promise.all([ + mod.load("~/tests/esm/" + dir + "/tilde-dep.mjs"), + mod.load("tests/esm/" + dir + "/bare-dep.mjs"), + mod.load("./sibling.mjs"), + ]); + }).then(function (namespaces) { + expect(namespaces.map(function (ns) { return ns.name; })).toEqual([ + dir + "-tilde", + dir + "-bare", + dir + "-sibling", + ]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + } + + it("leaves an exact entry out of the module's import() resolution", function (done) { + expectStaysFileImporter("self-mapped-file", function (url) { + return url; + }, done); + }); + + it("leaves a prefix entry out of the module's import() resolution", function (done) { + expectStaysFileImporter("self-mapped-prefix", function (url) { + return url.substring(0, url.lastIndexOf("/") + 1); + }, done); + }); + }); + describe("import-map lookup of a query from a file module", function () { var nsModule = require("ns:module"); diff --git a/TestRunner/app/tests/esm/self-mapped-file/bare-dep.mjs b/TestRunner/app/tests/esm/self-mapped-file/bare-dep.mjs new file mode 100644 index 000000000..3f0fca17f --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-file/bare-dep.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-file-bare"; diff --git a/TestRunner/app/tests/esm/self-mapped-file/local.mjs b/TestRunner/app/tests/esm/self-mapped-file/local.mjs new file mode 100644 index 000000000..d799907b6 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-file/local.mjs @@ -0,0 +1,4 @@ +export const url = import.meta.url; +export function load(spec) { + return import(spec); +} diff --git a/TestRunner/app/tests/esm/self-mapped-file/sibling.mjs b/TestRunner/app/tests/esm/self-mapped-file/sibling.mjs new file mode 100644 index 000000000..c745a64a4 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-file/sibling.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-file-sibling"; diff --git a/TestRunner/app/tests/esm/self-mapped-file/tilde-dep.mjs b/TestRunner/app/tests/esm/self-mapped-file/tilde-dep.mjs new file mode 100644 index 000000000..f2683c978 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-file/tilde-dep.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-file-tilde"; diff --git a/TestRunner/app/tests/esm/self-mapped-prefix/bare-dep.mjs b/TestRunner/app/tests/esm/self-mapped-prefix/bare-dep.mjs new file mode 100644 index 000000000..c53a35855 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-prefix/bare-dep.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-prefix-bare"; diff --git a/TestRunner/app/tests/esm/self-mapped-prefix/local.mjs b/TestRunner/app/tests/esm/self-mapped-prefix/local.mjs new file mode 100644 index 000000000..d799907b6 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-prefix/local.mjs @@ -0,0 +1,4 @@ +export const url = import.meta.url; +export function load(spec) { + return import(spec); +} diff --git a/TestRunner/app/tests/esm/self-mapped-prefix/sibling.mjs b/TestRunner/app/tests/esm/self-mapped-prefix/sibling.mjs new file mode 100644 index 000000000..aa90b92d9 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-prefix/sibling.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-prefix-sibling"; diff --git a/TestRunner/app/tests/esm/self-mapped-prefix/tilde-dep.mjs b/TestRunner/app/tests/esm/self-mapped-prefix/tilde-dep.mjs new file mode 100644 index 000000000..0048bf012 --- /dev/null +++ b/TestRunner/app/tests/esm/self-mapped-prefix/tilde-dep.mjs @@ -0,0 +1 @@ +export const name = "self-mapped-prefix-tilde"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 506776a60..35bc4ee91 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -662,7 +662,8 @@ consults the most specific matching scope first (longest prefix wins), then progressively less specific ones, then `imports` — so a scope can override a global mapping for one subtree and fall through to it everywhere else. The synchronous resolver, the graph walk, and `import()` all resolve through the -same cascade. +same cascade. The map rewrites only the specifiers a module imports, never the +importing module's own URL. The whole map is parsed and validated before any of it is installed: a rejected map throws a `TypeError` out of `configureLoader` and the previously