From 1b784a8d7d4ab0a65b1f37acdb4a41ce0620b9fd Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 20:32:03 -0300 Subject: [PATCH 1/6] test(runtime): pin what import() settles with per importer and specifier shape The import() resolution table records the outcome of 83 specifiers from a file module, a direct eval inside one, a CommonJS script, new Function, an indirect eval and an HTTP module, plus identity, concurrency and JSON attribute specs. Rows hold Android's current outcomes, including a blob URL with a fragment rejecting with "Blob not found". The import-map lookup group compares a static import with an import() issued from a module in the same directory, for exact, prefix, http(s) prefix and scoped entries, and for relative and ~/ specifiers carrying a query or fragment. --- .../assets/app/esm/import-pin/concurrent.mjs | 2 + .../main/assets/app/esm/import-pin/data.json | 1 + .../assets/app/esm/import-pin/dir/index.mjs | 1 + .../assets/app/esm/import-pin/importer-cjs.js | 3 + .../assets/app/esm/import-pin/importer.mjs | 7 + .../main/assets/app/esm/import-pin/leaf.mjs | 1 + .../assets/app/esm/import-pin/link-export.mjs | 2 + .../app/esm/import-pin/link-missing.mjs | 2 + .../app/esm/import-pin/syntax-error.mjs | 1 + .../main/assets/app/esm/import-pin/throws.mjs | 2 + .../main/assets/app/esm/import-pin/tla.mjs | 2 + .../main/assets/app/esm/query-map/dir/sub.mjs | 1 + .../main/assets/app/esm/query-map/file.mjs | 1 + .../assets/app/esm/query-map/importer.mjs | 3 + .../assets/app/esm/query-map/static-files.mjs | 4 + .../app/esm/query-map/static-http-prefix.mjs | 1 + .../app/esm/query-map/static-prefix.mjs | 1 + .../app/esm/query-map/static-scoped.mjs | 1 + .../app/esm/query-map/static-unmapped.mjs | 1 + test-app/app/src/main/assets/app/mainpage.js | 2 + .../assets/app/tests/testDynamicImport.js | 279 ++++++++++++++++++ .../assets/app/tests/testEsmHttpLoader.js | 124 +++++++- 22 files changed, 430 insertions(+), 12 deletions(-) create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/concurrent.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/data.json create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/dir/index.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/importer-cjs.js create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/importer.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/leaf.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/link-export.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/link-missing.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/syntax-error.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/throws.mjs create mode 100644 test-app/app/src/main/assets/app/esm/import-pin/tla.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/dir/sub.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/file.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/importer.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/static-files.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/static-http-prefix.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/static-prefix.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/static-scoped.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-map/static-unmapped.mjs create mode 100644 test-app/app/src/main/assets/app/tests/testDynamicImport.js diff --git a/test-app/app/src/main/assets/app/esm/import-pin/concurrent.mjs b/test-app/app/src/main/assets/app/esm/import-pin/concurrent.mjs new file mode 100644 index 000000000..c2854c33a --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/concurrent.mjs @@ -0,0 +1,2 @@ +globalThis.__importPinConcurrentEvaluations = (globalThis.__importPinConcurrentEvaluations || 0) + 1; +export const name = "concurrent"; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/data.json b/test-app/app/src/main/assets/app/esm/import-pin/data.json new file mode 100644 index 000000000..a31b158eb --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/data.json @@ -0,0 +1 @@ +{ "name": "json" } diff --git a/test-app/app/src/main/assets/app/esm/import-pin/dir/index.mjs b/test-app/app/src/main/assets/app/esm/import-pin/dir/index.mjs new file mode 100644 index 000000000..c3ed4ff73 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/dir/index.mjs @@ -0,0 +1 @@ +export const name = "dir-index"; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/importer-cjs.js b/test-app/app/src/main/assets/app/esm/import-pin/importer-cjs.js new file mode 100644 index 000000000..32bd4680a --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/importer-cjs.js @@ -0,0 +1,3 @@ +exports.load = function (spec) { + return import(spec); +}; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/importer.mjs b/test-app/app/src/main/assets/app/esm/import-pin/importer.mjs new file mode 100644 index 000000000..873b41b60 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/importer.mjs @@ -0,0 +1,7 @@ +export function load(spec, options) { + return options === undefined ? import(spec) : import(spec, options); +} + +export function evalLoad(spec) { + return eval("import(spec)"); +} diff --git a/test-app/app/src/main/assets/app/esm/import-pin/leaf.mjs b/test-app/app/src/main/assets/app/esm/import-pin/leaf.mjs new file mode 100644 index 000000000..78c8271f3 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/leaf.mjs @@ -0,0 +1 @@ +export const name = "leaf"; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/link-export.mjs b/test-app/app/src/main/assets/app/esm/import-pin/link-export.mjs new file mode 100644 index 000000000..90a58f29a --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/link-export.mjs @@ -0,0 +1,2 @@ +import { missingExport } from "./leaf.mjs"; +export const name = "link-export" + missingExport; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/link-missing.mjs b/test-app/app/src/main/assets/app/esm/import-pin/link-missing.mjs new file mode 100644 index 000000000..b61e5b5de --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/link-missing.mjs @@ -0,0 +1,2 @@ +import "./missing-dependency.mjs"; +export const name = "link-missing"; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/syntax-error.mjs b/test-app/app/src/main/assets/app/esm/import-pin/syntax-error.mjs new file mode 100644 index 000000000..8d6519374 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/syntax-error.mjs @@ -0,0 +1 @@ +export const name = ; diff --git a/test-app/app/src/main/assets/app/esm/import-pin/throws.mjs b/test-app/app/src/main/assets/app/esm/import-pin/throws.mjs new file mode 100644 index 000000000..1f3fdd55a --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/throws.mjs @@ -0,0 +1,2 @@ +export const name = "throws"; +throw new TypeError("import-pin evaluation error"); diff --git a/test-app/app/src/main/assets/app/esm/import-pin/tla.mjs b/test-app/app/src/main/assets/app/esm/import-pin/tla.mjs new file mode 100644 index 000000000..63b8ae488 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/import-pin/tla.mjs @@ -0,0 +1,2 @@ +await Promise.resolve(); +export const name = "tla"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/dir/sub.mjs b/test-app/app/src/main/assets/app/esm/query-map/dir/sub.mjs new file mode 100644 index 000000000..df64d3053 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/dir/sub.mjs @@ -0,0 +1 @@ +export const name = "sub"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/file.mjs b/test-app/app/src/main/assets/app/esm/query-map/file.mjs new file mode 100644 index 000000000..95f503bc2 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/file.mjs @@ -0,0 +1 @@ +export const name = "file"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/importer.mjs b/test-app/app/src/main/assets/app/esm/query-map/importer.mjs new file mode 100644 index 000000000..0712d2d4b --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/test-app/app/src/main/assets/app/esm/query-map/static-files.mjs b/test-app/app/src/main/assets/app/esm/query-map/static-files.mjs new file mode 100644 index 000000000..b4777dc45 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/static-files.mjs @@ -0,0 +1,4 @@ +export * as query from "./file.mjs?v=1"; +export * as fragment from "./file.mjs#frag"; +export * as tilde from "~/esm/query-map/file.mjs?v=1"; +export * as dotsInQuery from "./file.mjs?from=/../../nope"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/static-http-prefix.mjs b/test-app/app/src/main/assets/app/esm/query-map/static-http-prefix.mjs new file mode 100644 index 000000000..a12564b58 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/static-http-prefix.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-http/query.mjs?k=pfx"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/static-prefix.mjs b/test-app/app/src/main/assets/app/esm/query-map/static-prefix.mjs new file mode 100644 index 000000000..d1e9a25b9 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/static-prefix.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-dir/sub.mjs?x"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/static-scoped.mjs b/test-app/app/src/main/assets/app/esm/query-map/static-scoped.mjs new file mode 100644 index 000000000..93ba827b6 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/static-scoped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-scoped?x"; diff --git a/test-app/app/src/main/assets/app/esm/query-map/static-unmapped.mjs b/test-app/app/src/main/assets/app/esm/query-map/static-unmapped.mjs new file mode 100644 index 000000000..c790bf6cc --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-map/static-unmapped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-unmapped?x"; diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 4a5919de8..a20b10e03 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -149,6 +149,8 @@ require('./tests/testRuntimeBoundDispatch'); require('./tests/testConcurrentProxyGeneration'); // Fetches from the in-app loopback fixture server, so it goes last require('./tests/testEsmHttpLoader'); +// What import() settles with, per importer kind and specifier shape +require('./tests/testDynamicImport'); // Node-API addon surface require('./tests/NapiTests'); require('./tests/NapiCoverageTests'); diff --git a/test-app/app/src/main/assets/app/tests/testDynamicImport.js b/test-app/app/src/main/assets/app/tests/testDynamicImport.js new file mode 100644 index 000000000..ffaf046eb --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testDynamicImport.js @@ -0,0 +1,279 @@ +// What import() settles with, per importer kind and specifier shape. Each row +// is "ok:" or "rejected::", +// with the app root, the test server origin and blob URLs written as , +// and . Rows run in order and share one module registry, so a +// later row can see what an earlier one loaded. Code built by `new Function` +// or an indirect eval imports with the referrer of the script that built it, +// here this file in tests/. +describe("import() resolution table", function () { + var nsModule = require("ns:module"); + var dir = "~/esm/import-pin/"; + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); + var blobUrl = null; + + // Loopback fetches can outrun the 5s default on a cold emulator. + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function normalize(text) { + var out = String(text).split(appRoot).join(""); + out = out.split(origin).join(""); + if (blobUrl) { + out = out.split(blobUrl).join(""); + } + return out; + } + + function exposed(ns) { + if (ns === null || typeof ns !== "object") { + return "non-object:" + typeof ns; + } + if ("name" in ns) { + return String(ns.name); + } + if ("query" in ns) { + return "query=" + ns.query; + } + if ("default" in ns && ns.default && typeof ns.default === "object" && "name" in ns.default) { + return "default.name=" + ns.default.name; + } + // ns:module's member list differs between Debug and Release. + if ("createRequire" in ns) { + return "createRequire=" + typeof ns.createRequire; + } + return "keys=" + Object.keys(ns).sort().slice(0, 3).join(","); + } + + function describeError(e) { + var cls = e && e.constructor && e.constructor.name ? e.constructor.name : typeof e; + var message = e && typeof e.message === "string" ? e.message : String(e); + return cls + ":" + normalize(message); + } + + function outcome(promise) { + return Promise.resolve(promise).then(function (ns) { + return "ok:" + exposed(ns); + }, function (e) { + return "rejected:" + describeError(e); + }); + } + + var importers = { + esm: function (spec) { + return import(dir + "importer.mjs").then(function (m) { return m.load(spec); }); + }, + esmEval: function (spec) { + return import(dir + "importer.mjs").then(function (m) { return m.evalLoad(spec); }); + }, + cjs: function (spec) { + return require("../esm/import-pin/importer-cjs.js").load(spec); + }, + newFunction: new Function("spec", "return import(spec);"), + indirectEval: function (spec) { + globalThis.__importPinSpec = spec; + return (0, eval)("import(globalThis.__importPinSpec)"); + }, + http: function (spec) { + return import(origin + "/esm/resolve/import-pin/importer.mjs").then(function (m) { + return m.load(spec); + }); + }, + }; + + beforeAll(function () { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-pin-mapped": "~/esm/import-pin/leaf.mjs", + "ns-pin-relative-target": "./leaf.mjs", + "ns-pin-chain": "ns-pin-mapped", + "ns-pin-dir/": "~/esm/import-pin/dir/", + }, + }, + }); + // 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); + }; + blobUrl = URL.createObjectURL(new Blob(["export const name = 'blob';\n"], + { type: "text/javascript" }), { ext: ".mjs" }); + if (typeof previousBlob === "undefined") { + delete globalThis.Blob; + } else { + globalThis.Blob = previousBlob; + } + }); + + afterAll(function () { + URL.revokeObjectURL(blobUrl); + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // [importer, specifier, expected]; a specifier function is called when the + // row runs. + var rows = [ + ["esm", "./leaf.mjs", "ok:leaf"], + ["esm", "../import-pin/leaf.mjs", "ok:leaf"], + ["esm", "./leaf", "ok:leaf"], + ["esm", "./dir", "ok:dir-index"], + ["esm", "./dir/", "ok:dir-index"], + ["esm", "./leaf.mjs?v=1", "ok:leaf"], + ["esm", "./leaf.mjs#f", "ok:leaf"], + ["esm", "ns-pin-mapped", "ok:leaf"], + ["esm", "ns-pin-relative-target", "ok:leaf"], + ["esm", "ns-pin-chain", "rejected:Error:Cannot find module 'ns-pin-mapped' (tried /ns-pin-mapped)"], + ["esm", "ns-pin-dir/index.mjs", "ok:dir-index"], + ["esm", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["esm", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "/app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", function () { return appRoot + "/esm/import-pin/leaf.mjs"; }, "ok:leaf"], + ["esm", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", function () { return "file://" + appRoot + "/esm/import-pin/leaf.mjs"; }, "ok:leaf"], + ["esm", "./data.json", "ok:default.name=json"], + ["esm", "ns:module", "ok:createRequire=function"], + ["esm", "node:url", "ok:keys=URL,URLSearchParams,default"], + ["esm", "ns:import-pin-missing", "rejected:Error:No such built-in module: ns:import-pin-missing"], + ["esm", function () { return blobUrl; }, "ok:blob"], + ["esm", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], + ["esm", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["esm", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /esm/import-pin/missing.mjs)"], + ["esm", "~/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module '~/esm/import-pin/missing.mjs' (tried /app/esm/import-pin/missing.mjs)"], + ["esm", "./syntax-error.mjs", "rejected:SyntaxError:Unexpected token ';'"], + ["esm", "./link-export.mjs", "rejected:Error:Failed to instantiate module: ./link-export.mjs — SyntaxError: The requested module './leaf.mjs' does not provide an export named 'missingExport'"], + ["esm", "./link-export.mjs", "rejected:Error:Failed to instantiate module: ./link-export.mjs — SyntaxError: The requested module './leaf.mjs' does not provide an export named 'missingExport'"], + ["esm", "./link-missing.mjs", "rejected:Error:Failed to instantiate module: ./link-missing.mjs — Error: Cannot find module './missing-dependency.mjs' (tried /esm/import-pin/missing-dependency.mjs)"], + ["esm", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["esm", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["esm", "./tla.mjs", "ok:tla"], + ["esm", "", "rejected:Error:Cannot find module '' (tried )"], + + ["esmEval", "./leaf.mjs", "ok:leaf"], + + ["cjs", "./leaf.mjs", "ok:leaf"], + ["cjs", "../import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "./leaf", "ok:leaf"], + ["cjs", "./dir", "ok:dir-index"], + ["cjs", "ns-pin-mapped", "ok:leaf"], + ["cjs", "ns-pin-relative-target", "ok:leaf"], + ["cjs", "ns-pin-chain", "rejected:Error:Cannot find module 'ns-pin-mapped' (tried /ns-pin-mapped)"], + ["cjs", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["cjs", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "./data.json", "ok:default.name=json"], + ["cjs", "ns:module", "ok:createRequire=function"], + ["cjs", function () { return blobUrl; }, "ok:blob"], + ["cjs", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], + ["cjs", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["cjs", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /esm/import-pin/missing.mjs)"], + ["cjs", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + + ["newFunction", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "./esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], + ["newFunction", "ns-pin-mapped", "ok:leaf"], + ["newFunction", "ns-pin-relative-target", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["newFunction", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "ns:module", "ok:createRequire=function"], + ["newFunction", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + + ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], + ["indirectEval", "./esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], + ["indirectEval", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + ]; + + var httpRows = [ + ["esm", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["cjs", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["newFunction", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["http", "./relative.mjs?k=1", "ok:query=k=1"], + ["http", "ns-pin-mapped", "ok:leaf"], + ["http", "ns-pin-unmapped", "rejected:Error:Cannot resolve module specifier \"ns-pin-unmapped\" imported from /esm/resolve/import-pin/importer.mjs: it is not in the import map (bare specifiers from an HTTP module must be mapped)."], + ["http", "~/esm/import-pin/leaf.mjs", "rejected:Error:Cannot resolve module specifier \"~/esm/import-pin/leaf.mjs\" imported from /esm/resolve/import-pin/importer.mjs: app-relative \"~/\" paths are not available to modules loaded over HTTP (use a file:// URL, an import-map entry, or createRequire)."], + ["http", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["http", "file:///app/esm/import-pin/dir", "ok:dir-index"], + ["http", "file:///app/esm/import-pin/data.json", "ok:default.name=json"], + ["http", "file:///app/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module 'file:///app/esm/import-pin/missing.mjs' (tried /esm/import-pin/missing.mjs)"], + ["http", "file:///app/esm/import-pin/throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["http", "ns:module", "ok:createRequire=function"], + ["http", function () { return blobUrl; }, "ok:blob"], + ["http", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], + ["http", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ]; + + var rowCount = 0; + function addRow(row) { + var label = typeof row[1] === "function" + ? String(row[1]).replace(/^function \(\) \{ return |; \}$/g, "") + : JSON.stringify(row[1]); + rowCount++; + it("#" + rowCount + " from " + row[0] + ": " + label, function (done) { + var spec = typeof row[1] === "function" ? row[1]() : row[1]; + outcome(importers[row[0]](spec)).then(function (actual) { + expect(actual).toBe(row[2]); + done(); + }); + }); + } + + rows.forEach(addRow); + httpRows.forEach(addRow); + + it("from esm: the same namespace for a repeated import", function (done) { + Promise.all([importers.esm("./leaf.mjs"), importers.esm("./leaf.mjs")]).then(function (r) { + expect(r[0] === r[1]).toBe(true); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm and cjs: the same namespace for one file", function (done) { + Promise.all([importers.esm("./leaf.mjs"), importers.cjs("./leaf.mjs"), + importers.esm("~/esm/import-pin/leaf.mjs")]).then(function (r) { + expect([r[0] === r[1], r[0] === r[2]]).toEqual([true, true]); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm: concurrent first imports share one evaluation and namespace", function (done) { + Promise.all([importers.esm("./concurrent.mjs"), importers.esm("./concurrent.mjs"), + importers.cjs("./concurrent.mjs")]).then(function (r) { + expect([r[0] === r[1], r[0] === r[2], globalThis.__importPinConcurrentEvaluations]) + .toEqual([true, true, 1]); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm: JSON with a type attribute", function (done) { + import(dir + "importer.mjs").then(function (m) { + return outcome(m.load("./data.json", { with: { type: "json" } })); + }).then(function (actual) { + expect(actual).toBe("ok:default.name=json"); + done(); + }); + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 180aaffcf..803a85339 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -712,33 +712,133 @@ describe("HTTP ESM Loader", function () { }); }); - // A specifier reaches the import map as written from a file module, - // statically and through import() alike, query included. + // Each row compares a static import with an import() issued from a module + // in the same directory. A static importer links once per process, so each + // one serves a single map. describe("import-map lookup of a query from a file module", function () { + useHttpTimeout(); + var nsModule = require("ns:module"); + var dir = "~/esm/query-map/"; afterEach(function () { nsModule.configureLoader({ importMap: { imports: {} } }); }); - it("looks a static import's and an import()'s query up in the map", function (done) { + function settle(promise, pick) { + return promise.then(pick, function (error) { + return "rejected: " + formatError(error); + }); + } + + function name(ns) { + return ns.name; + } + + function dynamicImport(spec) { + return import(dir + "importer.mjs").then(function (mod) { + return mod.load(spec); + }); + } + + // Resolves to [static import's result, import()'s result]. + function bothForms(staticImporter, spec, pick) { + return Promise.all([ + settle(import(dir + staticImporter), function (ns) { + return pick(ns.dep); + }), + settle(dynamicImport(spec), pick), + ]); + } + + it("looks the query up in the map for import() as for a static import", function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-query-map-pkg": dir + "stripped.mjs", + "ns-query-map-pkg?x": dir + "literal.mjs", + }, + }, + }); + bothForms("static-importer.mjs", "ns-query-map-pkg?x", name).then(function (results) { + expect(results).toEqual(["literal", "literal"]); + done(); + }); + }); + + it("applies no entry of the query-less specifier to either form", function (done) { + nsModule.configureLoader({ + importMap: { imports: { "ns-query-map-unmapped": dir + "stripped.mjs" } }, + }); + bothForms("static-unmapped.mjs", "ns-query-map-unmapped?x", name).then(function (results) { + expect(results[0]).toContain("Cannot find module 'ns-query-map-unmapped?x'"); + expect(results[1]).toContain("Cannot find module 'ns-query-map-unmapped?x'"); + done(); + }); + }); + + it("matches a prefix entry rather than the query-less specifier's exact entry", + function (done) { nsModule.configureLoader({ importMap: { imports: { - "ns-query-map-pkg": "~/esm/query-map/stripped.mjs", - "ns-query-map-pkg?x": "~/esm/query-map/literal.mjs", + "ns-query-map-dir/": dir + "dir/", + "ns-query-map-dir/sub.mjs": dir + "stripped.mjs", }, }, }); + bothForms("static-prefix.mjs", "ns-query-map-dir/sub.mjs?x", name).then(function (results) { + expect(results).toEqual(["sub", "sub"]); + done(); + }); + }); + + it("keeps the query on a prefix entry's http(s) target", function (done) { + nsModule.configureLoader({ + importMap: { imports: { "ns-query-map-http/": origin + "/esm/" } }, + }); + bothForms("static-http-prefix.mjs", "ns-query-map-http/query.mjs?k=pfx", function (ns) { + return ns.query; + }).then(function (results) { + expect(results).toEqual(["k=pfx", "k=pfx"]); + done(); + }); + }); + + it("applies a scope to import() as to a static import", function (done) { + var scopes = {}; + scopes[appRoot + "/esm/query-map/"] = { "ns-query-map-scoped?x": dir + "literal.mjs" }; + nsModule.configureLoader({ + importMap: { + imports: { "ns-query-map-scoped": dir + "stripped.mjs" }, + scopes: scopes, + }, + }); + bothForms("static-scoped.mjs", "ns-query-map-scoped?x", name).then(function (results) { + expect(results).toEqual(["literal", "literal"]); + done(); + }); + }); + + it("loads the file a relative or ~/ specifier names, whatever its query or fragment", + function (done) { + var specs = [ + "./file.mjs?v=1", + "./file.mjs#frag", + dir + "file.mjs?v=1", + "./file.mjs?from=/../../nope", + ]; Promise.all([ - import("~/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("literal"); + settle(import(dir + "static-files.mjs"), function (ns) { + return [ns.query.name, ns.fragment.name, ns.tilde.name, ns.dotsInQuery.name]; + }), + Promise.all(specs.map(function (spec) { + return settle(dynamicImport(spec), name); + })), + ]).then(function (results) { + expect(results[0]).toEqual(["file", "file", "file", "file"]); + expect(results[1]).toEqual(["file", "file", "file", "file"]); done(); - }).catch(function (error) { - reportRejection(error, done); }); }); }); From a7446da60a3722f9275239664773dbf13fb4b6ea Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 20:34:14 -0300 Subject: [PATCH 2/6] fix(runtime): look a blob URL up without its fragment import() of a blob: URL now follows the File API's blob URL resolution from every importer: the store is looked up by the URL without its fragment and with its query, so blobUrl + '#f' loads the blob and blobUrl + '?x' rejects with "Blob not found". The module is registered under that same URL, so a blob URL with and without a fragment is one module. --- .../assets/app/tests/testDynamicImport.js | 19 +++++++++++++++---- .../src/main/cpp/ModuleInternalCallbacks.cpp | 9 +++++++++ test-app/runtime/src/main/cpp/ModuleUrl.cpp | 18 ++++++++++++++++++ test-app/runtime/src/main/cpp/ModuleUrl.h | 5 +++++ 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testDynamicImport.js b/test-app/app/src/main/assets/app/tests/testDynamicImport.js index ffaf046eb..0ae8152b1 100644 --- a/test-app/app/src/main/assets/app/tests/testDynamicImport.js +++ b/test-app/app/src/main/assets/app/tests/testDynamicImport.js @@ -149,7 +149,7 @@ describe("import() resolution table", function () { ["esm", "ns:import-pin-missing", "rejected:Error:No such built-in module: ns:import-pin-missing"], ["esm", function () { return blobUrl; }, "ok:blob"], ["esm", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], - ["esm", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["esm", function () { return blobUrl + "#f"; }, "ok:blob"], ["esm", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /esm/import-pin/missing.mjs)"], ["esm", "~/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module '~/esm/import-pin/missing.mjs' (tried /app/esm/import-pin/missing.mjs)"], ["esm", "./syntax-error.mjs", "rejected:SyntaxError:Unexpected token ';'"], @@ -178,7 +178,7 @@ describe("import() resolution table", function () { ["cjs", "ns:module", "ok:createRequire=function"], ["cjs", function () { return blobUrl; }, "ok:blob"], ["cjs", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], - ["cjs", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["cjs", function () { return blobUrl + "#f"; }, "ok:blob"], ["cjs", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /esm/import-pin/missing.mjs)"], ["cjs", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], @@ -191,7 +191,7 @@ describe("import() resolution table", function () { ["newFunction", "/esm/import-pin/leaf.mjs", "ok:leaf"], ["newFunction", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], ["newFunction", "ns:module", "ok:createRequire=function"], - ["newFunction", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["newFunction", function () { return blobUrl + "#f"; }, "ok:blob"], ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], ["indirectEval", "./esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], @@ -214,7 +214,7 @@ describe("import() resolution table", function () { ["http", "ns:module", "ok:createRequire=function"], ["http", function () { return blobUrl; }, "ok:blob"], ["http", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], - ["http", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["http", function () { return blobUrl + "#f"; }, "ok:blob"], ]; var rowCount = 0; @@ -268,6 +268,17 @@ describe("import() resolution table", function () { }); }); + it("from esm: the same namespace for a blob URL with and without a fragment", function (done) { + Promise.all([importers.esm(blobUrl), importers.esm(blobUrl + "#g"), + importers.cjs(blobUrl + "#h")]).then(function (r) { + expect([r[0] === r[1], r[0] === r[2]]).toEqual([true, true]); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + it("from esm: JSON with a type attribute", function (done) { import(dir + "importer.mjs").then(function (m) { return outcome(m.load("./data.json", { with: { type: "json" } })); diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 4176a559d..6a608d0ce 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -3238,6 +3238,15 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( normalizedSpec = dynamicResolution.url; } + // A blob URL is looked up, and keyed, the way the File API resolves it: + // without its fragment, with its query. + { + const std::string blobUrl = BlobStoreUrl(normalizedSpec); + if (!blobUrl.empty()) { + normalizedSpec = blobUrl; + } + } + try { // ── Blob URL support (e.g. blob:nativescript/) ── // Retrieve the blob content from the global BLOB_STORE via diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp index d86a93807..910c84ae8 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.cpp +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -116,6 +116,24 @@ std::string NormalizeHttpModuleUrl(const std::string& input) { return IsHttpRegistryKey(input) ? input : std::string(); } +std::string BlobStoreUrl(const std::string& input) { + // Fast reject only, as in NormalizeHttpModuleUrl. + size_t first = 0; + while (first < input.size() && + static_cast(input[first]) <= 0x20) { + first++; + } + if (first == input.size() || (input[first] != 'b' && input[first] != 'B')) { + return std::string(); + } + auto url = ada::parse(input, nullptr); + if (!url || url->get_protocol() != "blob:") { + return std::string(); + } + url->set_hash(""); + return std::string(url->get_href()); +} + bool HasUrlScheme(const std::string& s) { const size_t colon = s.find(':'); if (colon == 0 || colon == std::string::npos) { diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.h b/test-app/runtime/src/main/cpp/ModuleUrl.h index 44bd43716..2698b9177 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.h +++ b/test-app/runtime/src/main/cpp/ModuleUrl.h @@ -34,6 +34,11 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); // not an http(s) URL. std::string NormalizeHttpModuleUrl(const std::string& input); +// The key the blob URL store is looked up by for `input`, per the File API's +// blob URL resolution: the URL serialized without its fragment, a query kept. +// Empty when `input` is not an absolute blob: URL. +std::string BlobStoreUrl(const std::string& input); + // Whether `s` starts with a URL scheme and ':' (`node:fs`, `blob:…`, // `http://…`) rather than being a filesystem path. bool HasUrlScheme(const std::string& s); From 6d3fd1b46a713cc6243864c9ed48bd220df53456 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 20:36:50 -0300 Subject: [PATCH 3/6] feat(runtime): make a file module's query part of its identity As in browsers and Node, ./x.mjs?v=1, ./x.mjs?v=2, ./x.mjs? and ./x.mjs are four instances of one file, each evaluated once. A file module's registry key is its canonical path plus the specifier's query (after import-map rewriting) as the URL parser serializes it; the fragment is not part of it. A static import and an import() of one queried specifier share an instance, and an import-map target's query names its instance. import.meta.url carries the query. The file read, the code cache (one .mcache per file), import.meta.dirname, relative resolution, import-map scopes, a relative Worker's directory and the inspector's file URL reads use the path. FileModulePath turns a key or a reported file:// URL into that path, and every place that read one as a path goes through it. The entry module, a worker's script and require() of an ES module load the instance without a query. getLoadedModuleUrls keeps skipping file modules whatever their query holds, and invalidateModules given a file:// URL with a query drops only that instance. --- .../assets/app/esm/query-identity/counted.mjs | 4 + .../app/esm/query-identity/importer.mjs | 3 + .../assets/app/esm/query-identity/probe.mjs | 20 ++ .../app/esm/query-identity/query-worker.js | 1 + .../app/esm/query-identity/scoped-target.mjs | 1 + .../app/esm/query-identity/sibling-cjs.js | 1 + .../assets/app/esm/query-identity/sibling.mjs | 1 + .../app/esm/query-identity/static-mapped.mjs | 1 + .../app/esm/query-identity/static-v1.mjs | 1 + .../assets/app/tests/testDynamicImport.js | 177 ++++++++++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 6 + .../src/main/cpp/JsV8InspectorClient.cpp | 7 +- .../runtime/src/main/cpp/ModuleInternal.cpp | 5 +- .../runtime/src/main/cpp/ModuleInternal.h | 7 +- .../src/main/cpp/ModuleInternalCallbacks.cpp | 110 ++++++----- test-app/runtime/src/main/cpp/ModuleUrl.cpp | 30 +++ test-app/runtime/src/main/cpp/ModuleUrl.h | 20 +- 17 files changed, 340 insertions(+), 55 deletions(-) create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/counted.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/importer.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/probe.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/query-worker.js create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/scoped-target.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/sibling-cjs.js create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/sibling.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/static-mapped.mjs create mode 100644 test-app/app/src/main/assets/app/esm/query-identity/static-v1.mjs diff --git a/test-app/app/src/main/assets/app/esm/query-identity/counted.mjs b/test-app/app/src/main/assets/app/esm/query-identity/counted.mjs new file mode 100644 index 000000000..89601e0aa --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/counted.mjs @@ -0,0 +1,4 @@ +const counts = (globalThis.__queryIdentityEvaluations ??= {}); +counts[import.meta.url] = (counts[import.meta.url] || 0) + 1; + +export const url = import.meta.url; diff --git a/test-app/app/src/main/assets/app/esm/query-identity/importer.mjs b/test-app/app/src/main/assets/app/esm/query-identity/importer.mjs new file mode 100644 index 000000000..0712d2d4b --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/test-app/app/src/main/assets/app/esm/query-identity/probe.mjs b/test-app/app/src/main/assets/app/esm/query-identity/probe.mjs new file mode 100644 index 000000000..0b7e52328 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/probe.mjs @@ -0,0 +1,20 @@ +import { createRequire } from "ns:module"; +import { name as siblingName } from "./sibling.mjs"; + +export const url = import.meta.url; +export const search = new URL(import.meta.url).search; +export const dirname = import.meta.dirname; +export const staticSibling = siblingName; +export const required = createRequire(import.meta.url)("./sibling-cjs.js").name; + +export function dynamicSibling() { + return import("./sibling.mjs").then((m) => m.name); +} + +export function scopedImport() { + return import("ns-query-identity-scoped").then((m) => m.name); +} + +export function startWorker() { + return new Worker("./query-worker.js"); +} diff --git a/test-app/app/src/main/assets/app/esm/query-identity/query-worker.js b/test-app/app/src/main/assets/app/esm/query-identity/query-worker.js new file mode 100644 index 000000000..3d945d59f --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/query-worker.js @@ -0,0 +1 @@ +postMessage("query-worker-ready"); diff --git a/test-app/app/src/main/assets/app/esm/query-identity/scoped-target.mjs b/test-app/app/src/main/assets/app/esm/query-identity/scoped-target.mjs new file mode 100644 index 000000000..058bd6308 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/scoped-target.mjs @@ -0,0 +1 @@ +export const name = "scoped-target"; diff --git a/test-app/app/src/main/assets/app/esm/query-identity/sibling-cjs.js b/test-app/app/src/main/assets/app/esm/query-identity/sibling-cjs.js new file mode 100644 index 000000000..532e984fc --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/sibling-cjs.js @@ -0,0 +1 @@ +exports.name = "sibling-cjs"; diff --git a/test-app/app/src/main/assets/app/esm/query-identity/sibling.mjs b/test-app/app/src/main/assets/app/esm/query-identity/sibling.mjs new file mode 100644 index 000000000..309610c4c --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/sibling.mjs @@ -0,0 +1 @@ +export const name = "sibling"; diff --git a/test-app/app/src/main/assets/app/esm/query-identity/static-mapped.mjs b/test-app/app/src/main/assets/app/esm/query-identity/static-mapped.mjs new file mode 100644 index 000000000..bfb546ca4 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/static-mapped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-identity-mapped"; diff --git a/test-app/app/src/main/assets/app/esm/query-identity/static-v1.mjs b/test-app/app/src/main/assets/app/esm/query-identity/static-v1.mjs new file mode 100644 index 000000000..ff8517aec --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/query-identity/static-v1.mjs @@ -0,0 +1 @@ +export * as dep from "./counted.mjs?v=1"; diff --git a/test-app/app/src/main/assets/app/tests/testDynamicImport.js b/test-app/app/src/main/assets/app/tests/testDynamicImport.js index 0ae8152b1..5a6c58aeb 100644 --- a/test-app/app/src/main/assets/app/tests/testDynamicImport.js +++ b/test-app/app/src/main/assets/app/tests/testDynamicImport.js @@ -288,3 +288,180 @@ describe("import() resolution table", function () { }); }); }); + +// A file module's query is part of its identity, as in browsers and Node; its +// fragment is not, as for an http(s) module here. +describe("file module instances per query", function () { + var nsModule = require("ns:module"); + var dir = "~/esm/query-identity/"; + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + var urlBase = "file://" + appRoot + "/esm/query-identity/"; + + function evaluations(url) { + var counts = globalThis.__queryIdentityEvaluations || {}; + return counts[url] || 0; + } + + function load(spec) { + return import(dir + "importer.mjs").then(function (m) { return m.load(spec); }); + } + + function fail(done) { + return function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }; + } + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("gives a static import and an import() with one query one instance", function (done) { + Promise.all([import(dir + "static-v1.mjs"), load("./counted.mjs?v=1")]).then(function (r) { + expect(r[0].dep).toBe(r[1]); + expect(r[1].url).toBe(urlBase + "counted.mjs?v=1"); + expect(evaluations(urlBase + "counted.mjs?v=1")).toBe(1); + done(); + }, fail(done)); + }); + + it("gives two queries, an empty query and none four instances, each evaluated once", + function (done) { + Promise.all([load("./counted.mjs?v=1"), load("./counted.mjs?v=2"), load("./counted.mjs?"), + load("./counted.mjs")]).then(function (r) { + expect(r.map(function (ns) { return ns.url; })).toEqual([ + urlBase + "counted.mjs?v=1", + urlBase + "counted.mjs?v=2", + urlBase + "counted.mjs?", + urlBase + "counted.mjs", + ]); + expect([r[0] === r[1], r[0] === r[3], r[1] === r[3], r[2] === r[3]]) + .toEqual([false, false, false, false]); + expect(r.map(function (ns) { return evaluations(ns.url); })).toEqual([1, 1, 1, 1]); + done(); + }, fail(done)); + }); + + it("keeps the query of an import-map target in the module's identity", function (done) { + nsModule.configureLoader({ + importMap: { imports: { "ns-query-identity-mapped": dir + "counted.mjs?v=map" } }, + }); + Promise.all([import(dir + "static-mapped.mjs"), load("ns-query-identity-mapped"), + load("./counted.mjs?v=map")]).then(function (r) { + expect([r[0].dep === r[1], r[1] === r[2]]).toEqual([true, true]); + expect(r[1].url).toBe(urlBase + "counted.mjs?v=map"); + expect(evaluations(urlBase + "counted.mjs?v=map")).toBe(1); + done(); + }, fail(done)); + }); + + it("does not split instances by fragment", function (done) { + Promise.all([load("./counted.mjs#a"), load("./counted.mjs#b"), load("./counted.mjs"), + load("./counted.mjs?v=1#c"), load("./counted.mjs?v=1")]).then(function (r) { + expect([r[0] === r[2], r[1] === r[2], r[3] === r[4]]).toEqual([true, true, true]); + expect([r[0].url, r[3].url]).toEqual([urlBase + "counted.mjs", urlBase + "counted.mjs?v=1"]); + done(); + }, fail(done)); + }); + + it("gives require() of the file the instance without a query", function (done) { + Promise.all([load("./counted.mjs"), load("./counted.mjs?v=1")]).then(function (r) { + var required = require("../esm/query-identity/counted.mjs"); + expect([required === r[0], required === r[1]]).toEqual([true, false]); + done(); + }, fail(done)); + }); + + it("invalidates the instance a file:// URL's query names and no other", function (done) { + var invalidated = urlBase + "counted.mjs?v=inv"; + Promise.all([load("./counted.mjs?v=inv"), load("./counted.mjs")]).then(function (first) { + nsModule.invalidateModules([invalidated]); + return Promise.all([load("./counted.mjs?v=inv"), load("./counted.mjs")]).then(function (second) { + expect([first[0] === second[0], first[1] === second[1]]).toEqual([false, true]); + expect(evaluations(invalidated)).toBe(2); + done(); + }); + }).catch(fail(done)); + }); + + describe("inside a module imported with a query containing '/', '..' and '://'", function () { + var query = "?a=/../../y&u=http://h/z"; + var probe; + + function scopeOnFixtureDir() { + var scopes = {}; + scopes[appRoot + "/esm/query-identity/"] = { + "ns-query-identity-scoped": dir + "scoped-target.mjs", + }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + } + + beforeAll(function (done) { + scopeOnFixtureDir(); + load("./probe.mjs" + query).then(function (ns) { + probe = ns; + done(); + }, function (e) { + probe = { error: String((e && e.message) || e) }; + done(); + }); + }); + + it("loads", function () { + expect(probe.error).toBeUndefined(); + }); + + it("reports the query in import.meta.url and not in import.meta.dirname", function () { + expect(probe.url).toBe(urlBase + "probe.mjs" + query); + expect(probe.search).toBe(query); + expect(probe.dirname).toBe(appRoot + "/esm/query-identity"); + }); + + it("resolves relative imports against the module's directory", function (done) { + expect(probe.staticSibling).toBe("sibling"); + expect(probe.required).toBe("sibling-cjs"); + probe.dynamicSibling().then(function (name) { + expect(name).toBe("sibling"); + done(); + }, fail(done)); + }); + + it("matches an import-map scope on the module's directory", function (done) { + scopeOnFixtureDir(); + probe.scopedImport().then(function (name) { + expect(name).toBe("scoped-target"); + done(); + }, fail(done)); + }); + + it("starts a relative worker from the module's directory", function (done) { + var worker = probe.startWorker(); + var timer = setTimeout(function () { + worker.terminate(); + expect("no message").toBe("query-worker-ready"); + done(); + }, 10000); + worker.onerror = function (e) { + clearTimeout(timer); + worker.terminate(); + expect("error: " + String((e && e.message) || e)).toBe("query-worker-ready"); + done(); + }; + worker.onmessage = function (msg) { + clearTimeout(timer); + worker.terminate(); + expect(msg.data).toBe("query-worker-ready"); + done(); + }; + }, 15000); + + it("is not listed by getLoadedModuleUrls, like any file module", function () { + var listed = nsModule.getLoadedModuleUrls().filter(function (u) { + return u.indexOf("query-identity") >= 0; + }); + expect(listed).toEqual([]); + }); + }); +}); + diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index e73f16b21..5878756d5 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -1794,6 +1794,12 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfoGetFrame(isolate, 0)->GetScriptName(); auto currentExecutingScriptNameStr = ArgConverter::ConvertToString( currentExecutingScriptName); + // A file module's script URL carries its query, whose slashes are + // not path syntax. + const std::string callerPath = FileModulePath(currentExecutingScriptNameStr); + if (!callerPath.empty()) { + currentExecutingScriptNameStr = callerPath; + } auto lastForwardSlash = currentExecutingScriptNameStr.find_last_of("/"); if (lastForwardSlash != std::string::npos) { auto callerDir = currentExecutingScriptNameStr.substr(0, lastForwardSlash + 1); diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 13dbeba59..b9cd119b5 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -20,6 +20,7 @@ #include "Constants.h" #include "File.h" #include "HttpLoader.h" +#include "ModuleUrl.h" #include "Util.h" #include "Utils.h" #include "WorkerInspectorClient.h" @@ -316,7 +317,7 @@ std::string MaybeRewriteSourceMapURL(const std::string& message) { std::string path; if (sourceMapURL.rfind("file://", 0) == 0) { - path = sourceMapURL.substr(strlen("file://")); + path = FileModulePath(sourceMapURL); } else if (sourceMapURL[0] == '/') { path = sourceMapURL; } else { @@ -325,7 +326,7 @@ std::string MaybeRewriteSourceMapURL(const std::string& message) { if (scriptUrl.rfind("file://", 0) != 0) { return message; } - std::string scriptPath = scriptUrl.substr(strlen("file://")); + std::string scriptPath = FileModulePath(scriptUrl); auto lastSlash = scriptPath.rfind('/'); if (lastSlash == std::string::npos) { return message; @@ -995,7 +996,7 @@ std::string JsV8InspectorClient::HandleLoadNetworkResource(long long msgId, cons if (url.rfind(kSourceMapScheme, 0) == 0) { path = url.substr(strlen(kSourceMapScheme)); } else if (url.rfind("file://", 0) == 0) { - path = url.substr(strlen("file://")); + path = FileModulePath(url); } else { // Reply with a protocol error (not success:false) so DevTools falls // back to loading the resource from the frontend host, which is the diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index bb17511a7..1fba2fa3b 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -1053,7 +1053,8 @@ Local ModuleInternal::LoadData(Isolate* isolate, const string& path) { return json; } -MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const std::string& path) { +MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const std::string& path, + const std::string& query) { // The resolver only ever hands over a path it already probed, but the ENTRY // routes (app main, worker main) reach here straight from the caller's // specifier — so the existence check has to live here, or a missing entry @@ -1063,7 +1064,7 @@ MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const s throw NativeScriptException("Cannot find module " + path); } - string url = ReportedModuleUrl(path); + string url = ReportedModuleUrl(path + query); // An exists-but-unreadable file, or one deleted between the stat above and // the open, reads as "" — which compiles into a perfectly valid empty // module unless the failure is told apart from an empty file here. diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.h b/test-app/runtime/src/main/cpp/ModuleInternal.h index b2e17ac39..0ad2aaf38 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.h +++ b/test-app/runtime/src/main/cpp/ModuleInternal.h @@ -125,9 +125,12 @@ class ModuleInternal { * and the result is empty; a NativeScriptException is thrown instead when the * file does not exist, cannot be read, or the compile could not be set up. * This is the resolver's file loader: the resolver must only ever hand V8 a - * compiled module — evaluation order belongs to V8. + * compiled module — evaluation order belongs to V8. `query` is the module + * key's query: it is part of the reported URL (script origin, + * import.meta.url), never of the file read or of the code cache's name. */ - static v8::MaybeLocal CompileFileEsModule(v8::Isolate* isolate, const std::string& path); + static v8::MaybeLocal CompileFileEsModule(v8::Isolate* isolate, const std::string& path, + const std::string& query = std::string()); /* * The entry module's still-pending evaluation promise, or empty when diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 6a608d0ce..5a276ca7d 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -806,7 +806,7 @@ std::string CanonicalizeRegistryKey(const std::string& key) { registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { - registryKey = NormalizePath(FileURLToPath(key)); + registryKey = NormalizePath(FileURLToPath(key)) + ModuleQuery(key); classification = "file-url"; } else if (StartsWith(key, "blob:")) { registryKey = key; @@ -823,7 +823,10 @@ std::string CanonicalizeRegistryKey(const std::string& key) { classification = "custom-scheme"; traceEvenWithoutChange = true; } else { - registryKey = NormalizePath(key); + // A file module key is its path plus a query; the query's slashes and + // dot segments are not path syntax. + const std::string path = FileModulePath(key); + registryKey = NormalizePath(path) + key.substr(path.size()); } } @@ -1252,13 +1255,16 @@ static std::string LookupInEntries(const ImportMapEntries& entries, // // A scope key matches as a plain prefix of `referrerKey`, the importing // module's canonical registry key: an absolute http(s) URL for a served -// module, or a canonical absolute path for a file. That key is this runtime's -// analogue of the web's resolved referrer URL, which is what scope prefixes -// match there. Ending a scope key with '/' keeps it on a directory boundary, -// exactly as on the web. +// module, or a canonical absolute path for a file — without the query a file +// module's key may carry, so a scope matches every instance of one file alike. +// That key is this runtime's analogue of the web's resolved referrer URL, +// which is what scope prefixes match there. Ending a scope key with '/' keeps +// it on a directory boundary, exactly as on the web. static std::string LookupImportMap(const LoaderVocabulary& vocabulary, const std::string& specifier, - const std::string& referrerKey) { + const std::string& importerKey) { + const std::string importerPath = FileModulePath(importerKey); + const std::string& referrerKey = importerPath.empty() ? importerKey : importerPath; for (const auto& scope : vocabulary.importMap.scopes) { const std::string& prefix = scope.first; if (referrerKey.size() < prefix.size() || @@ -1295,7 +1301,11 @@ struct ModuleResolution { Kind kind = Kind::kUnresolved; std::string url; // kHttp - std::string path; // kFile + std::string path; // kFile: what is read, probed and code-cached + // kFile: the module's identity — the canonical path plus the specifier's + // query (ModuleQuery), so one file imported with two queries is two modules. + std::string key; + std::string query; // kFile: the query `key` carries, '?' included 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 @@ -1453,7 +1463,8 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, const bool specIsRelative = spec[0] == '.'; const bool specIsRootAbs = spec[0] == '/'; - std::string referrer = referrerKey; + const std::string referrerPath = FileModulePath(referrerKey); + std::string referrer = referrerPath.empty() ? referrerKey : referrerPath; if (referrer.empty() && specIsRelative) { TNS_DEBUG(Esm, "[resolver] No referrer for relative '%s' - assuming app root", spec.c_str()); @@ -1477,12 +1488,11 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } // A query or fragment is URL syntax, never part of a file name, so - // `import './x.js?v=1'` names x.js on disk. It is dropped only here, after - // every HTTP outcome has returned: for a served module the query is part of - // its identity (`/ns/asm?path=A` and `/ns/asm` are two modules to the - // server), and that holds for a root-absolute or relative specifier just as - // it does for an absolute URL. Applied in this one seam, so a static import - // and an import() of `./x.js?v=1` name the same file. + // `import './x.js?v=1'` reads x.js. The query stays part of the module's + // identity, in its key, as it is for a served module; the fragment does not. + // Split in this one seam, so a static import and an import() of + // `./x.js?v=1` name the same module. + const std::string query = ModuleQuery(spec); { size_t cut = spec.find_first_of("?#"); if (cut != std::string::npos) { @@ -1592,6 +1602,8 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, if (found) { result.kind = ModuleResolution::Kind::kFile; result.path = NormalizePath(absPath); + result.query = query; + result.key = CanonicalizeRegistryKey(result.path) + query; return result; } @@ -2234,18 +2246,21 @@ static void AsyncGraphOnFetchCompleted( // unregistered is exactly what makes those paths run and report. static void AsyncGraphCompileLocalModule( const std::shared_ptr& load, v8::Local context, - const std::string& path, const std::string& key) { + const ModuleResolution& resolution) { v8::Isolate* isolate = load->isolate; auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; + const std::string& path = resolution.path; + const std::string& key = resolution.key; v8::Local mod; { v8::TryCatch tcCompile(isolate); bool compiled = false; try { - compiled = - tns::ModuleInternal::CompileFileEsModule(isolate, path).ToLocal(&mod); + compiled = tns::ModuleInternal::CompileFileEsModule(isolate, path, + resolution.query) + .ToLocal(&mod); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), ex.GetErrorMessage().c_str()); @@ -2270,11 +2285,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution) { const bool isHttp = resolution.kind == ModuleResolution::Kind::kHttp; const std::string& target = isHttp ? resolution.url : resolution.path; - // The keys CanonicalizeRegistryKey gives these targets, so the walk registers - // every module under the exact key the resolver will look up; a resolved - // URL is already spelled, so only its vocabulary is applied. - const std::string key = - isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : CanonicalizeRegistryKey(target); + // The key the resolver looks the module up by, so the walk registers every + // module under it; a resolved URL is already spelled, so only its + // vocabulary is applied. + const std::string key = isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : resolution.key; if (!load->visited.insert(key).second) return; v8::Isolate* isolate = load->isolate; @@ -2303,7 +2317,7 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, if (EndsWith(target, ".json")) return; v8::Local context = load->context.Get(isolate); if (!context.IsEmpty()) { - AsyncGraphCompileLocalModule(load, context, target, key); + AsyncGraphCompileLocalModule(load, context, resolution); } return; } @@ -2344,18 +2358,22 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, } // Classify a walk root. The root arrives already resolved — an absolute URL -// from the HTTP loader, or a canonical path from LoadESModule — so it needs -// only scheme dispatch, not the full specifier resolution. +// from the HTTP loader, a canonical path from LoadESModule, or a file module's +// registry key from import() — so it needs only scheme dispatch, not the full +// specifier resolution. static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; const std::string httpUrl = NormalizeHttpModuleUrl(root); + const std::string path = FileModulePath(root); if (!httpUrl.empty()) { resolution.kind = ModuleResolution::Kind::kHttp; resolution.url = httpUrl; - } else if (IsFile(root)) { + } else if (!path.empty() && IsFile(path)) { resolution.kind = ModuleResolution::Kind::kFile; - resolution.path = root; + resolution.path = path; + resolution.key = CanonicalizeRegistryKey(root); + resolution.query = root.substr(path.size()); } // Anything else stays kUnresolved: there is nothing to walk, and the // caller's own load path reports why. @@ -2519,7 +2537,8 @@ std::vector GetLoadedModuleUrls() { for (const auto& entry : registry) { const std::string& key = entry.first; - if (key.empty()) continue; + // A file module's key is a path, whatever its query contains. + if (key.empty() || !FileModulePath(key).empty()) continue; if (StartsWith(key, "blob:") || key.find("://") != std::string::npos) { urls.push_back(key); } @@ -2830,7 +2849,7 @@ static v8::MaybeLocal CompileJsonTextAsEsModule( // The filesystem entry point: read the file, then share the wrap. static v8::MaybeLocal CompileJsonAsEsModule( v8::Isolate* isolate, v8::Local context, - const std::string& absPath, const std::string& registryAbsPath) { + const std::string& absPath, const std::string& registryKey) { Runtime* runtime = Runtime::TryGetRuntime(isolate); if (runtime == nullptr) { // Resolve-callback contract: an empty return needs an exception scheduled, @@ -2840,8 +2859,8 @@ static v8::MaybeLocal CompileJsonAsEsModule( return v8::MaybeLocal(); } const std::string jsonText = runtime->ReadFileText(absPath); - return CompileJsonTextAsEsModule(isolate, context, jsonText, registryAbsPath, - ReportedModuleUrl(absPath)); + return CompileJsonTextAsEsModule(isolate, context, jsonText, registryKey, + ReportedModuleUrl(registryKey)); } // ───────────────────────────────────────────────────────────── @@ -2924,11 +2943,11 @@ static v8::MaybeLocal LoadResolvedModule( } const std::string& absPath = resolution.path; - const std::string registryAbsPath = CanonicalizeRegistryKey(absPath); + const std::string& registryKey = resolution.key; // JSON module: compile a synthetic ESM. if (EndsWith(absPath, ".json")) { - return CompileJsonAsEsModule(isolate, context, absPath, registryAbsPath); + return CompileJsonAsEsModule(isolate, context, absPath, registryKey); } // Reuse any live, non-errored registry entry. The resolver never evaluates, @@ -2936,33 +2955,33 @@ static v8::MaybeLocal LoadResolvedModule( // simply rejoins the graph V8 is currently linking — that is how import // cycles terminate, the same way Node/Blink break them with the module-map // self-insert. - auto it = registry.find(registryAbsPath); + auto it = registry.find(registryKey); if (it != registry.end()) { v8::Local existing = it->second.Get(isolate); if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { - TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", absPath.c_str(), + TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", registryKey.c_str(), ModuleStatusToString(existing->GetStatus())); return v8::MaybeLocal(existing); } - RemoveModuleFromRegistry(isolate, absPath); + RemoveModuleFromRegistry(isolate, registryKey); } // Compile + register only — never instantiate or evaluate here. V8 is // instantiating the importer and continues the graph walk by resolving this // module's own requests next; evaluating inside the resolver would run // dependencies in resolver order instead of the spec's evaluation order. - TNS_DEBUG(Esm, "[resolver] -> compile-register %s", absPath.c_str()); + TNS_DEBUG(Esm, "[resolver] -> compile-register %s", registryKey.c_str()); try { v8::Local mod; - if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath) + if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath, resolution.query) .ToLocal(&mod)) { // The compile exception is pending on the isolate; V8 fails the // importer's instantiation with it. return v8::MaybeLocal(); } - UnindexRegistryKey(*moduleState, isolate, registryAbsPath); - registry[registryAbsPath].Reset(isolate, mod); - IndexRegisteredModule(*moduleState, registryAbsPath, mod); + UnindexRegistryKey(*moduleState, isolate, registryKey); + registry[registryKey].Reset(isolate, mod); + IndexRegisteredModule(*moduleState, registryKey, mod); return v8::MaybeLocal(mod); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[resolver] failed to compile '%s' -> '%s'", @@ -3822,7 +3841,7 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( // settles inside the call, so a local-only dynamic import is unchanged — // it neither waits nor touches the looper. if (dynamicResolution.kind == ModuleResolution::Kind::kFile) { - RunModuleGraphLoadPumped(isolate, context, dynamicResolution.path, + RunModuleGraphLoadPumped(isolate, context, dynamicResolution.key, kModuleEvaluateDeadlineSeconds); } @@ -4046,9 +4065,10 @@ void InitializeImportMetaObject(v8::Local context, moduleDirname = modulePath; } } else { - size_t lastSlash = modulePath.find_last_of("/\\"); + const std::string path = FileModulePath(modulePath); + size_t lastSlash = path.find_last_of("/\\"); moduleDirname = - lastSlash == std::string::npos ? "/app" : modulePath.substr(0, lastSlash); + lastSlash == std::string::npos ? "/app" : path.substr(0, lastSlash); } meta->CreateDataProperty( diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp index 910c84ae8..31395f916 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.cpp +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -171,4 +171,34 @@ std::string ReportedModuleUrl(const std::string& keyOrPath) { return "file://" + keyOrPath; } +std::string ModuleQuery(const std::string& specifier) { + if (specifier.find('?') == std::string::npos) { + return std::string(); + } + static const auto base = ada::parse("file:///", nullptr); + auto url = ada::parse(specifier, &base.value()); + if (!url || !url->has_search()) { + return std::string(); + } + const std::string_view search = url->get_search(); + return search.empty() ? std::string("?") : std::string(search); +} + +std::string FileModulePath(const std::string& keyOrUrl) { + if (StartsWith(keyOrUrl, "file://")) { + std::string rest = keyOrUrl.substr(std::char_traits::length("file://")); + // file://host/path names /path; the runtime never spells a host. + if (!rest.empty() && rest[0] != '/') { + const size_t slash = rest.find('/'); + rest = slash == std::string::npos ? std::string() : rest.substr(slash); + } + return rest.substr(0, rest.find('?')); + } + if (keyOrUrl.empty() || HasUrlScheme(keyOrUrl) || + IsHttpRegistryKey(keyOrUrl)) { + return std::string(); + } + return keyOrUrl.substr(0, keyOrUrl.find('?')); +} + } // namespace tns diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.h b/test-app/runtime/src/main/cpp/ModuleUrl.h index 2698b9177..a68388a5a 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.h +++ b/test-app/runtime/src/main/cpp/ModuleUrl.h @@ -46,9 +46,23 @@ bool HasUrlScheme(const std::string& s); // The URL a module or script is reported under (script origin, // import.meta.url, inspector target), from its registry key or path: an // http(s) URL as NormalizeHttpModuleUrl spells it; any other string that -// carries a URL scheme unchanged; a filesystem path as `file://` plus the -// absolute path, `file:///app/` for an empty one. The only place a `file://` -// URL is built from a path. +// carries a URL scheme unchanged; a filesystem path, or a file module key, as +// `file://` plus the absolute path verbatim (not percent-encoded) and then the +// key's query, `file:///app/` for an empty one. The only place a `file://` URL +// is built from a path. std::string ReportedModuleUrl(const std::string& keyOrPath); +// The query of `specifier` as the URL parser serializes it, '?' included, the +// fragment dropped: what a file module's registry key carries after its path. +// "?" for an empty query, which the URL standard keeps distinct from none; +// empty when there is no query. +std::string ModuleQuery(const std::string& specifier); + +// The filesystem path a file module's registry key, or a `file://` URL as +// ReportedModuleUrl spells it, names: everything before the first '?'. Empty +// for an empty string and for a key or URL with any other scheme. The one way +// a module key or script URL is read as a path; a file whose name contains +// '?' is read as path plus query. +std::string FileModulePath(const std::string& keyOrUrl); + } // namespace tns From 4af52ef60e96523efc5a71d6f9a54940d2c11077 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 20:37:46 -0300 Subject: [PATCH 4/6] fix(runtime): keep a '#' in a script path read from a file URL A script's reported file:// URL spells its path verbatim and appends only a module key's query, so a '#' in it is part of a directory or file name, never a fragment. The import() referrer key and createRequire() cut such URLs at the first '#', which resolved a relative import() from a script or module under a directory named with '#' against its parent, and pointed createRequire(import.meta.url) there too. Both now cut at the query only, as FileModulePath does. --- .../assets/app/tests/testDynamicImport.js | 117 ++++++++++++++++++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 26 +--- test-app/runtime/src/main/cpp/js/ns-module.js | 8 +- 3 files changed, 126 insertions(+), 25 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testDynamicImport.js b/test-app/app/src/main/assets/app/tests/testDynamicImport.js index 5a6c58aeb..24c660077 100644 --- a/test-app/app/src/main/assets/app/tests/testDynamicImport.js +++ b/test-app/app/src/main/assets/app/tests/testDynamicImport.js @@ -465,3 +465,120 @@ describe("file module instances per query", function () { }); }); + +// A script's URL spells its path verbatim, so a '#' in a directory name is part +// of the path there, not a fragment. A specifier is a URL, so the fixtures are +// reached through require(), which takes a path. Written at run time: the +// fixture lives in the app's files directory only for the duration of the +// specs. +describe("a script in a directory whose name contains '#'", function () { + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + var fixtureDir = appRoot + "/esm/hash#dir"; + + function writeFile(path, body) { + var writer = new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), "UTF-8"); + try { + writer.write(body); + } finally { + writer.close(); + } + } + + beforeAll(function () { + new java.io.File(fixtureDir).mkdirs(); + writeFile(fixtureDir + "/spawner.js", + "exports.start = function () { return new Worker(\"./w.js\"); };\n"); + writeFile(fixtureDir + "/w.js", "postMessage(\"hash-dir-worker\");\n"); + writeFile(fixtureDir + "/loader.js", + "exports.loadSibling = function () {\n" + + " return import(\"./sibling.mjs\").then(function (m) { return m.name; });\n" + + "};\n" + + "exports.loadModule = function () { return import(\"./module.mjs\"); };\n"); + writeFile(fixtureDir + "/module.mjs", + "import { createRequire } from \"ns:module\";\n" + + "export function loadSibling() {\n" + + " return import(\"./sibling.mjs\").then((m) => m.name);\n" + + "}\n" + + "export function requireSibling() {\n" + + " return createRequire(import.meta.url)(\"./sibling-cjs.js\").name;\n" + + "}\n"); + writeFile(fixtureDir + "/sibling.mjs", "export const name = \"hash-dir-sibling\";\n"); + writeFile(fixtureDir + "/sibling-cjs.js", "exports.name = \"hash-dir-sibling-cjs\";\n"); + }); + + function loader() { + return require(fixtureDir + "/loader.js"); + } + + function fail(done) { + return function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }; + } + + it("resolves a relative import() from a script there", function (done) { + loader().loadSibling().then(function (name) { + expect(name).toBe("hash-dir-sibling"); + done(); + }, fail(done)); + }); + + it("resolves a relative import() from a module there", function (done) { + loader().loadModule().then(function (m) { + return m.loadSibling(); + }).then(function (name) { + expect(name).toBe("hash-dir-sibling"); + done(); + }, fail(done)); + }); + + it("creates a require from a module's import.meta.url there", function (done) { + loader().loadModule().then(function (m) { + expect(m.requireSibling()).toBe("hash-dir-sibling-cjs"); + done(); + }, fail(done)); + }); + + afterAll(function () { + var dirFile = new java.io.File(fixtureDir); + var names = dirFile.list(); + if (names !== null) { + for (var i = 0; i < names.length; i++) { + new java.io.File(dirFile, names[i]).delete(); + } + } + dirFile.delete(); + }); + + it("starts a relative worker from that directory", function (done) { + var worker; + var timer = setTimeout(function () { + if (worker) { + worker.terminate(); + } + expect("no message").toBe("hash-dir-worker"); + done(); + }, 10000); + function finish(actual) { + clearTimeout(timer); + if (worker) { + worker.terminate(); + } + expect(actual).toBe("hash-dir-worker"); + done(); + } + try { + worker = require(fixtureDir + "/spawner.js").start(); + } catch (e) { + finish("threw: " + String((e && e.message) || e)); + return; + } + worker.onerror = function (e) { + finish("error: " + String((e && e.message) || e)); + }; + worker.onmessage = function (msg) { + finish(msg.data); + }; + }, 15000); +}); diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 5a276ca7d..f4c8f8a16 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -142,25 +142,6 @@ static std::string NormalizePath(const std::string& path) { return NormalizeDotSegments(path); } -// Convert a file:// URL to a filesystem path. Handles both file:///a/b and -// file:/a/b variants. Percent-decoding is deliberately omitted — the runtime -// only emits ASCII file:// URLs internally. -static std::string FileURLToPath(const std::string& url) { - if (url.empty()) return url; - if (!StartsWith(url, "file://")) return url; - std::string tail = url.substr(7); - // Strip host component when present (file://host/path → /path). NS never - // emits a host, but be tolerant. - if (!tail.empty() && tail[0] != '/') { - size_t slash = tail.find('/'); - tail = (slash == std::string::npos) ? std::string() : tail.substr(slash); - } - // Drop query and fragment — these have no meaning for filesystem paths. - size_t cut = tail.find_first_of("?#"); - if (cut != std::string::npos) tail = tail.substr(0, cut); - return NormalizePath(tail); -} - // Forward declarations for helpers referenced before their definitions. static const char* ModuleStatusToString(v8::Module::Status status); static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate); @@ -806,7 +787,12 @@ std::string CanonicalizeRegistryKey(const std::string& key) { registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { - registryKey = NormalizePath(FileURLToPath(key)) + ModuleQuery(key); + // The path is spelled verbatim, so a '#' before the query is part of it; + // only after the query does one start a fragment. + const size_t queryAt = key.find('?'); + registryKey = NormalizePath(FileModulePath(key)) + + (queryAt == std::string::npos ? std::string() + : ModuleQuery(key.substr(queryAt))); classification = "file-url"; } else if (StartsWith(key, "blob:")) { registryKey = key; diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index 866d0b5ed..227fa4e3b 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -49,15 +49,13 @@ function fileUrlToPath(href) { } rest = StringPrototypeSlice(rest, authorityEnd); - // The query and fragment are URL syntax, never part of the path. + // The query is URL syntax, never part of the path. A '#' is: the runtime + // spells a module's path verbatim after file:// (import.meta.url), so there + // it names a directory or file, and such a URL never carries a fragment. const queryAt = StringPrototypeIndexOf(rest, "?"); if (queryAt >= 0) { rest = StringPrototypeSlice(rest, 0, queryAt); } - const hashAt = StringPrototypeIndexOf(rest, "#"); - if (hashAt >= 0) { - rest = StringPrototypeSlice(rest, 0, hashAt); - } try { return decodeURIComponent(rest); From b6c83dee863627cac4c7fa686668239de3d91f67 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 20:38:15 -0300 Subject: [PATCH 5/6] docs(runtime): file module identity, '#' in script paths and blob URL lookup Describe the query as part of a file module's identity and what keeps using the path, a '#' in a script's path, the import map applied once by import(), and how import() looks a blob URL up. --- docs/ns-builtin-modules.md | 63 ++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index b4112c60f..d2ca982e7 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -487,10 +487,11 @@ const stale = getLoadedModuleUrls().filter((url) => url.includes("/src/")); invalidateModules(stale); ``` -`getLoadedModuleUrls()` reports the **URL-like** keys only: registry entries -that are `blob:`-prefixed or contain `://`. A module keyed by a plain -filesystem path is not in the result, so the eviction set a dev client computes -from it covers served modules rather than the app's own bundled files. +`getLoadedModuleUrls()` reports the **URL-like** keys only: `blob:` URLs and +http(s) URLs. A file module, keyed by its filesystem path and any query it was +imported with, is never in the result, even when that query holds `://`, so the +eviction set a dev client computes from it covers served modules rather than +the app's own bundled files. `createRequire` gives a module-relative `require` from anywhere, including an ES module that has no `__filename`: @@ -565,7 +566,8 @@ ending in `/` must have a target ending in `/`. A **scope key is matched as a plain prefix of the importing module's canonical registry key** — an absolute `http(s)` URL for a served module, or a canonical -absolute path for a file on disk. That key is this runtime's analogue of the +absolute path for a file on disk, without the query a file module may have been +imported with. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. An `http(s)` scope key is spelled the way registry keys are (see [Registry canonicalization](#registry-canonicalization)) when the map is @@ -811,16 +813,57 @@ 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 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 +scheme (`data:`, `file:/x`) is never looked up on disk. 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'` and `import('pkg?x')` alike look -`pkg?x` up in the import map as written. An import-map target is never looked -up in the map a second time, by a static import or by `import()`. +From a file module, `import 'pkg?x'` and `import('pkg?x')` both look `pkg?x` +up in the import map, exactly as written: an entry for `pkg` does not match it, +while a `pkg/` prefix entry matches `pkg/x.js?v=1`. A query or fragment is +dropped only when a file path is derived, so `./x.js?v=1` and `./x.js#f` load +`x.js`. + +#### File module identity + +As in browsers and Node, the query is part of a file module's identity: +`./x.js?v=1`, `./x.js?v=2` and `./x.js` are three instances of one file, each +evaluated once, whether imported statically or with `import()`; an import-map +target's query counts the same way. `./x.js?` is a fourth: the URL standard +keeps an empty query distinct from none. The fragment is not part of the +identity — `./x.js#a` and `./x.js#b` are the `./x.js` instance — matching how +this loader keys http(s) modules. The query is kept as the URL parser +serializes it. + +Inside such a module, `import.meta.url` carries the query +(`file:///x.js?v=1`) while `import.meta.dirname` does not, and +relative imports, `createRequire(import.meta.url)`, `new Worker('./w.js')` and +import-map scopes resolve exactly as for the module without a query. Anything +that names a file without a specifier — the entry module, a worker's script, +`require()` of an ES module — loads the instance without a query. The code +cache is per file, shared by every instance. File modules are not listed by +`getLoadedModuleUrls()`, with or without a query, and `invalidateModules()` +given a `file://` URL with a query drops only that instance. + +A module's `file://` URL spells its path verbatim after `file://`, so a `#` in +a directory or file name is part of the path there, not a fragment: a relative +`import()`, `createRequire(import.meta.url)` and `new Worker('./w.js')` from a +script under `a#b/` resolve inside `a#b/`. A `?` in a file name is not +supported: wherever a module's key or URL is read as a path, a `?` starts its +query. + +`import()` resolves its specifier once, by the same rules and against the same +importer as a static import from the module that calls it, so the import map is +applied once: an entry's target is never looked up in the map again, and a +`./x` or `../x` that names no file is reported as written +(`Cannot find module './x' (tried )`), as a static import reports it. + +`import()` of a `blob:` URL loads from the blob store, from any importer. The +store is looked up the way the File API resolves a blob URL: without the +fragment and with the query, so `blobUrl + '#f'` loads the blob and +`blobUrl + '?x'` rejects with `Blob not found`. A blob URL with and without a +fragment is one module. A static import of a `blob:` URL does not resolve. ### The `require()` specifier From 12a808d26ea8c545703f139b137b6cffa21d14d3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 3 Dec 2026 02:44:40 -0300 Subject: [PATCH 6/6] fix(runtime): createRequire() ignores a URL object's fragment A URL object's href is serialized, so a '#' in it always starts the fragment. Cut there before reading the path; a URL string still keeps a '#' as part of the path. --- test-app/app/src/main/assets/app/tests/testCreateRequire.js | 6 ++++++ test-app/runtime/src/main/cpp/js/ns-module.js | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/test-app/app/src/main/assets/app/tests/testCreateRequire.js b/test-app/app/src/main/assets/app/tests/testCreateRequire.js index d4f4c785d..832a97ab9 100644 --- a/test-app/app/src/main/assets/app/tests/testCreateRequire.js +++ b/test-app/app/src/main/assets/app/tests/testCreateRequire.js @@ -89,6 +89,12 @@ describe("createRequire", function () { expect(req("./target.js").tag).toBe("createrequire-target"); }); + it("ignores a URL object's fragment", function () { + var req = nsModule.createRequire( + new URL("file://" + fixtureDir + "/anything.js#fragment/child")); + expect(req("./target.js").tag).toBe("createrequire-target"); + }); + it("still resolves ~ specifiers against the app root", function () { var req = nsModule.createRequire(fixtureDir + "/anything.js"); expect(req("~/esm/createrequire/target.js").tag).toBe("createrequire-target"); diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index 227fa4e3b..3bef40692 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -75,7 +75,10 @@ function requireBaseDir(filenameOrURL) { if (typeof href !== "string") { throw new TypeError(CREATE_REQUIRE_ERROR); } - filepath = urlStringToPath(href); + // A URL object's href is serialized, so its first '#' starts the + // fragment; a '#' in the path itself is spelled %23. + const hashAt = StringPrototypeIndexOf(href, "#"); + filepath = urlStringToPath(hashAt >= 0 ? StringPrototypeSlice(href, 0, hashAt) : href); } else if (typeof filenameOrURL !== "string") { throw new TypeError(CREATE_REQUIRE_ERROR); } else if (StringPrototypeStartsWith(filenameOrURL, "/")) {