Skip to content

Commit 2da0e36

Browse files
committed
feat(vite)!: serve dynamic imports as Vite writes them
The runtimes resolve relative and root-relative specifiers of a module loaded over HTTP against that module's URL, static and dynamic, with the query kept (NativeScript/ios#586; Android 9.1.x). The dev server no longer writes its origin into served modules, so their bodies, ETags and cache headers no longer depend on it, and non-literal relative imports work. Runtime builtins are still restored in responses. The HMR client's own update import stays absolute: Vite's import analysis wraps it in injectQuery, which would add `import` to a root-relative URL and change the module's identity. BREAKING CHANGE: on iOS and visionOS, lazy imports under Vite HMR need a runtime with NativeScript/ios#586.
1 parent c844252 commit 2da0e36

9 files changed

Lines changed: 60 additions & 177 deletions

File tree

‎packages/vite/hmr/client/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@ export function createNsHmrRuntime(options: NsHmrStartOptions, deps: NsHmrRuntim
172172
client.attach(transport, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport }: Update): Promise<ModuleNamespace> {
173173
const [acceptedPathWithoutQuery, query] = acceptedPath.split('?');
174174
if (acceptedPath === entryPath) entryImportStarted = true;
175-
// The runtime resolves a non-`http(s)://` dynamic specifier on the filesystem and drops its query.
175+
// Absolute: Vite's import analysis wraps the `import()` below in `injectQuery`, which adds
176+
// `import` to a root-relative URL, and the query is part of the module's identity.
176177
const importPromise = importModule(`${origin}${acceptedPathWithoutQuery}?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`);
177178
if (isWithinCircularImport) {
178179
importPromise.catch(() => {

‎packages/vite/hmr/client/thin-vite-client.spec.ts‎

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
1+
import { beforeEach, describe, expect, it, vi } from 'vitest';
22
import { addTaggedAdditionalCSS, Application, removeTaggedAdditionalCSS } from '@nativescript/core';
33
import { injectQuery, removeStyle, updateStyle } from './thin-vite-client.js';
4-
import { nsDev } from '../shared/runtime/dev-globals.js';
54

65
vi.mock('@nativescript/core', () => ({ addTaggedAdditionalCSS: vi.fn(), removeTaggedAdditionalCSS: vi.fn(), Application: { getRootView: vi.fn() } }));
76

@@ -59,30 +58,14 @@ describe('updateStyle / removeStyle', () => {
5958
});
6059
});
6160

62-
const ORIGIN = 'http://192.168.1.5:5173';
63-
6461
describe('injectQuery', () => {
65-
afterEach(() => {
66-
delete nsDev().httpOrigin;
67-
});
68-
69-
it('makes a root-relative URL absolute on the dev-server origin, query first as in Vite', () => {
70-
nsDev().httpOrigin = `${ORIGIN}/`;
71-
expect(injectQuery('/src/data.json?raw#x', 'import')).toBe(`${ORIGIN}/src/data.json?import&raw#x`);
62+
it('puts the query first, as Vite does, on root-relative and relative URLs', () => {
63+
expect(injectQuery('/src/data.json?raw#x', 'import')).toBe('/src/data.json?import&raw#x');
64+
expect(injectQuery('./a.json', 'import')).toBe('./a.json?import');
7265
});
7366

7467
it('leaves absolute and bare specifiers untouched', () => {
75-
nsDev().httpOrigin = ORIGIN;
76-
expect(injectQuery(`${ORIGIN}/src/a.ts?t=1`, 'import')).toBe(`${ORIGIN}/src/a.ts?t=1`);
68+
expect(injectQuery('http://192.168.1.5:5173/src/a.ts?t=1', 'import')).toBe('http://192.168.1.5:5173/src/a.ts?t=1');
7769
expect(injectQuery('@nativescript/core', 'import')).toBe('@nativescript/core');
7870
});
79-
80-
it('injects into a relative URL without making it absolute', () => {
81-
nsDev().httpOrigin = ORIGIN;
82-
expect(injectQuery('./a.json', 'import')).toBe('./a.json?import');
83-
});
84-
85-
it('stays root-relative without a known origin', () => {
86-
expect(injectQuery('/src/a.json', 'import')).toBe('/src/a.json?import');
87-
});
8871
});

‎packages/vite/hmr/client/thin-vite-client.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
* own path), and the hot contexts must live in one module instance.
99
*/
1010
import { addTaggedAdditionalCSS, removeTaggedAdditionalCSS } from '@nativescript/core';
11-
import { nsDev } from '../shared/runtime/dev-globals.js';
1211
import { scheduleRestyle } from './restyle.js';
1312

1413
export { createHotContext, registerEntryBoundary } from './hot-state.js';
@@ -30,11 +29,5 @@ export function injectQuery(url: string, queryToInject: string): string {
3029
}
3130
const pathname = url.replace(/[?#].*$/, '');
3231
const { search, hash } = new URL(url, 'http://vite.dev');
33-
const injected = `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ''}${hash || ''}`;
34-
// Vite wraps non-literal dynamic `import()` specifiers in this call. The
35-
// runtime resolves a non-`http(s)://` dynamic specifier on the filesystem
36-
// and drops its query, so a root-relative one gets the dev-server origin.
37-
// A relative one can't: the importer's URL isn't known here.
38-
const origin = nsDev().httpOrigin;
39-
return injected[0] === '/' && injected[1] !== '/' && origin ? `${origin.replace(/\/$/, '')}${injected}` : injected;
32+
return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ''}${hash || ''}`;
4033
}

‎packages/vite/hmr/server/device-imports.spec.ts‎

Lines changed: 16 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,22 @@
11
import { EventEmitter } from 'node:events';
22
import { describe, expect, it } from 'vitest';
3-
import { restoreOriginETags, rewriteDeviceImports, rewriteDeviceImportsInResponse } from './device-imports.js';
4-
5-
const ORIGIN = 'http://192.168.1.2:5173';
3+
import { rewriteDeviceImports, rewriteDeviceImportsInResponse } from './device-imports.js';
64

75
describe('rewriteDeviceImports', () => {
8-
it('prefixes the origin to root-relative literal dynamic imports, keeping quotes and query', () => {
9-
const code = `const a = () => import('/src/lazy.ts?t=1700000000000');\nconst b = () => import("/@fs/repo/x.js");\n`;
10-
expect(rewriteDeviceImports(code, `${ORIGIN}/`)).toBe(`const a = () => import('${ORIGIN}/src/lazy.ts?t=1700000000000');\nconst b = () => import("${ORIGIN}/@fs/repo/x.js");\n`);
11-
});
12-
13-
it('leaves static imports, non-literal, relative, protocol-relative and absolute specifiers alone', () => {
14-
const code = `import { a } from "/src/a.ts";\nexport * from '/src/b.ts';\nimport('./rel.js');\nimport('//cdn/x.js');\nimport('https://cdn/x.js');\nimport(name);\nimport(__vite__injectQuery(u, 'import'));\nconst u = import.meta.url;`;
15-
expect(rewriteDeviceImports(code, ORIGIN)).toBe(code);
6+
it('leaves every specifier but a runtime builtin as Vite wrote it', () => {
7+
const code = `import { a } from "/src/a.ts";\nexport * from '/src/b.ts';\nimport('/src/lazy.ts?t=1700000000000');\nimport("/@fs/repo/x.js");\nimport('./rel.js');\nimport('//cdn/x.js');\nimport('https://cdn/x.js');\nimport("/@id/some-bare");\nimport(name);\nimport(__vite__injectQuery(u, 'import'));`;
8+
expect(rewriteDeviceImports(code)).toBe(code);
169
});
1710

1811
it('restores runtime builtins Vite serves under /@id/, static and dynamic', () => {
1912
const code = `import * as m from "/@id/ns:module";\nexport { x } from '/@id/ns:util';\nconst h = () => import('/@id/ns:module');\nimport "/@id/__x00__virtual:ns-dev-boot";\nimport "/@id/some-bare";\n`;
20-
expect(rewriteDeviceImports(code, ORIGIN)).toBe(`import * as m from "ns:module";\nexport { x } from 'ns:util';\nconst h = () => import('ns:module');\nimport "/@id/__x00__virtual:ns-dev-boot";\nimport "/@id/some-bare";\n`);
13+
expect(rewriteDeviceImports(code)).toBe(`import * as m from "ns:module";\nexport { x } from 'ns:util';\nconst h = () => import('ns:module');\nimport "/@id/__x00__virtual:ns-dev-boot";\nimport "/@id/some-bare";\n`);
2114
});
2215

2316
it('handles minified code and returns unparsable code unchanged', () => {
24-
expect(rewriteDeviceImports(`x=()=>import("/src/a.js"),y=()=>import("/src/b.js")`, ORIGIN)).toBe(`x=()=>import("${ORIGIN}/src/a.js"),y=()=>import("${ORIGIN}/src/b.js")`);
25-
const broken = `import('/src/a.js'); export {`;
26-
expect(rewriteDeviceImports(broken, ORIGIN)).toBe(broken);
17+
expect(rewriteDeviceImports(`import"/@id/ns:util";x=()=>import("/@id/ns:module"),y=()=>import("/src/b.js")`)).toBe(`import"ns:util";x=()=>import("ns:module"),y=()=>import("/src/b.js")`);
18+
const broken = `import('/@id/ns:module'); export {`;
19+
expect(rewriteDeviceImports(broken)).toBe(broken);
2720
});
2821
});
2922

@@ -56,22 +49,23 @@ class FakeResponse extends EventEmitter {
5649

5750
function respond(method: string, status: number, contentType: string | undefined, send: (res: FakeResponse) => void, isOptimizedDepUrl?: (url: string) => boolean, url = '/src/a.js') {
5851
const res = new FakeResponse();
59-
rewriteDeviceImportsInResponse({ method, url } as any, res as any, () => ORIGIN, isOptimizedDepUrl);
52+
rewriteDeviceImportsInResponse({ method, url } as any, res as any, isOptimizedDepUrl);
6053
res.statusCode = status;
6154
if (contentType) res.setHeader('Content-Type', contentType);
6255
send(res);
6356
return res;
6457
}
6558

6659
describe('rewriteDeviceImportsInResponse', () => {
67-
const module = `export const load = () => import('/src/lazy.ts');`;
60+
const module = `import { createRequire } from '/@id/ns:module'; export { createRequire };`;
61+
const rewritten = `import { createRequire } from 'ns:module'; export { createRequire };`;
6862

6963
it('rewrites a 2xx JavaScript body and fixes a set Content-Length', () => {
7064
const res = respond('GET', 200, 'text/javascript', (r) => {
7165
r.setHeader('Content-Length', Buffer.byteLength(module));
7266
r.end(module);
7367
});
74-
expect(res.text()).toBe(`export const load = () => import('${ORIGIN}/src/lazy.ts');`);
68+
expect(res.text()).toBe(rewritten);
7569
expect(res.getHeader('content-length')).toBe(Buffer.byteLength(res.text()));
7670
});
7771

@@ -81,35 +75,24 @@ describe('rewriteDeviceImportsInResponse', () => {
8175
r.write(module.slice(30));
8276
r.end();
8377
});
84-
expect(res.text()).toContain(`import('${ORIGIN}/src/lazy.ts')`);
78+
expect(res.text()).toBe(rewritten);
8579
expect(res.hasHeader('content-length')).toBe(false);
8680
});
8781

88-
it('ties the ETag to the origin and drops immutable when the origin is written into the body', () => {
89-
const res = respond('GET', 200, 'text/javascript', (r) => {
90-
r.setHeader('ETag', 'W/"2a-abc"');
91-
r.setHeader('Cache-Control', 'max-age=31536000,immutable');
92-
r.end(module);
93-
});
94-
expect(res.getHeader('etag')).toMatch(/^W\/"2a-abc-o[0-9a-f]{8}"$/);
95-
expect(res.getHeader('cache-control')).toBe('no-cache');
96-
});
97-
98-
it("keeps Vite's ETag and immutable for a pre-bundle without an origin-dependent rewrite", () => {
99-
const builtinOnly = `import { createRequire } from "/@id/ns:module";`;
82+
it("keeps Vite's ETag and immutable for a pre-bundle", () => {
10083
const res = respond(
10184
'GET',
10285
200,
10386
'text/javascript',
10487
(r) => {
10588
r.setHeader('ETag', 'W/"2a-abc"');
10689
r.setHeader('Cache-Control', 'max-age=31536000,immutable');
107-
r.end(builtinOnly);
90+
r.end(module);
10891
},
10992
(url) => url.startsWith('/node_modules/.vite/deps/'),
11093
'/node_modules/.vite/deps/pkg.js?v=1',
11194
);
112-
expect(res.text()).toBe(`import { createRequire } from "ns:module";`);
95+
expect(res.text()).toBe(rewritten);
11396
expect(res.getHeader('etag')).toBe('W/"2a-abc"');
11497
expect(res.getHeader('cache-control')).toBe('max-age=31536000,immutable');
11598
});
@@ -131,20 +114,6 @@ describe('rewriteDeviceImportsInResponse', () => {
131114
expect(res.getHeader('cache-control')).toBe('no-cache');
132115
});
133116

134-
it('maps validators issued for the current origin back to Vite ETags, leaving other origins unmatched', () => {
135-
const issued = respond('GET', 200, 'text/javascript', (r) => {
136-
r.setHeader('ETag', 'W/"2a-abc"');
137-
r.end(module);
138-
}).getHeader('etag') as string;
139-
expect(restoreOriginETags(issued, ORIGIN)).toBe('W/"2a-abc"');
140-
expect(restoreOriginETags(`W/"1-x", ${issued}`, ORIGIN)).toBe('W/"1-x", W/"2a-abc"');
141-
expect(restoreOriginETags(issued, 'http://10.0.0.9:5173')).toBe(issued);
142-
143-
const req = { method: 'GET', headers: { 'if-none-match': issued } } as any;
144-
rewriteDeviceImportsInResponse(req, new FakeResponse() as any, () => ORIGIN);
145-
expect(req.headers['if-none-match']).toBe('W/"2a-abc"');
146-
});
147-
148117
it('passes through other content types, statuses, HEAD requests and empty bodies', () => {
149118
expect(respond('GET', 200, 'text/css', (r) => r.end(module)).text()).toBe(module);
150119
expect(respond('GET', 404, 'text/javascript', (r) => r.end(module)).text()).toBe(module);

‎packages/vite/hmr/server/device-imports.ts‎

Lines changed: 19 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,40 @@
1-
import { createHash } from 'node:crypto';
21
import type { IncomingMessage, ServerResponse } from 'node:http';
32
import { initSync, parse } from 'es-module-lexer';
43
import { isBuiltinModuleId } from '../../helpers/builtin-modules.js';
54

65
const ID_PREFIX = '/@id/';
76

87
/**
9-
* Rewrites a served module's import specifiers into the form the device
10-
* runtime resolves:
11-
* - a runtime builtin (`ns:module`), which Vite's import analysis serves as
12-
* `/@id/ns:module`, goes back to the builtin specifier;
13-
* - every dynamic `import('/…')` whose specifier is a root-relative string
14-
* literal gets `origin` prefixed, query untouched. NativeScript runtimes
15-
* resolve a dynamic `import()` of a non-`http(s)` specifier on the
16-
* filesystem and strip its query.
17-
*
18-
* Other static imports stay root-relative.
8+
* Turns a runtime builtin (`ns:module`), which Vite's import analysis serves as
9+
* `/@id/ns:module`, back into the builtin specifier the device runtime resolves
10+
* itself. Every other specifier stays as Vite wrote it: the runtime resolves it
11+
* against the importing module's URL, as a browser does.
1912
*/
20-
export function rewriteDeviceImports(code: string, origin: string): string {
21-
return rewriteDeviceImportsDetailed(code, origin).code;
22-
}
23-
24-
function rewriteDeviceImportsDetailed(code: string, origin: string): { code: string; originInserted: boolean } {
25-
const unchanged = { code, originInserted: false };
26-
const hasDynamic = code.includes('import(') || code.includes('import (');
27-
if (!hasDynamic && !code.includes(ID_PREFIX)) return unchanged;
13+
export function rewriteDeviceImports(code: string): string {
14+
if (!code.includes(ID_PREFIX)) return code;
2815
initSync();
2916
let imports: ReturnType<typeof parse>[0];
3017
try {
3118
[imports] = parse(code);
3219
} catch {
33-
return unchanged;
20+
return code;
3421
}
35-
let originInserted = false;
36-
const base = origin.replace(/\/+$/, '');
37-
let out = '';
3822
let last = 0;
23+
let out = '';
3924
for (const imp of imports) {
40-
if (!imp.n || !imp.n.startsWith('/') || imp.n.startsWith('//')) continue;
25+
if (!imp.n?.startsWith(ID_PREFIX)) continue;
26+
const builtin = imp.n.slice(ID_PREFIX.length).split('?', 1)[0];
27+
if (!isBuiltinModuleId(builtin)) continue;
4128
const dynamic = imp.d > -1;
4229
const quote = dynamic ? code[imp.s] : '';
4330
if (dynamic && quote !== '"' && quote !== "'") continue;
4431
const start = dynamic ? imp.s + 1 : imp.s;
4532
const end = dynamic ? imp.e - 1 : imp.e;
4633
if (code[start] !== '/') continue;
47-
const builtin = imp.n.startsWith(ID_PREFIX) ? imp.n.slice(ID_PREFIX.length).split('?', 1)[0] : '';
48-
if (builtin && isBuiltinModuleId(builtin)) {
49-
out += code.slice(last, start) + builtin;
50-
last = end;
51-
} else if (dynamic) {
52-
out += code.slice(last, start) + base;
53-
last = start;
54-
originInserted = true;
55-
}
34+
out += code.slice(last, start) + builtin;
35+
last = end;
5636
}
57-
return last === 0 ? unchanged : { code: out + code.slice(last), originInserted };
58-
}
59-
60-
// A body with the origin baked in differs per origin while Vite's ETag and
61-
// `immutable` describe the origin-independent original, and the device caches
62-
// responses across sessions, whose origin can change (LAN address, USB tunnel).
63-
function originTag(origin: string): string {
64-
return '-o' + createHash('sha1').update(origin).digest('hex').slice(0, 8);
65-
}
66-
67-
function withOriginTag(etag: string, tag: string): string {
68-
return etag.endsWith('"') ? etag.slice(0, -1) + tag + '"' : etag + tag;
69-
}
70-
71-
/**
72-
* Maps `If-None-Match` validators this server issued for the current origin
73-
* back to Vite's own ETags, so Vite can still answer 304. Validators issued
74-
* for another origin are left as they are and never match.
75-
*/
76-
export function restoreOriginETags(ifNoneMatch: string, origin: string): string {
77-
const tag = originTag(origin) + '"';
78-
return ifNoneMatch
79-
.split(',')
80-
.map((value) => {
81-
const trimmed = value.trim();
82-
return trimmed.endsWith(tag) ? trimmed.slice(0, -tag.length) + '"' : trimmed;
83-
})
84-
.join(', ');
37+
return last === 0 ? code : out + code.slice(last);
8538
}
8639

8740
const jsContentTypeRE = /\bjavascript\b/i;
@@ -100,14 +53,9 @@ function toBuffer(chunk: unknown, encoding: unknown): Buffer {
10053

10154
/**
10255
* Applies {@link rewriteDeviceImports} to the body of a 2xx JavaScript
103-
* response, whichever middleware answers it. Rewriting the response rather
104-
* than the transform result keeps Vite's own specifiers intact: its soft
105-
* invalidation re-stamps `?t=` only on specifiers equal to an imported
106-
* module's root-relative URL.
56+
* response, whichever middleware answers it.
10757
*/
108-
export function rewriteDeviceImportsInResponse(req: IncomingMessage, res: ServerResponse, getOrigin: () => string, isOptimizedDepUrl: (url: string) => boolean = () => false): void {
109-
const ifNoneMatch = req.headers?.['if-none-match'];
110-
if (typeof ifNoneMatch === 'string') req.headers['if-none-match'] = restoreOriginETags(ifNoneMatch, getOrigin());
58+
export function rewriteDeviceImportsInResponse(req: IncomingMessage, res: ServerResponse, isOptimizedDepUrl: (url: string) => boolean = () => false): void {
11159
const write = res.write;
11260
const end = res.end;
11361
// undefined: undecided until the first write/end, when status and headers are final.
@@ -137,17 +85,12 @@ export function rewriteDeviceImportsInResponse(req: IncomingMessage, res: Server
13785
let body = original;
13886
if (original.length) {
13987
const code = original.toString('utf8');
140-
const origin = getOrigin();
141-
const rewritten = rewriteDeviceImportsDetailed(code, origin);
142-
if (rewritten.code !== code) body = Buffer.from(rewritten.code, 'utf8');
143-
if (rewritten.originInserted) {
144-
const etag = this.getHeader('etag');
145-
if (typeof etag === 'string') this.setHeader('ETag', withOriginTag(etag, originTag(origin)));
146-
}
88+
const rewritten = rewriteDeviceImports(code);
89+
if (rewritten !== code) body = Buffer.from(rewritten, 'utf8');
14790
// Vite marks every `?v=` URL immutable, but only a pre-bundle's bytes are tied to
14891
// that hash: a served file of an excluded package (a hand edit, patch-package, a
14992
// relinked build) changes under the same URL, and the device caches across launches.
150-
if ((rewritten.originInserted || !isOptimizedDepUrl(req.url ?? '')) && /\bimmutable\b/i.test(String(this.getHeader('cache-control') ?? ''))) {
93+
if (!isOptimizedDepUrl(req.url ?? '') && /\bimmutable\b/i.test(String(this.getHeader('cache-control') ?? ''))) {
15194
this.setHeader('Cache-Control', 'no-cache');
15295
}
15396
}

0 commit comments

Comments
 (0)