Skip to content

Commit 28850ec

Browse files
committed
fix(runtime): drop the legacy module URL forms
Nothing in the runtime feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the unwraps in CanonicalizeHttpUrlKey, CanonicalizeRegistryKey and ModuleInternal, HttpUrlEmbeddedInPath and RepairCollapsedUrlScheme go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://… is a file: URL that names no file, so import() of it rejects without fetching. A dynamic import() from an HTTP module that the resolver left unresolved now rejects instead of re-resolving in the tail, which path-joined an http referrer the URL parser rejects (an IPv6 zone id) into a collapsed URL. An http(s) worker script is labelled with its own URL in the inspector. The unused adjustedRegistryKey is gone.
1 parent ed556e1 commit 28850ec

6 files changed

Lines changed: 86 additions & 125 deletions

File tree

‎NativeScript/runtime/HttpLoader.h‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,6 @@ struct CanonicalizationConfig {
5858
// module under exactly one URL and never varies it for freshness.
5959
std::string CanonicalizeHttpUrlKey(const std::string& url);
6060

61-
// Repairs `http:/host` (one slash) back to `http://host`. Upstream path joins
62-
// collapse the double slash, and every key derivation has to undo it BEFORE it
63-
// tests the scheme — otherwise the collapsed form fails the test, is passed
64-
// through verbatim, and the same module ends up with two registry identities:
65-
// one from the resolver (which repairs) and one from whatever came in through
66-
// invalidateModules or a cache-bust mark (which did not).
67-
std::string RepairCollapsedUrlScheme(const std::string& url);
68-
6961
// What a module response turned out to be. Decided once, by the shared
7062
// classifier, for whichever transport produced the response.
7163
enum class ModuleResponseKind {

‎NativeScript/runtime/HttpLoader.mm‎

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -128,40 +128,14 @@ bool IsRemoteUrlAllowed(const std::string& url) {
128128
// URLs touched before the client configures anything (the local trampoline's
129129
// clean `/ns/core/*` imports) carry no query, so they canonicalize identically
130130
// under any vocabulary.
131-
std::string RepairCollapsedUrlScheme(const std::string& url) {
132-
if (StartsWith(url, "http:/") && !StartsWith(url, "http://")) {
133-
std::string repaired = url;
134-
repaired.insert(5, "/");
135-
return repaired;
136-
}
137-
if (StartsWith(url, "https:/") && !StartsWith(url, "https://")) {
138-
std::string repaired = url;
139-
repaired.insert(6, "/");
140-
return repaired;
141-
}
142-
return url;
143-
}
144-
145131
std::string CanonicalizeHttpUrlKey(const std::string& url) {
146132
// Per-isolate vocabulary, so this runs on the isolate's own thread. Fetch
147133
// threads never reach here — they carry keys computed for them.
148134
const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate();
149-
// Some loaders wrap HTTP module URLs as file://http(s)://...
150-
// Repaired before any scheme test, so a collapsed `http:/host` keys the same
151-
// as the URL it means rather than passing through untouched.
152-
std::string normalizedUrl = RepairCollapsedUrlScheme(url);
153-
// The wrapper is tested on the one-slash forms as well: a path join can
154-
// collapse the scheme INSIDE the wrapper (`file://http:/host/x`), which
155-
// matches neither the two-slash unwrap nor the repair above (whose prefix is
156-
// `file://`, not `http:/`) and would otherwise key as its own identity.
157-
if (StartsWith(normalizedUrl, "file://http:/") || StartsWith(normalizedUrl, "file://https:/")) {
158-
normalizedUrl = RepairCollapsedUrlScheme(normalizedUrl.substr(strlen("file://")));
159-
}
160-
const std::string httpUrl = NormalizeHttpModuleUrl(normalizedUrl);
161-
if (httpUrl.empty()) {
162-
return normalizedUrl;
163-
}
164-
normalizedUrl = httpUrl;
135+
const std::string normalizedUrl = NormalizeHttpModuleUrl(url);
136+
if (normalizedUrl.empty()) {
137+
return url;
138+
}
165139
// Drop fragment entirely
166140
size_t hashPos = normalizedUrl.find('#');
167141
std::string noHash =

‎NativeScript/runtime/ModuleInternal.mm‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -76,23 +76,12 @@ static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy p
7676
return options;
7777
}
7878

79-
static inline bool StartsWith(const std::string& value, const char* prefix) {
80-
size_t n = strlen(prefix);
81-
return value.size() >= n && value.compare(0, n, prefix) == 0;
79+
static bool IsHttpModulePath(const std::string& path) {
80+
return !NormalizeHttpModuleUrl(path).empty();
8281
}
8382

84-
// `path` as an http(s) module URL, or empty when it names none.
85-
static std::string HttpModuleUrl(const std::string& path) {
86-
if (StartsWith(path, "file://http://") || StartsWith(path, "file://https://")) {
87-
return NormalizeHttpModuleUrl(path.substr(strlen("file://")));
88-
}
89-
return NormalizeHttpModuleUrl(path);
90-
}
91-
92-
static bool IsHttpModulePath(const std::string& path) { return !HttpModuleUrl(path).empty(); }
93-
9483
static std::string CanonicalizeModulePath(const std::string& path) {
95-
const std::string url = HttpModuleUrl(path);
84+
const std::string url = NormalizeHttpModuleUrl(path);
9685
if (!url.empty()) {
9786
return CanonicalizeHttpUrlKey(url);
9887
}
@@ -238,7 +227,7 @@ static inline bool StartsWith(const std::string& value, const char* prefix) {
238227
if (IsESModule(path) || isHttpModule) {
239228
Local<Value> moduleNamespace;
240229
if (isHttpModule) {
241-
TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str());
230+
TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str());
242231
}
243232
try {
244233
// The entry runs before this thread's event loop does, so its graph can
@@ -265,7 +254,7 @@ throw NativeScriptException(
265254
"console for the matching [esm][evaluate][promise-timeout] entry.");
266255
}
267256
if (isHttpModule) {
268-
TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str());
257+
TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str());
269258
}
270259
return;
271260
}
@@ -1479,7 +1468,7 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio
14791468
const ModuleEvaluationOptions& options) {
14801469
bool isHttpModule = IsHttpModulePath(path);
14811470
std::string canonicalPath = CanonicalizeModulePath(path);
1482-
std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath;
1471+
std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath;
14831472
auto context = isolate->GetCurrentContext();
14841473
auto* registryPtr = ModuleRegistryFor(isolate);
14851474
if (registryPtr == nullptr) {

‎NativeScript/runtime/ModuleInternalCallbacks.mm‎

Lines changed: 15 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -765,22 +765,19 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string&
765765
return StartsWith(registryKey, "node:") || StartsWith(registryKey, "blob:");
766766
}
767767
768-
static std::string CanonicalizeRegistryKey(const std::string& rawKey) {
769-
if (rawKey.empty()) {
770-
return rawKey;
768+
static std::string CanonicalizeRegistryKey(const std::string& key) {
769+
if (key.empty()) {
770+
return key;
771771
}
772772
773-
// Before any scheme test: a collapsed `http:/host` would otherwise fail the
774-
// http tests below, fall through as a custom scheme, and give the module a
775-
// second identity that never matches the resolver's.
776-
const std::string key = RepairCollapsedUrlScheme(rawKey);
777-
778773
std::string registryKey;
779774
const char* classification = "path";
780775
bool traceEvenWithoutChange = false;
781776
782-
if (!NormalizeHttpModuleUrl(key).empty() || StartsWith(key, "file://http://") ||
783-
StartsWith(key, "file://https://")) {
777+
// Before any other scheme test: an http(s) URL in a spelling other than the
778+
// key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme
779+
// and give the module a second identity.
780+
if (!NormalizeHttpModuleUrl(key).empty()) {
784781
registryKey = CanonicalizeHttpUrlKey(key);
785782
classification = "http";
786783
} else if (StartsWith(key, "file://")) {
@@ -1592,28 +1589,6 @@ static bool IsRegularFile(const std::string& p) {
15921589
return (st.st_mode & S_IFMT) == S_IFREG;
15931590
}
15941591
1595-
// Rebuild an HTTP URL a path join swallowed ('/app/http:/host/x' →
1596-
// 'http://host/x'), or empty when the path embeds none.
1597-
static std::string HttpUrlEmbeddedInPath(const std::string& p) {
1598-
size_t pos1 = p.find("/http:/");
1599-
size_t pos2 = p.find("/https:/");
1600-
size_t pos = std::min(pos1 == std::string::npos ? SIZE_MAX : pos1,
1601-
pos2 == std::string::npos ? SIZE_MAX : pos2);
1602-
if (pos == SIZE_MAX) {
1603-
return "";
1604-
}
1605-
std::string tail = p.substr(pos + 1);
1606-
if (StartsWith(tail, "http:/") && !StartsWith(tail, "http://")) {
1607-
tail.insert(5, "/");
1608-
} else if (StartsWith(tail, "https:/") && !StartsWith(tail, "https://")) {
1609-
tail.insert(6, "/");
1610-
}
1611-
if (!IsHttpRegistryKey(tail)) {
1612-
return "";
1613-
}
1614-
return tail;
1615-
}
1616-
16171592
enum class ImportMapLookup {
16181593
kApply,
16191594
kSkip, // the specifier is an existing module's origin, which the map never rewrites
@@ -1636,10 +1611,7 @@ static ModuleResolution ResolveSpecifierToPath(
16361611
return result;
16371612
}
16381613
1639-
// Repair 'http:/host' (single slash) left by upstream path joins, so the URL
1640-
// takes the HTTP path instead of becoming '/app/http:/host'. Shared with the
1641-
// key derivations, so the resolver and the registry agree on one identity.
1642-
std::string spec = RepairCollapsedUrlScheme(rawSpec);
1614+
std::string spec = rawSpec;
16431615
16441616
TNS_DEBUG(Esm, "[resolver][spec] %s", spec.c_str());
16451617
@@ -1850,14 +1822,6 @@ static ModuleResolution ResolveSpecifierToPath(
18501822
for (const std::string& baseCandidate : candidateBases) {
18511823
absPath = NormalizePath(baseCandidate);
18521824
1853-
std::string embedded = HttpUrlEmbeddedInPath(absPath);
1854-
if (!embedded.empty()) {
1855-
TNS_DEBUG(Esm, "[resolver][http-embedded] %s -> %s", absPath.c_str(), embedded.c_str());
1856-
result.kind = ModuleResolution::Kind::kHttp;
1857-
result.url = embedded;
1858-
return result;
1859-
}
1860-
18611825
bool existsNow = IsRegularFile(absPath);
18621826
TNS_DEBUG(Esm, "[resolver] %s -> %s", absPath.c_str(), existsNow ? "file" : "missing");
18631827
@@ -3074,9 +3038,8 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
30743038
// map. A local origin (`file:///app/…`) still has to become the absolute
30753039
// app path the registry keys by, or no scope would match it.
30763040
const std::string resourceName(*resourceUtf8);
3077-
const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName);
3078-
if (!NormalizeHttpModuleUrl(resourceUrl).empty()) {
3079-
dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl);
3041+
if (!NormalizeHttpModuleUrl(resourceName).empty()) {
3042+
dynamicReferrerKey = CanonicalizeRegistryKey(resourceName);
30803043
} else {
30813044
const ModuleResolution referrer =
30823045
ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip);
@@ -3669,12 +3632,12 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
36693632
return scope.Escape(resolver->GetPromise());
36703633
}
36713634
3672-
// The tail below re-resolves with no referrer, which would let an HTTP
3673-
// importer's unmapped other-scheme specifier ('data:', 'file:/x') reach
3674-
// '<app>/<spec>' on disk. Only explicit file:// URLs and import-map
3675-
// targets may continue into it.
3635+
// The tail below re-resolves with no referrer and joins relative
3636+
// specifiers onto the referrer as a path, which would let an HTTP
3637+
// importer's specifier reach '<app>/<spec>' on disk or path-join an http
3638+
// URL. Only explicit file:// URLs may continue into it.
36763639
if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kUnresolved &&
3677-
normalizedSpec == rawSpec && !StartsWith(normalizedSpec, "file://")) {
3640+
!StartsWith(normalizedSpec, "file://")) {
36783641
resolver
36793642
->Reject(context, v8::Exception::Error(tns::ToV8String(
36803643
isolate, UnresolvedModuleMessage(dynamicResolution))))
@@ -3745,9 +3708,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
37453708
TNS_DEBUG(Esm, "[dyn-import][resolver-call] raw=%s normalized=%s adjusted=%s",
37463709
rawSpec.c_str(), normalizedSpec.c_str(), cAdj);
37473710
}
3748-
v8::String::Utf8Value adjustedSpecUtf8(isolate, adjustedSpecifier);
3749-
std::string adjustedRegistryKey =
3750-
*adjustedSpecUtf8 ? CanonicalizeRegistryKey(*adjustedSpecUtf8) : std::string();
37513711
if (maybeModule.IsEmpty()) {
37523712
if (resolveTc.HasCaught()) {
37533713
// Reject the promise with the thrown exception so callers don't hang

‎NativeScript/runtime/WorkerWrapper.mm‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include "DataWrapper.h"
55
#include "ErrorEvents.h"
66
#include "Helpers.h"
7+
#include "ModuleUrl.h"
78
#include "ObjectManager.h"
89
#include "Runtime.h"
910
#include "RuntimeConfig.h"
@@ -484,7 +485,9 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even
484485
}
485486
486487
// Same url scheme the module loader reports in Debugger.scriptParsed.
487-
std::string url = "file://" + ReplaceAll(scriptPath, RuntimeConfig.BaseDir, "");
488+
std::string url = NormalizeHttpModuleUrl(scriptPath).empty()
489+
? "file://" + ReplaceAll(scriptPath, RuntimeConfig.BaseDir, "")
490+
: scriptPath;
488491
489492
auto* client =
490493
new v8_inspector::WorkerInspectorClient(this->workerId_, isolate, CFRunLoopGetCurrent(), url);

‎TestRunner/app/tests/HttpEsmLoaderTests.js‎

Lines changed: 57 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1934,6 +1934,32 @@ describe("HTTP ESM Loader", function() {
19341934
});
19351935
});
19361936

1937+
it("rejects an import() whose import-map target resolves to nothing", function (done) {
1938+
var origin = getHostOrigin();
1939+
if (!origin) {
1940+
pending("REPORT_BASEURL not set; skipping host HTTP tests");
1941+
done();
1942+
return;
1943+
}
1944+
nsModule.configureLoader({
1945+
importMap: {
1946+
imports: {
1947+
"ns-tail-a": "ns-tail-b",
1948+
"ns-tail-b": "~/tests/esm/query-map/literal.mjs",
1949+
},
1950+
},
1951+
});
1952+
importer(origin, "tail").then(function (mod) {
1953+
return rejectionMessage(mod.load("ns-tail-a"));
1954+
}).then(function (message) {
1955+
expect(message).toContain("Cannot find module 'ns-tail-b'");
1956+
done();
1957+
}).catch(function (error) {
1958+
expect("rejected: " + formatError(error)).toBe("resolved");
1959+
done();
1960+
});
1961+
});
1962+
19371963
it("keeps the importer's origin as written when the query or fragment is empty",
19381964
function (done) {
19391965
var origin = getHostOrigin();
@@ -2346,6 +2372,30 @@ describe("HTTP ESM Loader", function() {
23462372
});
23472373
});
23482374

2375+
it("are not unwrapped from a file:// URL", function (done) {
2376+
var origin = getHostOrigin();
2377+
if (!origin) {
2378+
pending("REPORT_BASEURL not set; skipping host HTTP tests");
2379+
done();
2380+
return;
2381+
}
2382+
var target = "/esm/resolve/file-abs/wrapped.mjs";
2383+
import("file://" + origin + target).then(function () {
2384+
expect("resolved").toBe("rejected");
2385+
}, function (error) {
2386+
expect(String((error && error.message) || error)).toContain("Cannot find module");
2387+
}).then(function () {
2388+
return import(origin + "/esm/request-stats.json?target=" +
2389+
encodeURIComponent(target));
2390+
}).then(function (stats) {
2391+
expect(stats.default.count).toBe(0);
2392+
done();
2393+
}).catch(function (error) {
2394+
expect("rejected: " + formatError(error)).toBe("resolved");
2395+
done();
2396+
});
2397+
});
2398+
23492399
it("are refused by require() whatever their scheme's case", function () {
23502400
["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) {
23512401
var message = "";
@@ -2473,26 +2523,19 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () {
24732523
"https://cdn.example.com/lib.js?token=abc");
24742524
});
24752525

2476-
// Upstream path joins collapse `http://` to `http:/`. Every key
2477-
// derivation repairs that before it tests the scheme, so a key that
2478-
// arrives collapsed — through invalidateModules or a cache-bust mark —
2479-
// lands on the same identity the resolver produces.
2526+
// The URL parser reads `http:/host` as `http://host`, so a key that
2527+
// arrives collapsed, through invalidateModules say, lands on the same
2528+
// identity the resolver produces.
24802529
it("repairs a collapsed scheme to one identity", function () {
24812530
checkKey("http:/h/ns/core", "http://h/ns/core");
24822531
checkKey("https:/h/ns/core", "https://h/ns/core");
2483-
// Already well-formed keys are untouched by the repair.
24842532
checkKey("http://h/ns/core", "http://h/ns/core");
24852533
});
24862534

2487-
// Some loaders hand the URL over wrapped as file://http(s)://…, and a
2488-
// path join can collapse the scheme inside that wrapper too. Unwrapping
2489-
// and repairing have to compose, or the wrapped-collapsed form becomes
2490-
// a third identity for the same module.
2491-
it("repairs a collapsed scheme inside a file:// wrapper", function () {
2492-
checkKey("file://http:/h/ns/core", "http://h/ns/core");
2493-
checkKey("file://https:/h/ns/core", "https://h/ns/core");
2494-
// The well-formed wrapper still unwraps to the same key.
2495-
checkKey("file://http://h/ns/core", "http://h/ns/core");
2535+
it("does not read an http URL inside a file:// URL as an http key", function () {
2536+
checkKey("file://http:/h/ns/core", "file://http:/h/ns/core");
2537+
checkKey("file://https:/h/ns/core", "file://https:/h/ns/core");
2538+
checkKey("file://http://h/ns/core", "file://http://h/ns/core");
24962539
});
24972540

24982541
it("treats module identity as literally the URL — no path-tag collapses", function () {

0 commit comments

Comments
 (0)