create-octane-xplat 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -144
- package/compatibility.json +97 -19
- package/compatibility.ts +141 -72
- package/dist/compatibility.js +66 -26
- package/dist/index.js +127 -64
- package/dist/package-manager.js +62 -0
- package/dist/scaffold.js +377 -127
- package/index.ts +256 -154
- package/library-template/AGENTS.md +6 -4
- package/library-template/README.md +22 -18
- package/library-template/bunfig +4 -0
- package/library-template/package.json +115 -18
- package/library-template/patches/@nativescript-community__octane@0.2.5.patch +1018 -0
- package/library-template/patches/@nativescript-community__sqlite-bridge@4.1.1.patch +30 -0
- package/library-template/patches/@nativescript-community__vite-octane@0.2.1.patch +72 -0
- package/library-template/patches/@nativescript__core@9.1.3.patch +1280 -0
- package/library-template/patches/@nativescript__doctor@2.0.18.patch +13 -0
- package/library-template/patches/@nativescript__vite@8.0.20.patch +2019 -0
- package/library-template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
- package/library-template/patches/@octanejs__tiptap@0.0.62.patch +12 -0
- package/library-template/patches/@sveltejs__acorn-typescript@1.0.13.patch +16 -0
- package/library-template/patches/css@3.0.0.patch +52 -0
- package/library-template/patches/octane@0.16.3.patch +1479 -0
- package/library-template/src/Badge.tsx +7 -6
- package/library-template/src/Badge.web.tsx +7 -6
- package/library-template/src/Welcome.stories.tsx +12 -0
- package/library-template/src/normalizeBadgeLabel.ts +1 -1
- package/library-template/src/props.ts +11 -11
- package/library-template/tests/normalizeBadgeLabel.test.ts +1 -1
- package/library-template/tests/packed-consumer.mjs +140 -123
- package/library-template/tsconfig.envs.json +1 -0
- package/library-template/tsconfig.json +1 -0
- package/library-template/tsconfig.types.json +15 -1
- package/library-template/tsrx-typegen.json +1 -1
- package/library-template/workshop.config.ts +3 -0
- package/package-manager.ts +93 -0
- package/package.json +70 -58
- package/scaffold.ts +1056 -526
- package/template/.agents/skills/xplat/SKILL.md +6 -6
- package/template/.agents/skills/xplat/references/components.md +1 -1
- package/template/.agents/skills/xplat/references/navigation.md +1 -1
- package/template/.agents/skills/xplat/references/styling.md +14 -14
- package/template/AGENTS.md +10 -10
- package/template/bunfig +4 -0
- package/template/gitignore +1 -0
- package/template/nativescript.config.ts +13 -16
- package/template/package.json +119 -10
- package/template/patches/@nativescript-community__octane@0.2.5.patch +1018 -0
- package/template/patches/@nativescript-community__sqlite-bridge@4.1.1.patch +30 -0
- package/template/patches/@nativescript-community__vite-octane@0.2.1.patch +72 -0
- package/template/patches/@nativescript__core@9.1.3.patch +1280 -0
- package/template/patches/@nativescript__doctor@2.0.18.patch +13 -0
- package/template/patches/@nativescript__vite@8.0.20.patch +2019 -0
- package/template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
- package/template/patches/@octanejs__tiptap@0.0.62.patch +12 -0
- package/template/patches/@sveltejs__acorn-typescript@1.0.13.patch +16 -0
- package/template/patches/css@3.0.0.patch +52 -0
- package/template/patches/octane@0.16.3.patch +1479 -0
- package/template/src/App.tsrx +77 -42
- package/template/src/Welcome.stories.tsx +22 -0
- package/template/src/app.spec.tsrx +169 -163
- package/template/src/app.web.test.tsx +18 -13
- package/template/src/failure-reporting.spec.ts +3 -3
- package/template/src/main.ts +14 -13
- package/template/src/main.tsrx +2 -0
- package/template/src/main.web.tsrx +5 -5
- package/template/src/native-runtime.spec.ts +13 -11
- package/template/src/test-setup.web.ts +9 -8
- package/template/src/test.ts +6 -6
- package/template/tsconfig.json +17 -1
- package/template/vite.config.native.mts +1 -2
- package/template/vite.config.ts +29 -23
- package/template/vitest.config.mts +18 -18
- package/template/vitest.web.config.mts +7 -7
- package/template/workshop.config.ts +3 -0
- package/library-template/pnpm-workspace.yaml +0 -171
- package/template/pnpm-workspace.yaml +0 -192
|
@@ -0,0 +1,2019 @@
|
|
|
1
|
+
diff --git a/helpers/global-defines.js b/helpers/global-defines.js
|
|
2
|
+
index e7390cb182cafe3b7307a25585280655d6ad5fad..4e0e337a2616cf53684c963562b76b48bb406111 100644
|
|
3
|
+
--- a/helpers/global-defines.js
|
|
4
|
+
+++ b/helpers/global-defines.js
|
|
5
|
+
@@ -179,6 +179,51 @@ export function setUserDefineEntries(define) {
|
|
6
|
+
userDefineEntries = entries;
|
|
7
|
+
userProcessEnvDefineEntries = envEntries;
|
|
8
|
+
}
|
|
9
|
+
+// ── User-configured `resolve.alias` entries ─────────────────────────────────
|
|
10
|
+
+// Vite `resolve.alias` rewrites import specifiers during dev transforms, but
|
|
11
|
+
+// the NativeScript esbuild passes (deps bundle, vendor bundle) never see the
|
|
12
|
+
+// Vite config — an alias like `^@octane-xplat/nativescript-masonkit(?=/|$)` →
|
|
13
|
+
+// the app's mason-core package dir leaves their imports heading for a package
|
|
14
|
+
+// that is genuinely absent from the app's node_modules, where the
|
|
15
|
+
+// optional-dependency stub then plants a throw-on-evaluate module that kills
|
|
16
|
+
+// device boot. Captured from the resolved config in `configResolved` and
|
|
17
|
+
+// replayed inside the esbuild passes by `createViteAliasEsbuildPlugin`.
|
|
18
|
+
+//
|
|
19
|
+
+// Normalized to `{ find: string|RegExp, replacement: string }[]`, keeping
|
|
20
|
+
+// only entries esbuild can honor faithfully: a string `replacement`, no
|
|
21
|
+
+// `customResolver`, and a `find` that is a RegExp or a bare-specifier string
|
|
22
|
+
+// (not `.`-relative or `/`-absolute — those are importer-relative aliases
|
|
23
|
+
+// esbuild would have to evaluate per importer dir, which Vite itself does not
|
|
24
|
+
+// support).
|
|
25
|
+
+let userAliasEntries = [];
|
|
26
|
+
+export function setUserAliasEntries(alias) {
|
|
27
|
+
+ const entries = [];
|
|
28
|
+
+ if (alias) {
|
|
29
|
+
+ const list = Array.isArray(alias) ? alias : Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));
|
|
30
|
+
+ for (const entry of list) {
|
|
31
|
+
+ if (!entry || entry.customResolver)
|
|
32
|
+
+ continue;
|
|
33
|
+
+ const { find, replacement } = entry;
|
|
34
|
+
+ if (typeof replacement !== 'string')
|
|
35
|
+
+ continue;
|
|
36
|
+
+ if (!(find instanceof RegExp) && !(typeof find === 'string' && find.length && !find.startsWith('.') && !find.startsWith('/')))
|
|
37
|
+
+ continue;
|
|
38
|
+
+ entries.push({ find, replacement });
|
|
39
|
+
+ }
|
|
40
|
+
+ }
|
|
41
|
+
+ userAliasEntries = entries;
|
|
42
|
+
+}
|
|
43
|
+
+/** The captured `resolve.alias` entries (see setUserAliasEntries). */
|
|
44
|
+
+export function getUserAliasEntries() {
|
|
45
|
+
+ return userAliasEntries;
|
|
46
|
+
+}
|
|
47
|
+
+/** Stable fingerprint of the captured aliases for bundle cache keys. */
|
|
48
|
+
+export function getUserAliasEntriesFingerprint() {
|
|
49
|
+
+ return JSON.stringify(userAliasEntries.map(({ find, replacement }) => [
|
|
50
|
+
+ find instanceof RegExp ? `re:${find.source}:${find.flags}` : `str:${find}`,
|
|
51
|
+
+ replacement,
|
|
52
|
+
+ ]));
|
|
53
|
+
+}
|
|
54
|
+
/** The captured `__FOO__` define entries as `[key, expression]` pairs (see setUserDefineEntries). */
|
|
55
|
+
export function getUserDefineEntries() {
|
|
56
|
+
return userDefineEntries;
|
|
57
|
+
diff --git a/helpers/project.js b/helpers/project.js
|
|
58
|
+
index f6777fa5e64e667cbc56c7e76c4c32c5ab76a911..fdc1f974884e26030c0084d75c1e51a1e5968db2 100644
|
|
59
|
+
--- a/helpers/project.js
|
|
60
|
+
+++ b/helpers/project.js
|
|
61
|
+
@@ -73,7 +73,11 @@ function denoConfigHasWorkspace(dir) {
|
|
62
|
+
* - `lerna.json`
|
|
63
|
+
* - `nx.json` (Nx)
|
|
64
|
+
* - `rush.json` (Rush)
|
|
65
|
+
- * - `turbo.json` (Turborepo)
|
|
66
|
+
+ * - `turbo.json` (Turborepo) — NOT self-declaring: Turborepo scatters
|
|
67
|
+
+ * per-package `turbo.json` task configs (`"extends": ["//"]`) into every
|
|
68
|
+
+ * workspace package, so the file alone marks a package dir, not a root.
|
|
69
|
+
+ * Real turbo roots still resolve through their workspace declaration
|
|
70
|
+
+ * (`pnpm-workspace.yaml`, `lerna.json`, or `package.json#workspaces`)
|
|
71
|
+
* - `deno.json` / `deno.jsonc` containing a `workspace` field
|
|
72
|
+
* - `package.json` containing a `workspaces` field (npm/yarn workspaces)
|
|
73
|
+
*
|
|
74
|
+
@@ -106,6 +110,15 @@ export function findMonorepoWorkspaceRoot(start = getProjectRootPath()) {
|
|
75
|
+
return current;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
+ if (marker === 'turbo.json') {
|
|
79
|
+
+ // turbo.json is not self-declaring: Turborepo writes
|
|
80
|
+
+ // per-package task configs (`"extends": ["//"]`) into
|
|
81
|
+
+ // workspace packages, so a lone turbo.json marks a package
|
|
82
|
+
+ // dir, not a root. Every real turbo root still resolves —
|
|
83
|
+
+ // its workspace is declared by pnpm-workspace.yaml,
|
|
84
|
+
+ // lerna.json, or package.json#workspaces.
|
|
85
|
+
+ continue;
|
|
86
|
+
+ }
|
|
87
|
+
if (existsSync(join(current, marker)))
|
|
88
|
+
return current;
|
|
89
|
+
}
|
|
90
|
+
diff --git a/helpers/ts-config-paths.js b/helpers/ts-config-paths.js
|
|
91
|
+
index 27013b5c8f78a72b6e6df903ac36f72fc0d75c1a..53a2e7d489ab91593cbec47ee6fb640fc56c786f 100644
|
|
92
|
+
--- a/helpers/ts-config-paths.js
|
|
93
|
+
+++ b/helpers/ts-config-paths.js
|
|
94
|
+
@@ -113,15 +113,20 @@ function resolveTsConfigPath(fullPath, platform, verbose, debugId) {
|
|
95
|
+
if (verbose && debugId) {
|
|
96
|
+
console.log(`📁 TypeScript path candidate: ${debugId} -> ${fullPath}`);
|
|
97
|
+
}
|
|
98
|
+
+ // `.mobile` is the shared ios/android suffix tier — it sits between the os
|
|
99
|
+
+ // qualifier and the unsuffixed default. Probing it per extension keeps
|
|
100
|
+
+ // paths-mapped imports consistent with the bundler's extension chain.
|
|
101
|
+
+ const suffixes = platform === 'ios' || platform === 'android' ? [platform, 'mobile'] : platform ? [platform] : [];
|
|
102
|
+
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
|
103
|
+
- const platformIndexPatterns = [`index.${platform}.ts`, `index.${platform}.js`, `index.${platform}.mjs`];
|
|
104
|
+
- for (const indexFile of platformIndexPatterns) {
|
|
105
|
+
- const indexPath = path.join(fullPath, indexFile);
|
|
106
|
+
- if (fs.existsSync(indexPath)) {
|
|
107
|
+
- if (verbose) {
|
|
108
|
+
- console.log(`📁 Found platform-specific directory index: ${indexPath}`);
|
|
109
|
+
+ for (const suffix of suffixes) {
|
|
110
|
+
+ for (const ext of ['.ts', '.js', '.mjs']) {
|
|
111
|
+
+ const indexPath = path.join(fullPath, `index.${suffix}${ext}`);
|
|
112
|
+
+ if (fs.existsSync(indexPath)) {
|
|
113
|
+
+ if (verbose) {
|
|
114
|
+
+ console.log(`📁 Found platform-specific directory index: ${indexPath}`);
|
|
115
|
+
+ }
|
|
116
|
+
+ return indexPath;
|
|
117
|
+
}
|
|
118
|
+
- return indexPath;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
for (const indexFile of ['index.ts', 'index.js', 'index.mjs']) {
|
|
122
|
+
@@ -135,12 +140,14 @@ function resolveTsConfigPath(fullPath, platform, verbose, debugId) {
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
126
|
+
- const platformPath = `${fullPath}.${platform}${ext}`;
|
|
127
|
+
- if (fs.existsSync(platformPath)) {
|
|
128
|
+
- if (verbose) {
|
|
129
|
+
- console.log(`📁 Found platform-specific file: ${platformPath}`);
|
|
130
|
+
+ for (const suffix of suffixes) {
|
|
131
|
+
+ const platformPath = `${fullPath}.${suffix}${ext}`;
|
|
132
|
+
+ if (fs.existsSync(platformPath)) {
|
|
133
|
+
+ if (verbose) {
|
|
134
|
+
+ console.log(`📁 Found platform-specific file: ${platformPath}`);
|
|
135
|
+
+ }
|
|
136
|
+
+ return platformPath;
|
|
137
|
+
}
|
|
138
|
+
- return platformPath;
|
|
139
|
+
}
|
|
140
|
+
const basePath = `${fullPath}${ext}`;
|
|
141
|
+
if (fs.existsSync(basePath)) {
|
|
142
|
+
diff --git a/helpers/typescript-check.js b/helpers/typescript-check.js
|
|
143
|
+
index a05696b679b3feecd1bafa267de44b59db559162..e909d6e25b3142f48d13cae2f2c4c8c0dced36e7 100644
|
|
144
|
+
--- a/helpers/typescript-check.js
|
|
145
|
+
+++ b/helpers/typescript-check.js
|
|
146
|
+
@@ -7,14 +7,16 @@ import { getProjectRootPath, getProjectTSConfigPath } from './project.js';
|
|
147
|
+
import { loadTypeScript } from './typescript.js';
|
|
148
|
+
const require = createRequire(import.meta.url);
|
|
149
|
+
function getModuleSuffixes(platform) {
|
|
150
|
+
+ // `.mobile` is the shared ios/android suffix tier — it sits between the os
|
|
151
|
+
+ // qualifier and `.native`, matching the bundler's extension chain.
|
|
152
|
+
if (platform === 'android') {
|
|
153
|
+
- return ['.android', '.native', ''];
|
|
154
|
+
+ return ['.android', '.mobile', '.native', ''];
|
|
155
|
+
}
|
|
156
|
+
if (platform === 'ios') {
|
|
157
|
+
- return ['.ios', '.native', ''];
|
|
158
|
+
+ return ['.ios', '.mobile', '.native', ''];
|
|
159
|
+
}
|
|
160
|
+
if (platform === 'visionos') {
|
|
161
|
+
- return ['.visionos', '.ios', '.native', ''];
|
|
162
|
+
+ return ['.visionos', '.ios', '.mobile', '.native', ''];
|
|
163
|
+
}
|
|
164
|
+
return ['.native', ''];
|
|
165
|
+
}
|
|
166
|
+
@@ -29,13 +31,14 @@ function getVueTscBinPath() {
|
|
167
|
+
const pkgPath = require.resolve('vue-tsc/package.json');
|
|
168
|
+
return path.resolve(path.dirname(pkgPath), 'bin/vue-tsc.js');
|
|
169
|
+
}
|
|
170
|
+
-function getTsrxTscBinPath() {
|
|
171
|
+
+function getTscBinPath() {
|
|
172
|
+
try {
|
|
173
|
+
const projectRequire = createRequire(path.join(getProjectRootPath(), 'package.json'));
|
|
174
|
+
- const pkgPath = projectRequire.resolve('@tsrx/typescript-plugin/package.json');
|
|
175
|
+
+ const pkgPath = projectRequire.resolve('typescript/package.json');
|
|
176
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
177
|
+
- const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['tsrx-tsc'];
|
|
178
|
+
- return bin ? path.resolve(path.dirname(pkgPath), bin) : undefined;
|
|
179
|
+
+ const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['tsc'];
|
|
180
|
+
+ const major = Number.parseInt(String(pkg.version ?? ''), 10);
|
|
181
|
+
+ return bin && major >= 7 ? path.resolve(path.dirname(pkgPath), bin) : undefined;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return undefined;
|
|
185
|
+
@@ -92,7 +95,7 @@ function runTsrxTypeCheck(binPath, opts, tsConfigPath, parsedConfig, rootNames,
|
|
186
|
+
try {
|
|
187
|
+
const configPath = path.join(tempDir, 'tsconfig.json');
|
|
188
|
+
fs.writeFileSync(configPath, JSON.stringify(createTsrxCheckConfig(tsConfigPath, parsedConfig, rootNames, opts.platform)));
|
|
189
|
+
- runTscBinary('tsrx-tsc', [binPath, '--pretty', '-p', configPath], opts, failOnError);
|
|
190
|
+
+ runTscBinary('tsc', [binPath, '--runExternalCode', '--pretty', '-p', configPath], opts, failOnError);
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
194
|
+
@@ -304,9 +307,9 @@ export function typescriptCheckPlugin(opts) {
|
|
195
|
+
const parsedConfig = getParsedConfig(ts, tsConfigPath, opts.platform);
|
|
196
|
+
const failOnError = shouldFailOnTypeCheckError(opts, parsedConfig);
|
|
197
|
+
const rootNames = parsedConfig.fileNames.filter((fileName) => !shouldSkipFileForPlatform(fileName, opts.platform));
|
|
198
|
+
- const tsrxTscBinPath = getTsrxTscBinPath();
|
|
199
|
+
- if (tsrxTscBinPath && hasTsrxImports(ts, rootNames)) {
|
|
200
|
+
- runTsrxTypeCheck(tsrxTscBinPath, opts, tsConfigPath, parsedConfig, rootNames, failOnError);
|
|
201
|
+
+ const tscBinPath = getTscBinPath();
|
|
202
|
+
+ if (tscBinPath && hasTsrxImports(ts, rootNames)) {
|
|
203
|
+
+ runTsrxTypeCheck(tscBinPath, opts, tsConfigPath, parsedConfig, rootNames, failOnError);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const program = ts.createProgram({
|
|
207
|
+
@@ -323,7 +326,7 @@ export function typescriptCheckPlugin(opts) {
|
|
208
|
+
}
|
|
209
|
+
if (opts.logDiagnostics !== false) {
|
|
210
|
+
if (hasUnresolvedTsrxImport(ts, diagnostics)) {
|
|
211
|
+
- console.warn('[ns-vite] Unresolved .tsrx imports: install @tsrx/typescript-plugin so the type check can run through tsrx-tsc.');
|
|
212
|
+
+ console.warn('[ns-vite] Unresolved .tsrx imports: install TypeScript 7.1 or newer so .tsrx files are checked through tsc --runExternalCode.');
|
|
213
|
+
}
|
|
214
|
+
const output = ts.formatDiagnosticsWithColorAndContext(diagnostics, getFormatHost(ts));
|
|
215
|
+
(failOnError ? console.error : console.warn)(output);
|
|
216
|
+
diff --git a/helpers/typescript.js b/helpers/typescript.js
|
|
217
|
+
index fe9c9fe948862def734df7bc5b817a9989155019..8d6b16a7043be959afaa0c1e16aefb09fbf2f142 100644
|
|
218
|
+
--- a/helpers/typescript.js
|
|
219
|
+
+++ b/helpers/typescript.js
|
|
220
|
+
@@ -6,23 +6,33 @@ let loaded;
|
|
221
|
+
* The compiler API backs the NativeClass ES5 downlevel and build-time type
|
|
222
|
+
* checking, but a plain JavaScript app has no reason to install `typescript`.
|
|
223
|
+
* Loading it on demand keeps every config helper importable without it; each
|
|
224
|
+
- * call site decides what to do when it is absent. The project's own copy is
|
|
225
|
+
- * preferred over one reachable from this package so type checking runs on the
|
|
226
|
+
- * version the app was written against.
|
|
227
|
+
+ * call site decides what to do when it is absent. Prefer the project's
|
|
228
|
+
+ * explicit classic API alias; a native TypeScript launcher is not an API.
|
|
229
|
+
+ * TSRX checking still delegates to the project's tsc --runExternalCode.
|
|
230
|
+
*/
|
|
231
|
+
export function loadTypeScript() {
|
|
232
|
+
- if (loaded !== undefined)
|
|
233
|
+
- return loaded;
|
|
234
|
+
- loaded = null;
|
|
235
|
+
+ if (loaded !== undefined) return loaded;
|
|
236
|
+
+ let incompatible = false;
|
|
237
|
+
for (const paths of [[getProjectRootPath()], undefined]) {
|
|
238
|
+
- try {
|
|
239
|
+
- loaded = require(require.resolve('typescript', paths ? { paths } : undefined));
|
|
240
|
+
- break;
|
|
241
|
+
+ for (const name of ['typescript-classic', 'typescript']) {
|
|
242
|
+
+ let candidate;
|
|
243
|
+
+ try {
|
|
244
|
+
+ candidate = require(require.resolve(name, paths ? { paths } : undefined));
|
|
245
|
+
+ } catch { continue; }
|
|
246
|
+
+ if (typeof candidate.transpileModule === 'function' && typeof candidate.getParsedCommandLineOfConfigFile === 'function') {
|
|
247
|
+
+ loaded = candidate;
|
|
248
|
+
+ return loaded;
|
|
249
|
+
+ }
|
|
250
|
+
+ incompatible = true;
|
|
251
|
+
}
|
|
252
|
+
- catch { }
|
|
253
|
+
}
|
|
254
|
+
+ if (incompatible) {
|
|
255
|
+
+ throw new Error('[ns-vite] Native TypeScript does not provide the classic compiler API used by NativeClass and config parsing. Install typescript-classic@npm:typescript@5.9.3; project typechecks can keep native TypeScript.');
|
|
256
|
+
+ }
|
|
257
|
+
+ loaded = null;
|
|
258
|
+
return loaded;
|
|
259
|
+
}
|
|
260
|
+
+
|
|
261
|
+
let warned = false;
|
|
262
|
+
/**
|
|
263
|
+
* Logged once per process. A `@NativeClass` source that is not downleveled
|
|
264
|
+
diff --git a/hmr/client/hot-context.js b/hmr/client/hot-context.js
|
|
265
|
+
index 120bc26fec96d1056701e4c3eb7b78987b40ab8f..f17cea64a1f0f8f87f4c0df856080789ddfa3c14 100644
|
|
266
|
+
--- a/hmr/client/hot-context.js
|
|
267
|
+
+++ b/hmr/client/hot-context.js
|
|
268
|
+
@@ -74,6 +74,47 @@ const VERBOSE = (() => {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
})();
|
|
272
|
+
+/**
|
|
273
|
+
+ * Dev-reload cancellation contract for dynamic imports.
|
|
274
|
+
+ *
|
|
275
|
+
+ * `ns:module` `invalidateModules` deliberately rejects every pending dynamic
|
|
276
|
+
+ * `import()` whose target was evicted, with a plain `Error` reading
|
|
277
|
+
+ * `Module invalidated during dev reload: <url>` (iOS
|
|
278
|
+
+ * `RejectResolversForInvalidation`, Android likewise). A whole-graph eviction
|
|
279
|
+
+ * (`jsFullReload` below) orphans every in-flight app `import()` (most
|
|
280
|
+
+ * visibly an entry's `void import(...)` issued after application start), and
|
|
281
|
+
+ * a targeted HMR eviction can orphan one too; nothing else owns those
|
|
282
|
+
+ * rejections, so each surfaces as a fatal unhandled rejection.
|
|
283
|
+
+ *
|
|
284
|
+
+ * The cancellation is issued by the dev machinery itself, so an *unhandled*
|
|
285
|
+
+ * one is owned here: `preventDefault()` suppresses only the fatal report. A
|
|
286
|
+
+ * call site that attached `.catch` still observes the rejection normally,
|
|
287
|
+
+ * and every other failure — fetch errors, evaluation throws, missing
|
|
288
|
+
+ * modules — reports exactly as before.
|
|
289
|
+
+ */
|
|
290
|
+
+const DEV_RELOAD_CANCELLATION_PREFIX = 'Module invalidated during dev reload:';
|
|
291
|
+
+// Duck-typed rather than `instanceof Error`: the rejected value can cross
|
|
292
|
+
+// module realms on device.
|
|
293
|
+
+function isDevReloadCancellation(reason) {
|
|
294
|
+
+ return (typeof reason === 'object' && reason !== null && typeof reason.message === 'string' &&
|
|
295
|
+
+ reason.message.startsWith(DEV_RELOAD_CANCELLATION_PREFIX));
|
|
296
|
+
+}
|
|
297
|
+
+function installDevReloadRejectionFilter(g) {
|
|
298
|
+
+ try {
|
|
299
|
+
+ if (typeof g.addEventListener !== 'function' || g.__NS_DEV_RELOAD_REJECTION_FILTER__)
|
|
300
|
+
+ return;
|
|
301
|
+
+ g.__NS_DEV_RELOAD_REJECTION_FILTER__ = true;
|
|
302
|
+
+ g.addEventListener('unhandledrejection', (event) => {
|
|
303
|
+
+ const reason = event?.reason;
|
|
304
|
+
+ if (!isDevReloadCancellation(reason))
|
|
305
|
+
+ return;
|
|
306
|
+
+ if (VERBOSE)
|
|
307
|
+
+ console.info('[ns-hot] dev reload cancelled an in-flight import:', reason.message);
|
|
308
|
+
+ event.preventDefault();
|
|
309
|
+
+ });
|
|
310
|
+
+ }
|
|
311
|
+
+ catch { }
|
|
312
|
+
+}
|
|
313
|
+
function createRegistry() {
|
|
314
|
+
const modules = new Map();
|
|
315
|
+
const eventListeners = new Map();
|
|
316
|
+
@@ -384,6 +425,10 @@ function createRegistry() {
|
|
317
|
+
*/
|
|
318
|
+
export function installNsHotRegistry() {
|
|
319
|
+
const g = globalThis;
|
|
320
|
+
+ // The dev machinery owns the deliberate `invalidateModules` cancellation
|
|
321
|
+
+ // regardless of which copy installs the registry — install the filter
|
|
322
|
+
+ // even when another realm already seeded `__NS_HOT_REGISTRY__`.
|
|
323
|
+
+ installDevReloadRejectionFilter(g);
|
|
324
|
+
if (g.__NS_HOT_REGISTRY__ && typeof g.__NS_HOT_REGISTRY__.createHotContext === 'function') {
|
|
325
|
+
return g.__NS_HOT_REGISTRY__;
|
|
326
|
+
}
|
|
327
|
+
diff --git a/hmr/helpers/ast-normalizer.js b/hmr/helpers/ast-normalizer.js
|
|
328
|
+
index 77f5533a289902b644f2dba4c8a558f5a00c8314..5c1d57f34a5e863ae3e684012a99f9bb8796e974 100644
|
|
329
|
+
--- a/hmr/helpers/ast-normalizer.js
|
|
330
|
+
+++ b/hmr/helpers/ast-normalizer.js
|
|
331
|
+
@@ -86,9 +86,10 @@ export function astNormalizeModuleImportsAndHelpers(code, opts) {
|
|
332
|
+
// path (e.g. `html-entities` when not in optimizeDeps) — those must be
|
|
333
|
+
// rewritten to the bare id (see below), not removed; removing them
|
|
334
|
+
// left consumer bindings undefined (`decode is not defined`).
|
|
335
|
+
+ // User virtual stylesheets must reach the native CSS registration route.
|
|
336
|
+
// Exemption: oxc runtime helper virtuals are real servable URLs that
|
|
337
|
+
// downstream passes preserve/origin-prefix — keep them here too.
|
|
338
|
+
- const isViteVirtual = (src) => !!src && (/\0/.test(src) || /__x00__/.test(src)) && !src.includes('__x00__@oxc-project+runtime');
|
|
339
|
+
+ const isViteVirtual = (src) => !!src && (/\0/.test(src) || /__x00__/.test(src)) && !src.includes('__x00__@oxc-project+runtime') && !/\.(css|scss|sass|less|styl|stylus)(?:[?#]|$)/i.test(src);
|
|
340
|
+
const realIdPrefixed = (src) => {
|
|
341
|
+
if (!src || !src.startsWith('/@id/'))
|
|
342
|
+
return null;
|
|
343
|
+
diff --git a/hmr/server/css-device-module.js b/hmr/server/css-device-module.js
|
|
344
|
+
index 0d7cd968eac690a85411cf3d6a24323a3d3a3992..98094d6ccfb918d00249d8087aebdd994b64244d 100644
|
|
345
|
+
--- a/hmr/server/css-device-module.js
|
|
346
|
+
+++ b/hmr/server/css-device-module.js
|
|
347
|
+
@@ -41,4 +41,15 @@ export function buildCssRegisterSnippet(tag, cssText) {
|
|
348
|
+
export function buildCssRegisterSnippetFromVar(tag, varName) {
|
|
349
|
+
return buildRegisterCall(JSON.stringify(tag), varName);
|
|
350
|
+
}
|
|
351
|
+
+/** Bridge only plugin-provided virtual stylesheets; file CSS has its own hot-update path. */
|
|
352
|
+
+export function virtualCssUpdates(payload) {
|
|
353
|
+
+ if (payload?.type !== 'update') return [];
|
|
354
|
+
+ return (payload.updates || []).flatMap((update) => {
|
|
355
|
+
+ if (update.type !== 'css-update' && update.type !== 'js-update') return [];
|
|
356
|
+
+ let spec = update.path?.split(/[?#]/)[0];
|
|
357
|
+
+ if (spec?.startsWith('\0')) spec = '/@id/' + spec.replace(/\0/g, '__x00__');
|
|
358
|
+
+ if (!spec?.startsWith('/@id/__x00__') || !CSS_MODULE_RE.test(spec)) return [];
|
|
359
|
+
+ return [{ type: 'css-update', path: '/ns/m' + spec, acceptedPath: '/ns/m' + spec, tag: spec, timestamp: update.timestamp }];
|
|
360
|
+
+ });
|
|
361
|
+
+}
|
|
362
|
+
//# sourceMappingURL=css-device-module.js.map
|
|
363
|
+
|
|
364
|
+
diff --git a/hmr/server/deps-bundle.js b/hmr/server/deps-bundle.js
|
|
365
|
+
index 395c29e9b9b552fbf30c4a7131121a0d841df116..e2523548534dda72042efe318beeeb05c05f73e5 100644
|
|
366
|
+
--- a/hmr/server/deps-bundle.js
|
|
367
|
+
+++ b/hmr/server/deps-bundle.js
|
|
368
|
+
@@ -53,21 +53,22 @@
|
|
369
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
370
|
+
import * as path from 'node:path';
|
|
371
|
+
import { createHash } from 'node:crypto';
|
|
372
|
+
+import { createRequire } from 'node:module';
|
|
373
|
+
import * as esbuild from 'esbuild';
|
|
374
|
+
import { resolvePlatform } from '../../helpers/cli-flags.js';
|
|
375
|
+
-import { getGlobalDefines, getUserDefineEntries } from '../../helpers/global-defines.js';
|
|
376
|
+
+import { getGlobalDefines, getUserDefineEntries, getUserAliasEntriesFingerprint } from '../../helpers/global-defines.js';
|
|
377
|
+
import { getProjectFlavor } from '../../helpers/flavor.js';
|
|
378
|
+
import { getMonorepoWorkspaceRoot } from '../../helpers/project.js';
|
|
379
|
+
import { createNativeClassEsbuildPlugin } from '../../helpers/nativeclass-esbuild-plugin.js';
|
|
380
|
+
import { resolveVerboseFlag } from '../../helpers/logging.js';
|
|
381
|
+
import { getVitePackageVersion } from '../../helpers/vite-package-version.js';
|
|
382
|
+
-import { createNodeBuiltinPolyfillEsbuildPlugin, createSolidJsxEsbuildPlugin, createUnicodeRegexEsbuildPlugin, createVendorEsbuildPlugin, createWebpackLoaderStubEsbuildPlugin, createOptionalDependencyStubEsbuildPlugin, createNativeAddonStubEsbuildPlugin } from '../shared/vendor/vendor-esbuild-plugins.js';
|
|
383
|
+
+import { createNodeBuiltinPolyfillEsbuildPlugin, createSolidJsxEsbuildPlugin, createUnicodeRegexEsbuildPlugin, createVendorEsbuildPlugin, createViteAliasEsbuildPlugin, createWebpackLoaderStubEsbuildPlugin, createOptionalDependencyStubEsbuildPlugin, createNativeAddonStubEsbuildPlugin } from '../shared/vendor/vendor-esbuild-plugins.js';
|
|
384
|
+
import { getVendorManifest, setVendorRuntimeModuleProvider } from '../shared/vendor/registry.js';
|
|
385
|
+
import { collectVendorModules } from '../shared/vendor/manifest-collect.js';
|
|
386
|
+
import { generatePlatformPolyfills } from '../shared/runtime/platform-polyfills.js';
|
|
387
|
+
import { getAngularLinkerFactory, runAngularLinker } from '../frameworks/angular/build/shared-linker.js';
|
|
388
|
+
import { getBlockedDeviceNodeModulesReason, isFlavorClientPackageSpecifier, resolveCandidateFilePath } from './websocket-module-specifiers.js';
|
|
389
|
+
-import { extractDirectExportedNames, JS_IDENTIFIER_RE, parseExportSpecList } from './websocket-core-bridge.js';
|
|
390
|
+
+import { extractDirectExportedNames, JS_IDENTIFIER_RE, maskJsComments, parseExportSpecList } from './websocket-core-bridge.js';
|
|
391
|
+
import { hasExistingDefaultExport } from './ns-core-cjs-shape.js';
|
|
392
|
+
import { getCjsNamedExports } from '../helpers/cjs-named-exports.js';
|
|
393
|
+
import { loadPersistedBootRecording } from './boot-recording.js';
|
|
394
|
+
@@ -537,6 +538,7 @@ export function computeDepsBundleCacheKey(input) {
|
|
395
|
+
defines: input.defines,
|
|
396
|
+
entryKeys: input.entryKeys,
|
|
397
|
+
lockfile: input.lockfile,
|
|
398
|
+
+ aliases: input.aliases,
|
|
399
|
+
vitePackageVersion: input.vitePackageVersion,
|
|
400
|
+
});
|
|
401
|
+
return createHash('sha1').update(payload).digest('hex');
|
|
402
|
+
@@ -681,6 +683,9 @@ export async function generateDepsBundle(options) {
|
|
403
|
+
entryKeys: entries.map((e) => e.key).sort(),
|
|
404
|
+
lockfile: lockfileFingerprint(projectRoot),
|
|
405
|
+
vitePackageVersion: getVitePackageVersion(),
|
|
406
|
+
+ // Aliases change which files the esbuild pass resolves — a stale
|
|
407
|
+
+ // bundle built before an alias appeared must not be reused.
|
|
408
|
+
+ aliases: getUserAliasEntriesFingerprint(),
|
|
409
|
+
});
|
|
410
|
+
const cached = tryLoadDepsBundleFromDisk(projectRoot, String(platform), cacheKey);
|
|
411
|
+
if (cached) {
|
|
412
|
+
@@ -699,6 +704,29 @@ export async function generateDepsBundle(options) {
|
|
413
|
+
// the device cannot resolve.
|
|
414
|
+
const buildPlugins = () => [
|
|
415
|
+
createWebpackLoaderStubEsbuildPlugin(),
|
|
416
|
+
+ // Bare `octane` is the DOM entry — a dep importing it (published
|
|
417
|
+
+ // @octane-xplat/* dist files kept `from "octane"` through 0.6.0)
|
|
418
|
+
+ // bundles a second runtime next to the universal one, and hooks read
|
|
419
|
+
+ // an empty CURRENT_SCOPE ("Cannot read properties of null (reading
|
|
420
|
+
+ // 'hooks')"). Vite resolve.alias never reaches these esbuild passes;
|
|
421
|
+
+ // route exact `octane` imports to the host-neutral entry here.
|
|
422
|
+
+ {
|
|
423
|
+
+ name: 'ns-deps-bundle-octane-universal-alias',
|
|
424
|
+
+ setup(build) {
|
|
425
|
+
+ build.onResolve({ filter: /^octane$/ }, (args) => {
|
|
426
|
+
+ for (const dir of [args.importer && path.dirname(args.importer), args.resolveDir, projectRoot]) {
|
|
427
|
+
+ if (!dir)
|
|
428
|
+
+ continue;
|
|
429
|
+
+ try {
|
|
430
|
+
+ return { path: createRequire(path.join(dir, 'noop.js')).resolve('octane/universal/native') };
|
|
431
|
+
+ }
|
|
432
|
+
+ catch {
|
|
433
|
+
+ }
|
|
434
|
+
+ }
|
|
435
|
+
+ return null;
|
|
436
|
+
+ });
|
|
437
|
+
+ },
|
|
438
|
+
+ },
|
|
439
|
+
createNodeBuiltinPolyfillEsbuildPlugin(projectRoot, NODE_BUILTINS),
|
|
440
|
+
createNativeClassEsbuildPlugin(platform),
|
|
441
|
+
createVendorEsbuildPlugin(projectRoot),
|
|
442
|
+
@@ -706,6 +734,9 @@ export async function generateDepsBundle(options) {
|
|
443
|
+
...(flavor === 'angular' ? [createDepsAngularLinkerPlugin(projectRoot)] : []),
|
|
444
|
+
...(flavor === 'solid' ? [createSolidJsxEsbuildPlugin(projectRoot)] : []),
|
|
445
|
+
createUnicodeRegexEsbuildPlugin(projectRoot),
|
|
446
|
+
+ // App `resolve.alias` redirects for packages that are NOT installed
|
|
447
|
+
+ // (masonkit → mason-core & co.) — without this they hit the stub below.
|
|
448
|
+
+ createViteAliasEsbuildPlugin(projectRoot),
|
|
449
|
+
createOptionalDependencyStubEsbuildPlugin(projectRoot),
|
|
450
|
+
createNativeAddonStubEsbuildPlugin(),
|
|
451
|
+
];
|
|
452
|
+
@@ -793,7 +824,15 @@ export async function generateDepsBundle(options) {
|
|
453
|
+
}
|
|
454
|
+
return state;
|
|
455
|
+
}
|
|
456
|
+
-const ESM_SYNTAX_RE = /^[ \t]*(?:import[\s{"'*]|export[\s{*])/m;
|
|
457
|
+
+// ESM markers can sit anywhere on a line — minified chunks emit
|
|
458
|
+
+// `...;export{mt as g};` after other statements, and a line-anchored check
|
|
459
|
+
+// misclassifies them as opaque CJS (the served shim then drops every named
|
|
460
|
+
+// export). The pattern runs against a copy with comments and string/template/
|
|
461
|
+
+// regex literal interiors blanked (positions preserved), so look-alike text
|
|
462
|
+
+// inside literals can never match. The lookbehind keeps `$export`-style
|
|
463
|
+
+// identifiers and `obj.import`/`obj.export` member access from matching.
|
|
464
|
+
+const ESM_PREFIX = '(?<![.$\\u200c\\u200d\\p{ID_Continue}])';
|
|
465
|
+
+const ESM_SYNTAX_RE = new RegExp(ESM_PREFIX + String.raw`(?:import[\s{"'*]|export[\s{*])`, 'u');
|
|
466
|
+
function resolveLocalReExportTarget(spec, importerPath, platform) {
|
|
467
|
+
const base = path.resolve(path.dirname(importerPath), spec);
|
|
468
|
+
if (existsSync(base) && statSync(base).isFile())
|
|
469
|
+
@@ -881,23 +920,35 @@ export function collectDepsModuleExportInfo(absPath, platform, seen = new Set())
|
|
470
|
+
catch {
|
|
471
|
+
return { names: null, hasDefault: false };
|
|
472
|
+
}
|
|
473
|
+
- if (!/\.mjs$/i.test(absPath) && !ESM_SYNTAX_RE.test(code))
|
|
474
|
+
+ const maskedCode = maskJsComments(code, true);
|
|
475
|
+
+ if (!/\.mjs$/i.test(absPath) && !ESM_SYNTAX_RE.test(maskedCode))
|
|
476
|
+
return collectCjsExportInfo(code);
|
|
477
|
+
- const names = new Set(extractDirectExportedNames(code));
|
|
478
|
+
+ const names = new Set(extractDirectExportedNames(maskedCode));
|
|
479
|
+
let match;
|
|
480
|
+
- const starAsRe = /\bexport\s+\*\s+as\s+([$_\p{ID_Start}][$\p{ID_Continue}]*)\s+from\s+["'][^"']+["']/gu;
|
|
481
|
+
- while ((match = starAsRe.exec(code)) !== null) {
|
|
482
|
+
+ // Minifiers drop the spaces `export * as ns from "x"` keeps — allow none.
|
|
483
|
+
+ const starAsRe = new RegExp(ESM_PREFIX + String.raw`export\s*\*\s*as\s+([$_\p{ID_Start}][$\p{ID_Continue}]*)\s+from\s*["'][^"']*["']`, 'gu');
|
|
484
|
+
+ while ((match = starAsRe.exec(maskedCode)) !== null) {
|
|
485
|
+
names.add(match[1]);
|
|
486
|
+
}
|
|
487
|
+
- const braceRe = /\bexport\s*\{([^}]+)\}/g;
|
|
488
|
+
- while ((match = braceRe.exec(code)) !== null) {
|
|
489
|
+
+ const braceRe = new RegExp(ESM_PREFIX + String.raw`export\s*\{([^}]+)\}`, 'gu');
|
|
490
|
+
+ while ((match = braceRe.exec(maskedCode)) !== null) {
|
|
491
|
+
for (const { exportedName } of parseExportSpecList(match[1])) {
|
|
492
|
+
names.add(exportedName);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
- const starRe = /^[ \t]*export\s+\*\s+from\s+["']([^"']+)["']/gm;
|
|
496
|
+
- while ((match = starRe.exec(code)) !== null) {
|
|
497
|
+
- const spec = match[1];
|
|
498
|
+
+ // `export * from` carries the same mid-line minification hazard — find it
|
|
499
|
+
+ // on the masked copy, then read the specifier literal from the original
|
|
500
|
+
+ // code at the same offset (masked interiors are blanked).
|
|
501
|
+
+ const starRe = new RegExp(ESM_PREFIX + String.raw`export\s*\*\s*from\s*(["'])`, 'gu');
|
|
502
|
+
+ while ((match = starRe.exec(maskedCode)) !== null) {
|
|
503
|
+
+ const quoteIndex = match.index + match[0].length - 1;
|
|
504
|
+
+ const quote = match[1];
|
|
505
|
+
+ let specEnd = quoteIndex + 1;
|
|
506
|
+
+ while (specEnd < code.length && code[specEnd] !== quote)
|
|
507
|
+
+ specEnd += code[specEnd] === '\\' ? 2 : 1;
|
|
508
|
+
+ if (specEnd >= code.length)
|
|
509
|
+
+ return { names: null, hasDefault: false };
|
|
510
|
+
+ const spec = code.slice(quoteIndex + 1, specEnd);
|
|
511
|
+
const target = spec.startsWith('.') ? resolveLocalReExportTarget(spec, absPath, platform) : resolveBareReExportTarget(spec, absPath, platform);
|
|
512
|
+
if (!target)
|
|
513
|
+
return { names: null, hasDefault: false };
|
|
514
|
+
diff --git a/hmr/server/device-transform-helpers.js b/hmr/server/device-transform-helpers.js
|
|
515
|
+
index 71574c48f655183af0c9601b020fd1febd63ccb3..0061d9c9e9fe9c6034576eae8449831d19f8ace7 100644
|
|
516
|
+
--- a/hmr/server/device-transform-helpers.js
|
|
517
|
+
+++ b/hmr/server/device-transform-helpers.js
|
|
518
|
+
@@ -79,7 +79,11 @@ function bareSpecifierFromFlatDepPath(depPath) {
|
|
519
|
+
return bareSpecifier;
|
|
520
|
+
}
|
|
521
|
+
function rewriteVitePrebundleImportsForDevice(code, preserveVendorImports) {
|
|
522
|
+
- const imports = collectTopLevelImportRecords(code);
|
|
523
|
+
+ // Re-export statements (`export { x } from`/`export * from`) carry specifiers
|
|
524
|
+
+ // too — vite's importAnalysis rewrites them to `.vite/deps?v=` URLs the same
|
|
525
|
+
+ // as `import` declarations, so they need the same decode. Barrel modules
|
|
526
|
+
+ // (e.g. a linked framework package's index) are nothing but re-exports.
|
|
527
|
+
+ const imports = collectTopLevelImportRecords(code, true);
|
|
528
|
+
if (!imports.length) {
|
|
529
|
+
return code;
|
|
530
|
+
}
|
|
531
|
+
diff --git a/hmr/server/hmr-module-graph.js b/hmr/server/hmr-module-graph.js
|
|
532
|
+
index 8cff593b8ac8d8eff82ebdd398c1305a8408d308..92f6d194924b288864bcaca4fc42ef805d048e4f 100644
|
|
533
|
+
--- a/hmr/server/hmr-module-graph.js
|
|
534
|
+
+++ b/hmr/server/hmr-module-graph.js
|
|
535
|
+
@@ -1,3 +1,4 @@
|
|
536
|
+
+import { normalizeHmrModuleId } from './hmr-module-id.js';
|
|
537
|
+
import { matchesRuntimeGraphModuleId } from './runtime-graph-filter.js';
|
|
538
|
+
import { classifyGraphUpsert, shouldBroadcastGraphUpsertDelta, shouldBumpGraphVersion } from './websocket-graph-upsert.js';
|
|
539
|
+
import { getProjectAppVirtualPath } from '../../helpers/utils.js';
|
|
540
|
+
@@ -39,25 +40,9 @@ export class HmrModuleGraph {
|
|
541
|
+
return ('00000000' + (h >>> 0).toString(16)).slice(-8);
|
|
542
|
+
}
|
|
543
|
+
normalizeGraphId(raw) {
|
|
544
|
+
- if (!raw)
|
|
545
|
+
- return raw;
|
|
546
|
+
- let id = raw.split('?')[0].replace(/\\/g, '/');
|
|
547
|
+
- id = id.replace(/^file:\/\//, '');
|
|
548
|
+
- const pluginRoot = this.deps.getPluginRoot();
|
|
549
|
+
- if (pluginRoot) {
|
|
550
|
+
- const rootNorm = pluginRoot.replace(/\\/g, '/');
|
|
551
|
+
- if (id.startsWith(rootNorm)) {
|
|
552
|
+
- id = id.slice(rootNorm.length);
|
|
553
|
+
- }
|
|
554
|
+
- }
|
|
555
|
+
- if (!id.startsWith('/'))
|
|
556
|
+
- id = '/' + id;
|
|
557
|
+
- // Collapse nested app root indicators when present (defensive)
|
|
558
|
+
- const idx = id.indexOf(APP_VIRTUAL_WITH_SLASH);
|
|
559
|
+
- if (idx !== -1)
|
|
560
|
+
- id = id.slice(idx);
|
|
561
|
+
- return id;
|
|
562
|
+
+ return normalizeHmrModuleId(raw, this.deps.getPluginRoot());
|
|
563
|
+
}
|
|
564
|
+
+
|
|
565
|
+
// Dependency-closed, topologically sorted list of modules for a set of
|
|
566
|
+
// changed ids. Only includes application modules we can serve (under the
|
|
567
|
+
// app virtual root and known framework/.ts/.js entries already in the graph).
|
|
568
|
+
diff --git a/hmr/server/hmr-module-id.js b/hmr/server/hmr-module-id.js
|
|
569
|
+
new file mode 100644
|
|
570
|
+
index 0000000000000000000000000000000000000000..13a0c29d4b0fad502730062ddba081016514c440
|
|
571
|
+
--- /dev/null
|
|
572
|
+
+++ b/hmr/server/hmr-module-id.js
|
|
573
|
+
@@ -0,0 +1,30 @@
|
|
574
|
+
+import { existsSync } from 'node:fs';
|
|
575
|
+
+import * as path from 'node:path';
|
|
576
|
+
+import { getMonorepoWorkspaceRoot } from '../../helpers/project.js';
|
|
577
|
+
+import { rewriteFsAbsoluteToNsM } from './websocket-module-specifiers.js';
|
|
578
|
+
+
|
|
579
|
+
+// Use the same app/workspace/@fs spelling as static device imports. App
|
|
580
|
+
+// virtual IDs remain intact; an unrelated /src/ substring is never a root.
|
|
581
|
+
+export function normalizeHmrModuleId(raw, projectRoot) {
|
|
582
|
+
+ if (!raw) return raw;
|
|
583
|
+
+ let id = raw.split(/[?#]/)[0].replace(/\\/g, '/');
|
|
584
|
+
+ if (id.startsWith('/ns/m/')) return id.slice('/ns/m'.length);
|
|
585
|
+
+ const fileUrl = id.startsWith('file://');
|
|
586
|
+
+ if (fileUrl) id = id.slice('file://'.length);
|
|
587
|
+
+ const fsUrl = id.startsWith('/@fs/');
|
|
588
|
+
+ if (fsUrl) id = id.slice('/@fs'.length);
|
|
589
|
+
+ const root = projectRoot?.replace(/\\/g, '/').replace(/\/$/, '');
|
|
590
|
+
+ const within = (base) => base && (id === base || id.startsWith(base + '/'));
|
|
591
|
+
+ // Preserve ordinary app IDs, including Windows drive paths, without
|
|
592
|
+
+ // passing a drive-letter source through POSIX /@fs parsing.
|
|
593
|
+
+ if (within(root)) return id.slice(root.length) || '/';
|
|
594
|
+
+ const workspace = root ? getMonorepoWorkspaceRoot(root) : null;
|
|
595
|
+
+ if (root && id.startsWith('/../')) id = path.resolve(root, '.' + id).replace(/\\/g, '/');
|
|
596
|
+
+ if (root && (fileUrl || fsUrl || within(root) || within(workspace) || (path.isAbsolute(id) && existsSync(id)))) {
|
|
597
|
+
+ const url = rewriteFsAbsoluteToNsM('/@fs' + id, root, workspace);
|
|
598
|
+
+ // The module route serves explicit /@fs paths for linked sources
|
|
599
|
+
+ // outside both roots, matching rewriteImports' existing fallback.
|
|
600
|
+
+ return url ? url.slice('/ns/m'.length) : '/@fs' + id;
|
|
601
|
+
+ }
|
|
602
|
+
+ return id.startsWith('/') ? id : '/' + id;
|
|
603
|
+
+}
|
|
604
|
+
diff --git a/hmr/server/process-code-for-device.js b/hmr/server/process-code-for-device.js
|
|
605
|
+
index 1f02ba5ebb7e89d40eff58d1c395b5ec838f45fe..808ed238e795fd935d2a34623479fc08a285d547 100644
|
|
606
|
+
--- a/hmr/server/process-code-for-device.js
|
|
607
|
+
+++ b/hmr/server/process-code-for-device.js
|
|
608
|
+
@@ -1,3 +1,5 @@
|
|
609
|
+
+import { normalizeHmrModuleId } from './hmr-module-id.js';
|
|
610
|
+
+import { CSS_MODULE_RE } from './css-device-module.js';
|
|
611
|
+
// Device code-transform: cleans Vite/framework noise out of a served module,
|
|
612
|
+
// injects NativeScript build globals + the process.env shim, normalizes
|
|
613
|
+
// imports/helpers for the on-device ESM runtime, and collects an importer's
|
|
614
|
+
@@ -125,25 +127,10 @@ export function inlineNsConfigVirtualImports(code) {
|
|
615
|
+
// `hmr/client/hot-context.ts` so cold-boot evaluation and HMR re-evaluation
|
|
616
|
+
// resolve the same `hot.data` entry.
|
|
617
|
+
export function computeHotContextId(sourceId, projectRoot) {
|
|
618
|
+
- if (!sourceId || typeof sourceId !== 'string')
|
|
619
|
+
- return null;
|
|
620
|
+
- let id = sourceId.split('?')[0].split('#')[0].replace(/\\/g, '/');
|
|
621
|
+
- if (!id)
|
|
622
|
+
- return null;
|
|
623
|
+
- id = id.replace(/^\/@fs/, '');
|
|
624
|
+
- if (projectRoot) {
|
|
625
|
+
- const rootPosix = projectRoot.replace(/\\/g, '/').replace(/\/$/, '');
|
|
626
|
+
- if (rootPosix && id.startsWith(rootPosix + '/')) {
|
|
627
|
+
- id = id.slice(rootPosix.length);
|
|
628
|
+
- }
|
|
629
|
+
- }
|
|
630
|
+
- if (id.startsWith('/ns/m/'))
|
|
631
|
+
- id = id.slice('/ns/m'.length);
|
|
632
|
+
- id = id.replace(/\.(ts|tsx|js|jsx|mjs|mts|cts)$/i, '');
|
|
633
|
+
- if (!id.startsWith('/'))
|
|
634
|
+
- id = '/' + id;
|
|
635
|
+
- return id;
|
|
636
|
+
+ if (!sourceId || typeof sourceId !== 'string') return null;
|
|
637
|
+
+ return normalizeHmrModuleId(sourceId, projectRoot).replace(/\.(ts|tsx|tsrx|js|jsx|mjs|mts|cts)$/i, '');
|
|
638
|
+
}
|
|
639
|
+
+
|
|
640
|
+
// One-line `import.meta.hot` prelude. Single-statement, no internal `;` or
|
|
641
|
+
// newline, so that if any later sanitize pass re-applies
|
|
642
|
+
// `IMPORT_META_HOT_ASSIGNMENT` the whole statement strips cleanly (module
|
|
643
|
+
@@ -263,6 +250,8 @@ function processCodeForDevice(code, isVitePreBundled, preserveVendorImports = fa
|
|
644
|
+
const bindingOptions = {
|
|
645
|
+
preserveNonPluginVendorImports: preserveVendorImports,
|
|
646
|
+
resolvedSpecifierOverrides,
|
|
647
|
+
+ importerId: sourceId,
|
|
648
|
+
+ importerIsLibrary: isNodeModule,
|
|
649
|
+
// Worker entries evaluate in their own realm, where the main realm's
|
|
650
|
+
// vendor registry / __nsRequire never exist — route their vendor
|
|
651
|
+
// imports to the per-module /ns/m/node_modules HTTP ESM form instead,
|
|
652
|
+
@@ -449,13 +438,13 @@ function processCodeForDevice(code, isVitePreBundled, preserveVendorImports = fa
|
|
653
|
+
// Unlike other virtual ids these are real, servable dev-server URLs returning
|
|
654
|
+
// self-contained ESM — stripping them leaves `_decorate`/`_decorateMetadata`
|
|
655
|
+
// undefined at runtime. They're origin-prefixed for the device in rewriteImports.
|
|
656
|
+
- result = result.replace(/import\s+[^;]+\s+from\s+["']\/@id\/(?!__x00__@oxc-project\+runtime)[^"']*["'];?\s*/g, '');
|
|
657
|
+
+ result = result.replace(/import\s+[^;]+\s+from\s+["'](\/@id\/(?!__x00__@oxc-project\+runtime)[^"']*)["'];?\s*/g, (statement, spec) => CSS_MODULE_RE.test(spec) ? statement : '');
|
|
658
|
+
// Also remove side-effect only virtual id imports like: import "/@id/__x00__vite/dynamic-import-helper.js";
|
|
659
|
+
// These can slip through and cause the NativeScript runtime to attempt resolving
|
|
660
|
+
// a non-existent physical file (e.g. /@id/__x00__vite/dynamic-import-helper.js) leading to
|
|
661
|
+
// module not found crashes during HMR evaluation.
|
|
662
|
+
if (/^[\t ]*import\s+["']\/@id\/[^"']+["'];?\s*$/m.test(result)) {
|
|
663
|
+
- result = result.replace(/^[\t ]*import\s+["']\/@id\/[^"']+["'];?\s*$/gm, '');
|
|
664
|
+
+ result = result.replace(/^[\t ]*import\s+["'](\/@id\/[^"']+)["'];?\s*$/gm, (statement, spec) => CSS_MODULE_RE.test(spec) ? statement : '');
|
|
665
|
+
// Inject a lightweight marker comment (harmless if left in output) so devs can confirm rewrite took place when viewing streamed artifact.
|
|
666
|
+
result = `// [hmr-sanitize] stripped virtual /@id/ side-effect imports\n${result}`;
|
|
667
|
+
}
|
|
668
|
+
diff --git a/hmr/server/rewrite-imports.js b/hmr/server/rewrite-imports.js
|
|
669
|
+
index 51ad398cefe75c918e887bd9506d9152259b957e..57dc2be15705a5ac8b5393852fd5de411a88fd50 100644
|
|
670
|
+
--- a/hmr/server/rewrite-imports.js
|
|
671
|
+
+++ b/hmr/server/rewrite-imports.js
|
|
672
|
+
@@ -1,8 +1,9 @@
|
|
673
|
+
+import { CSS_MODULE_RE } from './css-device-module.js';
|
|
674
|
+
// THE SINGLE import-rewrite function — used everywhere for consistency. Maps a
|
|
675
|
+
// served module's specifiers to device-reachable forms: the unified /ns/core
|
|
676
|
+
// bridge, /ns/m node_modules + app modules, /ns/sfc for Vue, vendor bare specs,
|
|
677
|
+
// inlined JSON, and import.meta.url-relative dynamic imports.
|
|
678
|
+
-import { existsSync, readFileSync } from 'fs';
|
|
679
|
+
+import { existsSync, readFileSync, realpathSync } from 'fs';
|
|
680
|
+
import * as path from 'path';
|
|
681
|
+
import * as PAT from './constants.js';
|
|
682
|
+
import { getMonorepoWorkspaceRoot } from '../../helpers/project.js';
|
|
683
|
+
@@ -12,7 +13,139 @@ import { resolveAngularCoreHmrImportSource, rewriteAngularEntryRegisterOnly } fr
|
|
684
|
+
import { isNativeScriptCoreModule, isNativeScriptPluginModule, normalizeNativeScriptCoreSpecifier, normalizeNodeModulesSpecifier, resolveNodeModulesPackageBoundary, resolveVendorRouting, rewriteFsAbsoluteToNsM, shouldPreserveBareRuntimePluginSubpathImport } from './websocket-module-specifiers.js';
|
|
685
|
+
import { ensureDynamicHmrImportHelper } from './websocket-served-module-helpers.js';
|
|
686
|
+
import { collectMixedRuntimePluginHttpRootPackages, findDependencyFileName, getProjectRelativeImportPath, isApplicationImport, normalizeImportPath, stripToProjectRelative, toAppModuleBaseId, toNodeModulesHttpModuleId } from './device-transform-helpers.js';
|
|
687
|
+
+import { resolvePlatform } from '../../helpers/cli-flags.js';
|
|
688
|
+
const APP_ROOT_DIR = getProjectAppPath();
|
|
689
|
+
+// Bare-specifier fallback anchor: the generic `/ns/m/node_modules/<spec>`
|
|
690
|
+
+// URL resolves only from the app root, so a bare specifier imported by a
|
|
691
|
+
+// node_modules file whose package is not an app-level dependency — e.g.
|
|
692
|
+
+// storybook's `@storybook/global` sibling under pnpm's isolated layout —
|
|
693
|
+
+// 404s there. When the app-root node_modules ancestor walk misses, map the
|
|
694
|
+
+// importer to its absolute path and walk ITS ancestor chain for the package
|
|
695
|
+
+// (the same lookup Node performs for the import), then anchor the URL at
|
|
696
|
+
+// the real package dir via the /ns/m /@fs route.
|
|
697
|
+
+const barePackageNameOf = (spec) =>
|
|
698
|
+
+ spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
|
|
699
|
+
+const bareSpecifierHttpFallback = (spec, importerPath, projectRoot) => {
|
|
700
|
+
+ const pkg = barePackageNameOf(spec);
|
|
701
|
+
+ const subpath = spec.slice(pkg.length);
|
|
702
|
+
+ let dir = projectRoot;
|
|
703
|
+
+ for (;;) {
|
|
704
|
+
+ if (existsSync(path.join(dir, 'node_modules', pkg, 'package.json')))
|
|
705
|
+
+ return `/ns/m/node_modules/${spec}`;
|
|
706
|
+
+ const parent = path.dirname(dir);
|
|
707
|
+
+ if (parent === dir)
|
|
708
|
+
+ break;
|
|
709
|
+
+ dir = parent;
|
|
710
|
+
+ }
|
|
711
|
+
+ let importerAbs = null;
|
|
712
|
+
+ if (importerPath.startsWith('/@fs/'))
|
|
713
|
+
+ importerAbs = importerPath.slice('/@fs'.length);
|
|
714
|
+
+ else if (importerPath.startsWith('/'))
|
|
715
|
+
+ importerAbs = path.join(projectRoot, `.${importerPath}`);
|
|
716
|
+
+ if (importerAbs) {
|
|
717
|
+
+ importerAbs = importerAbs.replace(PAT.QUERY_PATTERN, '');
|
|
718
|
+
+ try {
|
|
719
|
+
+ importerAbs = realpathSync(importerAbs);
|
|
720
|
+
+ }
|
|
721
|
+
+ catch { }
|
|
722
|
+
+ dir = path.dirname(importerAbs);
|
|
723
|
+
+ for (;;) {
|
|
724
|
+
+ const pkgDir = path.join(dir, 'node_modules', pkg);
|
|
725
|
+
+ if (existsSync(path.join(pkgDir, 'package.json')))
|
|
726
|
+
+ return `/ns/m/@fs${pkgDir}${subpath}`;
|
|
727
|
+
+ const parent = path.dirname(dir);
|
|
728
|
+
+ if (parent === dir)
|
|
729
|
+
+ break;
|
|
730
|
+
+ dir = parent;
|
|
731
|
+
+ }
|
|
732
|
+
+ }
|
|
733
|
+
+ return `/ns/m/node_modules/${spec}`;
|
|
734
|
+
+};
|
|
735
|
+
+// ── Package `imports` field (`#specifier`) resolution ─────────────────────
|
|
736
|
+
+// A `#`-prefixed specifier resolves through the `imports` field of the
|
|
737
|
+
+// importer's own package.json (Node "package imports" — e.g. octane's
|
|
738
|
+
+// `#octane/dist/signal-actions/graph`). Served node_modules files are raw-read
|
|
739
|
+
+// by the /ns/m route without Vite import analysis, and the bare-npm fallback
|
|
740
|
+
+// below rejects `#` outright (bareNpmRe requires an alphanumeric first char),
|
|
741
|
+
+// so the literal specifier reached the device loader as "Cannot find module".
|
|
742
|
+
+// Device-visible conditions: `import` (ESM), `native`, the active platform —
|
|
743
|
+
+// `node`, `require`, and build-time conditions like `octane-islands` are
|
|
744
|
+
+// intentionally absent.
|
|
745
|
+
+function resolveImportsConditionalTarget(value, conditions) {
|
|
746
|
+
+ while (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
747
|
+
+ let next;
|
|
748
|
+
+ for (const condition of Object.keys(value)) {
|
|
749
|
+
+ if (condition === 'default' || conditions.has(condition)) {
|
|
750
|
+
+ next = value[condition];
|
|
751
|
+
+ break;
|
|
752
|
+
+ }
|
|
753
|
+
+ }
|
|
754
|
+
+ value = next;
|
|
755
|
+
+ }
|
|
756
|
+
+ return typeof value === 'string' ? value : null;
|
|
757
|
+
+}
|
|
758
|
+
+function resolvePackageImportsSpecifier(spec, importerPath, projectRoot, verbose) {
|
|
759
|
+
+ let importerAbs;
|
|
760
|
+
+ if (importerPath.startsWith('/@fs/')) {
|
|
761
|
+
+ importerAbs = importerPath.slice('/@fs'.length);
|
|
762
|
+
+ }
|
|
763
|
+
+ else if (importerPath.startsWith('/')) {
|
|
764
|
+
+ importerAbs = path.join(projectRoot, `.${importerPath}`);
|
|
765
|
+
+ }
|
|
766
|
+
+ else {
|
|
767
|
+
+ return null;
|
|
768
|
+
+ }
|
|
769
|
+
+ try {
|
|
770
|
+
+ importerAbs = importerAbs.replace(PAT.QUERY_PATTERN, '');
|
|
771
|
+
+ let dir = path.dirname(importerAbs);
|
|
772
|
+
+ // The `imports` field is scoped to the importer's nearest enclosing
|
|
773
|
+
+ // package.json — the same lookup Node performs.
|
|
774
|
+
+ for (;;) {
|
|
775
|
+
+ const packageJsonPath = path.join(dir, 'package.json');
|
|
776
|
+
+ if (existsSync(packageJsonPath)) {
|
|
777
|
+
+ const pkgJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
|
|
778
|
+
+ const importsField = pkgJson.imports;
|
|
779
|
+
+ if (!importsField || typeof importsField !== 'object' || Array.isArray(importsField) || !pkgJson.name)
|
|
780
|
+
+ return null;
|
|
781
|
+
+ const conditions = new Set(['default', 'import', 'native', resolvePlatform()].filter(Boolean));
|
|
782
|
+
+ const exactMatch = Object.hasOwn(importsField, spec);
|
|
783
|
+
+ let target = exactMatch
|
|
784
|
+
+ ? resolveImportsConditionalTarget(importsField[spec], conditions)
|
|
785
|
+
+ : null;
|
|
786
|
+
+ if (!exactMatch && target === null) {
|
|
787
|
+
+ for (const key of Object.keys(importsField)) {
|
|
788
|
+
+ const star = key.indexOf('*');
|
|
789
|
+
+ if (star === -1)
|
|
790
|
+
+ continue;
|
|
791
|
+
+ const pre = key.slice(0, star);
|
|
792
|
+
+ const post = key.slice(star + 1);
|
|
793
|
+
+ if (spec.length < pre.length + post.length || !spec.startsWith(pre) || !spec.endsWith(post))
|
|
794
|
+
+ continue;
|
|
795
|
+
+ const matched = spec.slice(pre.length, spec.length - post.length);
|
|
796
|
+
+ const patternTarget = resolveImportsConditionalTarget(importsField[key], conditions);
|
|
797
|
+
+ target = typeof patternTarget === 'string' ? patternTarget.replaceAll('*', matched) : null;
|
|
798
|
+
+ break;
|
|
799
|
+
+ }
|
|
800
|
+
+ }
|
|
801
|
+
+ // Only `./`-relative targets can be expressed as a device URL
|
|
802
|
+
+ // (bare-specifier targets are rare and keep falling through).
|
|
803
|
+
+ if (typeof target !== 'string' || !target.startsWith('./'))
|
|
804
|
+
+ return null;
|
|
805
|
+
+ const out = `/ns/m/node_modules/${pkgJson.name}/${target.slice(2)}`;
|
|
806
|
+
+ if (verbose)
|
|
807
|
+
+ console.log(`[rewrite] imports-field specifier: ${spec} → ${out}`);
|
|
808
|
+
+ return out;
|
|
809
|
+
+ }
|
|
810
|
+
+ const parent = path.dirname(dir);
|
|
811
|
+
+ if (parent === dir)
|
|
812
|
+
+ return null;
|
|
813
|
+
+ dir = parent;
|
|
814
|
+
+ }
|
|
815
|
+
+ }
|
|
816
|
+
+ catch {
|
|
817
|
+
+ return null;
|
|
818
|
+
+ }
|
|
819
|
+
+}
|
|
820
|
+
export function prepareAngularEntryForDevice(code, importerPath, sfcFileMap, depFileMap, projectRoot, verbose = false, outputDirOverrideRel, httpOrigin, resolveVendorAsHttp = false) {
|
|
821
|
+
const rewrittenCode = rewriteImports(code, importerPath, sfcFileMap, depFileMap, projectRoot, verbose, outputDirOverrideRel, httpOrigin, resolveVendorAsHttp);
|
|
822
|
+
return rewriteAngularEntryRegisterOnly(rewrittenCode, resolveAngularCoreHmrImportSource(rewrittenCode, httpOrigin));
|
|
823
|
+
@@ -239,6 +372,19 @@ export function rewriteImports(code, importerPath, sfcFileMap, depFileMap, proje
|
|
824
|
+
}
|
|
825
|
+
return `${prefix}${stub}${suffix}`;
|
|
826
|
+
}
|
|
827
|
+
+ // `#`-prefixed package-imports specifier (Node `imports` field, e.g.
|
|
828
|
+
+ // octane's `#octane/dist/signal-actions/graph`). Resolved through the
|
|
829
|
+
+ // importer's own package.json — the bare-npm branches below reject it.
|
|
830
|
+
+ if (spec.startsWith('#')) {
|
|
831
|
+
+ const importsOut = resolvePackageImportsSpecifier(spec, importerPath, projectRoot, verbose);
|
|
832
|
+
+ if (importsOut) {
|
|
833
|
+
+ if (httpOriginSafe) {
|
|
834
|
+
+ return `${prefix}${httpOriginSafe}${importsOut}${suffix}`;
|
|
835
|
+
+ }
|
|
836
|
+
+ return `${prefix}${importsOut}${suffix}`;
|
|
837
|
+
+ }
|
|
838
|
+
+ return `${prefix}${spec}${suffix}`;
|
|
839
|
+
+ }
|
|
840
|
+
spec = normalizeNativeScriptCoreSpecifier(spec);
|
|
841
|
+
// Pull `/@fs/<abs-path>` URLs back into the `/ns/m/` pipeline so they
|
|
842
|
+
// hit our CJS/UMD-wrapping handler. Vite emits `/@fs/...` for any
|
|
843
|
+
@@ -256,17 +402,39 @@ export function rewriteImports(code, importerPath, sfcFileMap, depFileMap, proje
|
|
844
|
+
}
|
|
845
|
+
return `${prefix}${rewritten}${suffix}`;
|
|
846
|
+
}
|
|
847
|
+
- // Path resolves outside both roots — leave Vite's URL alone as a
|
|
848
|
+
- // last resort. The original behaviour was to fall through here
|
|
849
|
+
- // and let downstream branches (e.g. `normalizeNodeModulesSpecifier`)
|
|
850
|
+
- // handle paths whose abs form happens to contain `/node_modules/`,
|
|
851
|
+
- // so preserve that for the unrewritable case below.
|
|
852
|
+
+ // Path resolves outside both roots — the `link:`/`workspace:` case,
|
|
853
|
+
+ // where a package's realpath lives in another checkout entirely.
|
|
854
|
+
+ // A raw /@fs URL makes the device fetch vite's standard middleware
|
|
855
|
+
+ // response, bypassing the device transform: optimizer
|
|
856
|
+
+ // `.vite/deps?v=` specifiers inside reach the runtime unrewritten
|
|
857
|
+
+ // and 504 once the optimizer re-commits its browserHash. The /ns/m
|
|
858
|
+
+ // route already resolves an absolute `/@fs` spec through the full
|
|
859
|
+
+ // device pipeline, so route it there. Paths whose realpath still
|
|
860
|
+
+ // contains /node_modules/ keep falling through to the bare-package
|
|
861
|
+
+ // branch below (upstream behavior).
|
|
862
|
+
+ if (!spec.includes('/node_modules/')) {
|
|
863
|
+
+ const out = `/ns/m${spec}`;
|
|
864
|
+
+ if (httpOriginSafe) {
|
|
865
|
+
+ return `${prefix}${httpOriginSafe}${out}${suffix}`;
|
|
866
|
+
+ }
|
|
867
|
+
+ return `${prefix}${out}${suffix}`;
|
|
868
|
+
+ }
|
|
869
|
+
+ // Path resolves outside both roots but still names a node_modules
|
|
870
|
+
+ // file — leave Vite's URL alone as a last resort. The original
|
|
871
|
+
+ // behaviour was to fall through here and let downstream branches
|
|
872
|
+
+ // (e.g. `normalizeNodeModulesSpecifier`) handle paths whose abs
|
|
873
|
+
+ // form happens to contain `/node_modules/`, so preserve that for
|
|
874
|
+
+ // the unrewritable case below.
|
|
875
|
+
}
|
|
876
|
+
// Vite 8 oxc runtime helpers (decorators etc.) — emitted as
|
|
877
|
+
// `/@id/__x00__@oxc-project+runtime@<ver>/helpers/<name>.js`. These are
|
|
878
|
+
// real dev-server URLs serving self-contained ESM, so just origin-prefix
|
|
879
|
+
// them for the device; no /ns/m wrapping needed (processCodeForDevice
|
|
880
|
+
// exempts them from the generic /@id/ strip for the same reason).
|
|
881
|
+
+ // User virtual CSS needs native compilation/registration, never the DOM module.
|
|
882
|
+
+ if (spec.startsWith('/@id/') && CSS_MODULE_RE.test(spec)) {
|
|
883
|
+
+ return `${prefix}${httpOriginSafe || ''}/ns/m${spec}${suffix}`;
|
|
884
|
+
+ }
|
|
885
|
+
if (spec.startsWith('/@id/__x00__@oxc-project+runtime')) {
|
|
886
|
+
if (httpOriginSafe) {
|
|
887
|
+
return `${prefix}${httpOriginSafe}${spec}${suffix}`;
|
|
888
|
+
@@ -510,7 +678,7 @@ export function rewriteImports(code, importerPath, sfcFileMap, depFileMap, proje
|
|
889
|
+
// root internally, which also lands here. Reached only after the
|
|
890
|
+
// bare-vendor-routing block above, so a non-Solid project that
|
|
891
|
+
// genuinely vendors solid-js is already handled and never gets here.
|
|
892
|
+
- const httpSpec = spec === 'solid-js' ? `/ns/m/node_modules/solid-js/dist/dev.js` : `/ns/m/node_modules/${spec}`;
|
|
893
|
+
+ const httpSpec = spec === 'solid-js' ? `/ns/m/node_modules/solid-js/dist/dev.js` : bareSpecifierHttpFallback(spec, importerPath, projectRoot);
|
|
894
|
+
if (httpOriginSafe) {
|
|
895
|
+
return `${prefix}${httpOriginSafe}${httpSpec}${suffix}`;
|
|
896
|
+
}
|
|
897
|
+
diff --git a/hmr/server/transform-cache-invalidation.js b/hmr/server/transform-cache-invalidation.js
|
|
898
|
+
index c4ee7fbd75d8e630e1702b08f4c1b6f7fc4f27bd..27a2e64215c592eec176fe9fdc6f5ccad7a8ca51 100644
|
|
899
|
+
--- a/hmr/server/transform-cache-invalidation.js
|
|
900
|
+
+++ b/hmr/server/transform-cache-invalidation.js
|
|
901
|
+
@@ -1,3 +1,4 @@
|
|
902
|
+
+import { statSync } from 'node:fs';
|
|
903
|
+
import { isRuntimeGraphExcludedPath, normalizeRuntimeGraphPath } from './runtime-graph-filter.js';
|
|
904
|
+
// Framework-agnostic transform-cache-invalidation primitives shared by the
|
|
905
|
+
// per-flavor `handleHotUpdate` tails (Angular + Solid today). They live in this
|
|
906
|
+
@@ -153,4 +154,36 @@ export function collectTransitiveImportersForInvalidation(options) {
|
|
907
|
+
}
|
|
908
|
+
return Array.from(collected.values());
|
|
909
|
+
}
|
|
910
|
+
+
|
|
911
|
+
+const servedFileFingerprints = new Map();
|
|
912
|
+
+/**
|
|
913
|
+
+ * Out-of-band mutation sentinel for served dependency files. Vite's watcher
|
|
914
|
+
+ * excludes node_modules, so a pnpm/bun patch install (or a manual
|
|
915
|
+
+ * node_modules edit) rewrites dependency sources without a file event —
|
|
916
|
+
+ * `handleHotUpdate` never runs and both transform caches keep serving the
|
|
917
|
+
+ * pre-install output. The `/ns/m` pipeline fingerprints each resolved
|
|
918
|
+
+ * dependency file the first time the dev server sees it and reports a change
|
|
919
|
+
+ * when (mtimeMs, size) differs on a later request; the caller invalidates the
|
|
920
|
+
+ * file's caches before re-transforming. The fingerprint records whatever was
|
|
921
|
+
+ * on disk at first serve, so only subsequent mutations count. A rewrite that
|
|
922
|
+
+ * preserves both mtime and byte size stays undetected — the documented bound
|
|
923
|
+
+ * of this check.
|
|
924
|
+
+ */
|
|
925
|
+
+export function servedDependencyFileChanged(file) {
|
|
926
|
+
+ let stat;
|
|
927
|
+
+ try {
|
|
928
|
+
+ stat = statSync(file);
|
|
929
|
+
+ }
|
|
930
|
+
+ catch {
|
|
931
|
+
+ return false;
|
|
932
|
+
+ }
|
|
933
|
+
+ if (!stat.isFile()) {
|
|
934
|
+
+ return false;
|
|
935
|
+
+ }
|
|
936
|
+
+ const key = file.replace(/\\/g, '/');
|
|
937
|
+
+ const fingerprint = `${stat.mtimeMs}:${stat.size}`;
|
|
938
|
+
+ const previous = servedFileFingerprints.get(key);
|
|
939
|
+
+ servedFileFingerprints.set(key, fingerprint);
|
|
940
|
+
+ return previous !== undefined && previous !== fingerprint;
|
|
941
|
+
+}
|
|
942
|
+
//# sourceMappingURL=transform-cache-invalidation.js.map
|
|
943
|
+
|
|
944
|
+
diff --git a/hmr/server/vite-plugin.js b/hmr/server/vite-plugin.js
|
|
945
|
+
index 15c6c7293826767ce7fd45feb6b03cb64a4bdbb5..1f66ca8ae896fad9ee21eabdf3bb75f609bd7132 100644
|
|
946
|
+
--- a/hmr/server/vite-plugin.js
|
|
947
|
+
+++ b/hmr/server/vite-plugin.js
|
|
948
|
+
@@ -4,7 +4,7 @@ import path from 'path';
|
|
949
|
+
import { pathToFileURL } from 'url';
|
|
950
|
+
import { NS_DEFAULT_DEV_FEATURE_FLAGS, NS_DEFAULT_HOST_MODULES } from '../shared/runtime/browser-runtime-contract.js';
|
|
951
|
+
import { resolveDeviceReachableHost } from '../../helpers/dev-host.js';
|
|
952
|
+
-import { setUserDefineEntries } from '../../helpers/global-defines.js';
|
|
953
|
+
+import { setUserAliasEntries, setUserDefineEntries } from '../../helpers/global-defines.js';
|
|
954
|
+
import { getMonorepoWorkspaceRoot } from '../../helpers/project.js';
|
|
955
|
+
const require = createRequire(import.meta.url);
|
|
956
|
+
const VIRTUAL_ID = 'virtual:ns-hmr-client';
|
|
957
|
+
@@ -619,6 +619,9 @@ export function nsHmrClientVitePlugin(opts) {
|
|
958
|
+
// modules; without a shim a free `__FOO__` is mis-bound to /ns/rt → wrong
|
|
959
|
+
// value under HMR vs the production bundle). See setUserDefineEntries.
|
|
960
|
+
setUserDefineEntries(c.define);
|
|
961
|
+
+ // Mirror `resolve.alias` into the esbuild passes (deps bundle,
|
|
962
|
+
+ // vendor bundle) — see setUserAliasEntries / createViteAliasEsbuildPlugin.
|
|
963
|
+
+ setUserAliasEntries(c.resolve?.alias);
|
|
964
|
+
},
|
|
965
|
+
resolveId(id) {
|
|
966
|
+
if (id === VIRTUAL_ID)
|
|
967
|
+
diff --git a/hmr/server/websocket-core-bridge.js b/hmr/server/websocket-core-bridge.js
|
|
968
|
+
index 0d58dfc3e2254656cd910ddf2dde7845dd1cf595..8d57de97e60bbab854737f33391c2c6e345c64de 100644
|
|
969
|
+
--- a/hmr/server/websocket-core-bridge.js
|
|
970
|
+
+++ b/hmr/server/websocket-core-bridge.js
|
|
971
|
+
@@ -12,10 +12,12 @@ const REGEX_PRECEDING_KEYWORD_RE = /(?:^|[^$\w])(?:return|typeof|instanceof|in|o
|
|
972
|
+
/**
|
|
973
|
+
* Blank line and block comments (preserving newlines) so the regex export
|
|
974
|
+
* scanners never see a commented-out `export` declaration. String, template
|
|
975
|
+
- * and regex literals are skipped so their contents are left intact.
|
|
976
|
+
+ * and regex literals are skipped so their contents are left intact — pass
|
|
977
|
+
+ * `literals` to blank their interiors too (keeping quotes/positions) so the
|
|
978
|
+
+ * scanners can also trust keyword matches as real syntax.
|
|
979
|
+
*/
|
|
980
|
+
-export function maskJsComments(code) {
|
|
981
|
+
- if (!code || (code.indexOf('//') === -1 && code.indexOf('/*') === -1)) {
|
|
982
|
+
+export function maskJsComments(code, literals = false) {
|
|
983
|
+
+ if (!code || (!literals && code.indexOf('//') === -1 && code.indexOf('/*') === -1)) {
|
|
984
|
+
return code;
|
|
985
|
+
}
|
|
986
|
+
const chars = code.split('');
|
|
987
|
+
@@ -38,6 +40,82 @@ export function maskJsComments(code) {
|
|
988
|
+
return true;
|
|
989
|
+
return REGEX_PRECEDING_KEYWORD_RE.test(code.slice(Math.max(0, j - 10), j + 1));
|
|
990
|
+
};
|
|
991
|
+
+ // Skip a regex literal starting at `at`; returns the index just past it.
|
|
992
|
+
+ const skipRegex = (at) => {
|
|
993
|
+
+ let j = at + 1;
|
|
994
|
+
+ let inClass = false;
|
|
995
|
+
+ while (j < n && code[j] !== '\n') {
|
|
996
|
+
+ const r = code[j];
|
|
997
|
+
+ if (r === '\\') {
|
|
998
|
+
+ j += 2;
|
|
999
|
+
+ continue;
|
|
1000
|
+
+ }
|
|
1001
|
+
+ if (r === '[')
|
|
1002
|
+
+ inClass = true;
|
|
1003
|
+
+ else if (r === ']')
|
|
1004
|
+
+ inClass = false;
|
|
1005
|
+
+ else if (r === '/' && !inClass)
|
|
1006
|
+
+ break;
|
|
1007
|
+
+ j++;
|
|
1008
|
+
+ }
|
|
1009
|
+
+ return j + 1;
|
|
1010
|
+
+ };
|
|
1011
|
+
+ // Skip a string/template literal starting at `at`; returns the index just
|
|
1012
|
+
+ // past it. Template `${}` expressions may hold nested literals, comments
|
|
1013
|
+
+ // and regexes — a naive next-backtick scan closes early and desyncs every
|
|
1014
|
+
+ // later literal (`...it's...` inside a template opened a fake string).
|
|
1015
|
+
+ const skipQuoted = (at) => {
|
|
1016
|
+
+ const quote = code[at];
|
|
1017
|
+
+ let j = at + 1;
|
|
1018
|
+
+ if (quote !== '`') {
|
|
1019
|
+
+ while (j < n && code[j] !== quote)
|
|
1020
|
+
+ j += code[j] === '\\' ? 2 : 1;
|
|
1021
|
+
+ return j + 1;
|
|
1022
|
+
+ }
|
|
1023
|
+
+ while (j < n) {
|
|
1024
|
+
+ const t = code[j];
|
|
1025
|
+
+ if (t === '\\') {
|
|
1026
|
+
+ j += 2;
|
|
1027
|
+
+ continue;
|
|
1028
|
+
+ }
|
|
1029
|
+
+ if (t === '`')
|
|
1030
|
+
+ return j + 1;
|
|
1031
|
+
+ if (t === '$' && code[j + 1] === '{') {
|
|
1032
|
+
+ j += 2;
|
|
1033
|
+
+ let depth = 1;
|
|
1034
|
+
+ while (j < n && depth) {
|
|
1035
|
+
+ const e = code[j];
|
|
1036
|
+
+ const e2 = code[j + 1];
|
|
1037
|
+
+ if (e === "'" || e === '"' || e === '`') {
|
|
1038
|
+
+ j = skipQuoted(j);
|
|
1039
|
+
+ continue;
|
|
1040
|
+
+ }
|
|
1041
|
+
+ if (e === '/' && e2 === '/') {
|
|
1042
|
+
+ const eol = code.indexOf('\n', j);
|
|
1043
|
+
+ j = eol === -1 ? n : eol;
|
|
1044
|
+
+ continue;
|
|
1045
|
+
+ }
|
|
1046
|
+
+ if (e === '/' && e2 === '*') {
|
|
1047
|
+
+ const close = code.indexOf('*/', j + 2);
|
|
1048
|
+
+ j = close === -1 ? n : close + 2;
|
|
1049
|
+
+ continue;
|
|
1050
|
+
+ }
|
|
1051
|
+
+ if (e === '/' && slashStartsRegex(j)) {
|
|
1052
|
+
+ j = skipRegex(j);
|
|
1053
|
+
+ continue;
|
|
1054
|
+
+ }
|
|
1055
|
+
+ if (e === '{')
|
|
1056
|
+
+ depth++;
|
|
1057
|
+
+ else if (e === '}')
|
|
1058
|
+
+ depth--;
|
|
1059
|
+
+ j++;
|
|
1060
|
+
+ }
|
|
1061
|
+
+ continue;
|
|
1062
|
+
+ }
|
|
1063
|
+
+ j++;
|
|
1064
|
+
+ }
|
|
1065
|
+
+ return j;
|
|
1066
|
+
+ };
|
|
1067
|
+
let i = 0;
|
|
1068
|
+
while (i < n) {
|
|
1069
|
+
const c = code[i];
|
|
1070
|
+
@@ -55,30 +133,16 @@ export function maskJsComments(code) {
|
|
1071
|
+
i = stop;
|
|
1072
|
+
}
|
|
1073
|
+
else if (c === "'" || c === '"' || c === '`') {
|
|
1074
|
+
- i++;
|
|
1075
|
+
- while (i < n && code[i] !== c) {
|
|
1076
|
+
- i += code[i] === '\\' ? 2 : 1;
|
|
1077
|
+
- }
|
|
1078
|
+
- i++;
|
|
1079
|
+
+ const start = i;
|
|
1080
|
+
+ i = skipQuoted(i);
|
|
1081
|
+
+ if (literals)
|
|
1082
|
+
+ blank(start + 1, i - 1);
|
|
1083
|
+
}
|
|
1084
|
+
else if (c === '/' && slashStartsRegex(i)) {
|
|
1085
|
+
- i++;
|
|
1086
|
+
- let inClass = false;
|
|
1087
|
+
- while (i < n && code[i] !== '\n') {
|
|
1088
|
+
- const r = code[i];
|
|
1089
|
+
- if (r === '\\') {
|
|
1090
|
+
- i += 2;
|
|
1091
|
+
- continue;
|
|
1092
|
+
- }
|
|
1093
|
+
- if (r === '[')
|
|
1094
|
+
- inClass = true;
|
|
1095
|
+
- else if (r === ']')
|
|
1096
|
+
- inClass = false;
|
|
1097
|
+
- else if (r === '/' && !inClass)
|
|
1098
|
+
- break;
|
|
1099
|
+
- i++;
|
|
1100
|
+
- }
|
|
1101
|
+
- i++;
|
|
1102
|
+
+ const start = i;
|
|
1103
|
+
+ i = skipRegex(i);
|
|
1104
|
+
+ if (literals)
|
|
1105
|
+
+ blank(start, i);
|
|
1106
|
+
}
|
|
1107
|
+
else {
|
|
1108
|
+
i++;
|
|
1109
|
+
diff --git a/hmr/server/websocket-module-bindings.js b/hmr/server/websocket-module-bindings.js
|
|
1110
|
+
index 00b89ff3ae13b1c2b219a4c35c0450f97ac5ffc9..54c8716bfc5c9a6e2cd9cbee7bbbe9c7fb971943 100644
|
|
1111
|
+
--- a/hmr/server/websocket-module-bindings.js
|
|
1112
|
+
+++ b/hmr/server/websocket-module-bindings.js
|
|
1113
|
+
@@ -5,7 +5,7 @@ import * as PAT from './constants.js';
|
|
1114
|
+
import { astExtractImportsAndStripTypes } from '../helpers/ast-extract.js';
|
|
1115
|
+
import { getProjectRootPath } from '../../helpers/project.js';
|
|
1116
|
+
import { extractRootPackageName } from '../shared/package-classifier.js';
|
|
1117
|
+
-import { isEsmFrameworkPackageSpecifier, isLikelyNativeScriptPluginSpecifier, isLikelyNativeScriptRuntimePluginSpecifier, normalizeNodeModulesSpecifier, resolveInternalRuntimePluginBareSpecifier, resolveNodeModulesPackageBoundary, resolveVendorFromCandidate, shouldPreserveBareRuntimePluginSubpathImport } from './websocket-module-specifiers.js';
|
|
1118
|
+
+import { isEsmFrameworkPackageSpecifier, isLikelyNativeScriptPluginSpecifier, isLikelyNativeScriptRuntimePluginSpecifier, normalizeNodeModulesSpecifier, resolveInternalRuntimePluginBareSpecifier, resolveNodeModulesPackageBoundary, resolvePackageInternalVendorFileSpecifier, resolveVendorFromCandidate, shouldPreserveBareRuntimePluginSubpathImport } from './websocket-module-specifiers.js';
|
|
1119
|
+
import { MODULE_IMPORT_ANALYSIS_PLUGINS } from './websocket-served-module-helpers.js';
|
|
1120
|
+
import { getVendorManifest } from '../shared/vendor/registry.js';
|
|
1121
|
+
/**
|
|
1122
|
+
@@ -252,6 +252,18 @@ export function ensureNativeScriptModuleBindings(code, options) {
|
|
1123
|
+
canonical = null;
|
|
1124
|
+
}
|
|
1125
|
+
const runtimePluginSpecifier = isLikelyNativeScriptRuntimePluginSpecifier(canonical || specifier, getProjectRootPath());
|
|
1126
|
+
+ // Library files served per-module (cold boot — no deps bundle
|
|
1127
|
+
+ // yet) get static HTTP vendor imports so ESM evaluation order and
|
|
1128
|
+
+ // live bindings hold: a registry require evaluates the importer
|
|
1129
|
+
+ // before the vendored module and reads stubs/empty defaults
|
|
1130
|
+
+ // (gesturehandler.common's `extends Observable`). Package-internal
|
|
1131
|
+
+ // non-entry files keep their concrete subpath; everything else
|
|
1132
|
+
+ // uses the root URL form the import map and vendor.mjs share.
|
|
1133
|
+
+ if (options?.importerIsLibrary && !options?.vendorImportsAsHttp && canonical && !/^@nativescript\/core(\b|\/)/i.test(canonical)) {
|
|
1134
|
+
+ const internalVendorSpecifier = resolvePackageInternalVendorFileSpecifier(specifier, options?.importerId, canonical);
|
|
1135
|
+
+ preservedImports.push(rewritePreservedImportSpecifier(original, rawSpec, `/ns/m/node_modules/${internalVendorSpecifier || canonical}`));
|
|
1136
|
+
+ continue;
|
|
1137
|
+
+ }
|
|
1138
|
+
// Preserving a bare vendor id is only correct where the IMPORT MAP
|
|
1139
|
+
// exists to route it (main realm). Worker realms have no import map —
|
|
1140
|
+
// a preserved bare specifier falls through to the runtime's
|
|
1141
|
+
@@ -309,6 +321,14 @@ export function ensureNativeScriptModuleBindings(code, options) {
|
|
1142
|
+
canonical = null;
|
|
1143
|
+
}
|
|
1144
|
+
const runtimePluginSpecifier = isLikelyNativeScriptRuntimePluginSpecifier(canonical || specifier, getProjectRootPath());
|
|
1145
|
+
+ // Library files served per-module (cold boot) get static HTTP vendor
|
|
1146
|
+
+ // imports — see the side-effect branch above. Package-internal
|
|
1147
|
+
+ // non-entry files keep their concrete subpath.
|
|
1148
|
+
+ if (options?.importerIsLibrary && !options?.vendorImportsAsHttp && canonical && !/^@nativescript\/core(\b|\/)/i.test(canonical)) {
|
|
1149
|
+
+ const internalVendorSpecifier = resolvePackageInternalVendorFileSpecifier(specifier, options?.importerId, canonical);
|
|
1150
|
+
+ preservedImports.push(rewritePreservedImportSpecifier(original, rawSpec, `/ns/m/node_modules/${internalVendorSpecifier || canonical}`));
|
|
1151
|
+
+ continue;
|
|
1152
|
+
+ }
|
|
1153
|
+
// See the side-effect branch above: bare preservation relies on the main
|
|
1154
|
+
// realm's import map; in a worker serve (vendorImportsAsHttp) it must not
|
|
1155
|
+
// win over the /ns/m HTTP rewrite.
|
|
1156
|
+
diff --git a/hmr/server/websocket-module-specifiers.js b/hmr/server/websocket-module-specifiers.js
|
|
1157
|
+
index 0081819906b9df7480408697b1afadb149e26e31..ae7ef0adf8b810cbeff74f26bce242d750129c06 100644
|
|
1158
|
+
--- a/hmr/server/websocket-module-specifiers.js
|
|
1159
|
+
+++ b/hmr/server/websocket-module-specifiers.js
|
|
1160
|
+
@@ -1,4 +1,5 @@
|
|
1161
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'fs';
|
|
1162
|
+
+import { createRequire } from 'module';
|
|
1163
|
+
import * as path from 'path';
|
|
1164
|
+
import * as PAT from './constants.js';
|
|
1165
|
+
import { getVendorManifest, resolveVendorSpecifier } from '../shared/vendor/registry.js';
|
|
1166
|
+
@@ -328,6 +329,24 @@ export function resolveVendorFromCandidate(specifier) {
|
|
1167
|
+
}
|
|
1168
|
+
return null;
|
|
1169
|
+
}
|
|
1170
|
+
+const pnpmStoreDirsCache = new Map();
|
|
1171
|
+
+// Upstream scans linked checkouts; retain only the app-local pnpm store fallback.
|
|
1172
|
+
+function listPnpmStoreNodeModulesDirs(projectRoot) {
|
|
1173
|
+
+ const cached = pnpmStoreDirsCache.get(projectRoot);
|
|
1174
|
+
+ if (cached) return cached;
|
|
1175
|
+
+ const dirs = [];
|
|
1176
|
+
+ const store = path.join(projectRoot, 'node_modules', '.pnpm');
|
|
1177
|
+
+ try {
|
|
1178
|
+
+ for (const entry of readdirSync(store, { withFileTypes: true })) {
|
|
1179
|
+
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
|
|
1180
|
+
+ const dir = path.join(store, entry.name, 'node_modules');
|
|
1181
|
+
+ if (existsSync(dir)) dirs.push(dir);
|
|
1182
|
+
+ }
|
|
1183
|
+
+ }
|
|
1184
|
+
+ } catch {}
|
|
1185
|
+
+ pnpmStoreDirsCache.set(projectRoot, dirs);
|
|
1186
|
+
+ return dirs;
|
|
1187
|
+
+}
|
|
1188
|
+
const workspaceNodeModulesDirsCache = new Map();
|
|
1189
|
+
/**
|
|
1190
|
+
* `node_modules` dirs that can hold a package the served URL no longer
|
|
1191
|
+
@@ -485,6 +504,8 @@ export function resolveCandidateFilePath(candidate, projectRoot, workspaceRoot)
|
|
1192
|
+
return fromWorkspaceScan;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
+ const fromPnpmStore = probeNodeModulesTail(listPnpmStoreNodeModulesDirs(projectRoot));
|
|
1196
|
+
+ if (fromPnpmStore) return fromPnpmStore;
|
|
1197
|
+
// Linked source checkouts keep private node_modules outside both roots.
|
|
1198
|
+
// Only packages the app's own install lacks may come from them: each
|
|
1199
|
+
// extension/index variant is resolved separately, so a variant missing
|
|
1200
|
+
@@ -533,6 +554,8 @@ export function resolveCandidateFilePath(candidate, projectRoot, workspaceRoot)
|
|
1201
|
+
* Returns `null` when the absolute path is outside both roots; the
|
|
1202
|
+
* caller should then leave the original `/@fs/` URL alone (defensive).
|
|
1203
|
+
*/
|
|
1204
|
+
+const fsStoreCanonicalization = new Map();
|
|
1205
|
+
+
|
|
1206
|
+
export function rewriteFsAbsoluteToNsM(spec, projectRoot, workspaceRoot) {
|
|
1207
|
+
if (!spec || !spec.startsWith('/@fs/'))
|
|
1208
|
+
return null;
|
|
1209
|
+
@@ -566,6 +589,56 @@ export function rewriteFsAbsoluteToNsM(spec, projectRoot, workspaceRoot) {
|
|
1210
|
+
}
|
|
1211
|
+
if (rel === null)
|
|
1212
|
+
return null;
|
|
1213
|
+
+ // pnpm virtual-store paths (`node_modules/.pnpm/<store>/node_modules/<pkg>/<sub>`)
|
|
1214
|
+
+ // must not keep the store spelling — the same package is also served
|
|
1215
|
+
+ // canonically at `/ns/m/node_modules/<pkg>/<sub>` via the vendor route, and
|
|
1216
|
+
+ // two URL spellings evaluate two copies with separate module state
|
|
1217
|
+
+ // (observed: octane's element registry split — `registerElement` landed in
|
|
1218
|
+
+ // one copy, the driver consulted the other and threw `is not a registered
|
|
1219
|
+
+ // element`). Collapse to the canonical spelling only when the store
|
|
1220
|
+
+ // directory and the project-resolved package are the SAME realpath.
|
|
1221
|
+
+ const storeNodeModules = absPath.lastIndexOf('/node_modules/');
|
|
1222
|
+
+ if (storeNodeModules !== -1) {
|
|
1223
|
+
+ const pkgSub = absPath.slice(storeNodeModules + '/node_modules/'.length);
|
|
1224
|
+
+ const segments = pkgSub.split('/');
|
|
1225
|
+
+ const rootCount = segments[0]?.startsWith('@') ? 2 : 1;
|
|
1226
|
+
+ const pkgName = segments.slice(0, rootCount).join('/');
|
|
1227
|
+
+ const subpath = segments.slice(rootCount).join('/');
|
|
1228
|
+
+ if (pkgName && subpath) {
|
|
1229
|
+
+ const storePkgDir = absPath.slice(0, storeNodeModules + '/node_modules/'.length + pkgName.length);
|
|
1230
|
+
+ let canonical = fsStoreCanonicalization.get(storePkgDir);
|
|
1231
|
+
+ if (canonical === undefined) {
|
|
1232
|
+
+ canonical = null;
|
|
1233
|
+
+ try {
|
|
1234
|
+
+ const projectRequire = createRequire(path.join(projectRootPosix, 'package.json'));
|
|
1235
|
+
+ let pkgJsonPath = null;
|
|
1236
|
+
+ try {
|
|
1237
|
+
+ pkgJsonPath = projectRequire.resolve(`${pkgName}/package.json`);
|
|
1238
|
+
+ }
|
|
1239
|
+
+ catch {
|
|
1240
|
+
+ // `exports` maps that omit `./package.json` refuse the
|
|
1241
|
+
+ // subpath resolve — probe the require resolution dirs
|
|
1242
|
+
+ // directly, matching manifest-collect's fallback.
|
|
1243
|
+
+ for (const dir of projectRequire.resolve.paths(pkgName) ?? []) {
|
|
1244
|
+
+ const candidate = path.join(dir, pkgName, 'package.json');
|
|
1245
|
+
+ if (existsSync(candidate)) {
|
|
1246
|
+
+ pkgJsonPath = candidate;
|
|
1247
|
+
+ break;
|
|
1248
|
+
+ }
|
|
1249
|
+
+ }
|
|
1250
|
+
+ }
|
|
1251
|
+
+ if (pkgJsonPath && realpathSync(path.dirname(pkgJsonPath)) === realpathSync(storePkgDir)) {
|
|
1252
|
+
+ canonical = pkgName;
|
|
1253
|
+
+ }
|
|
1254
|
+
+ }
|
|
1255
|
+
+ catch { }
|
|
1256
|
+
+ fsStoreCanonicalization.set(storePkgDir, canonical);
|
|
1257
|
+
+ }
|
|
1258
|
+
+ if (canonical !== null) {
|
|
1259
|
+
+ return `/ns/m/node_modules/${canonical}/${subpath}${querySuffix}`;
|
|
1260
|
+
+ }
|
|
1261
|
+
+ }
|
|
1262
|
+
+ }
|
|
1263
|
+
return rel === '' ? `/ns/m${querySuffix}` : `/ns/m/${rel}${querySuffix}`;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
@@ -746,6 +819,26 @@ export function resolveNodeModulesPackageBoundary(nodeModulesSpec, projectRoot)
|
|
1267
|
+
return resolved;
|
|
1268
|
+
}
|
|
1269
|
+
const exportsReverseMapCache = new Map();
|
|
1270
|
+
+// Locate an installed package's package.json through Node's node_modules
|
|
1271
|
+
+// ancestor chain: hoisted workspaces (pnpm nodeLinker: hoisted, npm/yarn
|
|
1272
|
+
+// classic workspaces) install packages at the workspace root and the app's
|
|
1273
|
+
+// own node_modules may be empty, so a plain `projectRoot/node_modules/<pkg>`
|
|
1274
|
+
+// join misses packages that are resolvable at runtime.
|
|
1275
|
+
+function resolveInstalledPackageJsonPath(pkgName, projectRoot) {
|
|
1276
|
+
+ let dir = path.resolve(projectRoot || getProjectRootPath());
|
|
1277
|
+
+ for (;;) {
|
|
1278
|
+
+ const candidate = path.join(dir, 'node_modules', pkgName, 'package.json');
|
|
1279
|
+
+ if (existsSync(candidate)) {
|
|
1280
|
+
+ return candidate;
|
|
1281
|
+
+ }
|
|
1282
|
+
+ const parent = path.dirname(dir);
|
|
1283
|
+
+ if (parent === dir) {
|
|
1284
|
+
+ break;
|
|
1285
|
+
+ }
|
|
1286
|
+
+ dir = parent;
|
|
1287
|
+
+ }
|
|
1288
|
+
+ return null;
|
|
1289
|
+
+}
|
|
1290
|
+
function resolveExportConditionValue(conditions) {
|
|
1291
|
+
if (typeof conditions === 'string')
|
|
1292
|
+
return conditions;
|
|
1293
|
+
@@ -771,8 +864,8 @@ function getExportsReverseMap(pkgName, projectRoot) {
|
|
1294
|
+
return cached;
|
|
1295
|
+
const map = new Map();
|
|
1296
|
+
try {
|
|
1297
|
+
- const pkgJsonPath = path.join(projectRoot, 'node_modules', pkgName, 'package.json');
|
|
1298
|
+
- const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
|
|
1299
|
+
+ const pkgJsonPath = resolveInstalledPackageJsonPath(pkgName, projectRoot);
|
|
1300
|
+
+ const pkgJson = pkgJsonPath ? JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) : {};
|
|
1301
|
+
if (pkgJson.exports && typeof pkgJson.exports === 'object') {
|
|
1302
|
+
for (const [entryPoint, conditions] of Object.entries(pkgJson.exports)) {
|
|
1303
|
+
if (entryPoint.includes('*') || entryPoint.endsWith('.json'))
|
|
1304
|
+
@@ -973,4 +1066,43 @@ export function resolveVendorRouting(nodeModulesSpec, projectRoot) {
|
|
1305
|
+
}
|
|
1306
|
+
return { route: 'http' };
|
|
1307
|
+
}
|
|
1308
|
+
+/**
|
|
1309
|
+
+ * First-boot per-module serving: a vendored package's package-internal file
|
|
1310
|
+
+ * import (its own sibling module, after Vite resolution e.g.
|
|
1311
|
+
+ * `/node_modules/<pkg>/<file>` or `/@fs/.../node_modules/<pkg>/<file>`)
|
|
1312
|
+
+ * collapses to the package ROOT via findVendorPrefix, and its named imports
|
|
1313
|
+
+ * become vendor-registry picks of a module that never declares them —
|
|
1314
|
+
+ * `Class extends value undefined` (gesturehandler's
|
|
1315
|
+
+ * `./gesturehandler.common` → `BaseGestureRootView`). Keep the concrete file
|
|
1316
|
+
+ * on /ns/m: return the normalized `pkg/subpath` id when the importer lives
|
|
1317
|
+
+ * inside the same vendored package and the specifier targets a file that is
|
|
1318
|
+
+ * NOT the package's root entry. Platform/alias spellings of the root entry
|
|
1319
|
+
+ * still collapse so the package keeps one vendor record.
|
|
1320
|
+
+ */
|
|
1321
|
+
+export function resolvePackageInternalVendorFileSpecifier(specifier, importerId, canonical) {
|
|
1322
|
+
+ if (!specifier || !importerId || !canonical) {
|
|
1323
|
+
+ return null;
|
|
1324
|
+
+ }
|
|
1325
|
+
+ const importerPackage = extractRootPackageName(normalizeNodeModulesSpecifier(importerId));
|
|
1326
|
+
+ if (!importerPackage || importerPackage !== canonical) {
|
|
1327
|
+
+ return null;
|
|
1328
|
+
+ }
|
|
1329
|
+
+ const nodeModulesSpecifier = normalizeNodeModulesSpecifier(specifier);
|
|
1330
|
+
+ if (!nodeModulesSpecifier || !nodeModulesSpecifier.startsWith(`${importerPackage}/`)) {
|
|
1331
|
+
+ return null;
|
|
1332
|
+
+ }
|
|
1333
|
+
+ const subpath = nodeModulesSpecifier.slice(importerPackage.length + 1);
|
|
1334
|
+
+ if (!subpath) {
|
|
1335
|
+
+ return null;
|
|
1336
|
+
+ }
|
|
1337
|
+
+ const projectRoot = getProjectRootPath();
|
|
1338
|
+
+ if (getExportsReverseMap(importerPackage, projectRoot).get(subpath) === importerPackage) {
|
|
1339
|
+
+ return null;
|
|
1340
|
+
+ }
|
|
1341
|
+
+ if (subpathMatchesMainEntry(subpath, getPackageMainFieldInfo(importerPackage, projectRoot).mainEntries)) {
|
|
1342
|
+
+ return null;
|
|
1343
|
+
+ }
|
|
1344
|
+
+ return nodeModulesSpecifier;
|
|
1345
|
+
+}
|
|
1346
|
+
+
|
|
1347
|
+
//# sourceMappingURL=websocket-module-specifiers.js.map
|
|
1348
|
+
|
|
1349
|
+
diff --git a/hmr/server/websocket-ns-m-request.js b/hmr/server/websocket-ns-m-request.js
|
|
1350
|
+
index 0879633dc5ee172f16de82d5d24bebe2f6f7878f..2c3a7476b1fda40bb454aca5041829a095cb4610 100644
|
|
1351
|
+
--- a/hmr/server/websocket-ns-m-request.js
|
|
1352
|
+
+++ b/hmr/server/websocket-ns-m-request.js
|
|
1353
|
+
@@ -27,10 +27,15 @@ const MODULE_CANDIDATE_EXTS = ['ts', 'js', 'tsx', 'jsx', 'mjs', 'mts', 'cts', 'v
|
|
1354
|
+
*/
|
|
1355
|
+
function expandModuleCandidates(spec, hasExt, baseNoExt) {
|
|
1356
|
+
const platform = resolvePlatform();
|
|
1357
|
+
+ // Active platform first, then the remaining platform tags plus the shared
|
|
1358
|
+
+ // `native` tag split-entry packages use — a plugin shipping only
|
|
1359
|
+
+ // `index.native.js`, or an `index.android.js` fetched while resolving under
|
|
1360
|
+
+ // another platform, has no candidate otherwise.
|
|
1361
|
+
+ const suffixes = [...new Set([platform, 'ios', 'android', 'visionos', 'native'].filter(Boolean))];
|
|
1362
|
+
const candidates = hasExt ? [spec] : [];
|
|
1363
|
+
for (const base of [baseNoExt, `${baseNoExt}/index`]) {
|
|
1364
|
+
- if (platform) {
|
|
1365
|
+
- candidates.push(...MODULE_CANDIDATE_EXTS.map((ext) => `${base}.${platform}.${ext}`));
|
|
1366
|
+
+ for (const suffix of suffixes) {
|
|
1367
|
+
+ candidates.push(...MODULE_CANDIDATE_EXTS.map((ext) => `${base}.${suffix}.${ext}`));
|
|
1368
|
+
}
|
|
1369
|
+
candidates.push(...MODULE_CANDIDATE_EXTS.map((ext) => `${base}.${ext}`));
|
|
1370
|
+
}
|
|
1371
|
+
@@ -163,6 +168,24 @@ export function resolveFsAnchoredSpec(spec, serverRoot, workspaceRoot) {
|
|
1372
|
+
export async function resolveNsMTransformedModule(options) {
|
|
1373
|
+
const { context, transformRequest, resolveId, loadVirtualId, timeoutMs = 120000 } = options;
|
|
1374
|
+
const { spec, serverRoot, workspaceRoot, transformCandidates } = context;
|
|
1375
|
+
+ const notifyServedDependencyFile = options.notifyServedDependencyFile;
|
|
1376
|
+
+ // Dependency files can change without a Vite file event (patch installs
|
|
1377
|
+
+ // rewrite node_modules out of band). Report each resolved node_modules
|
|
1378
|
+
+ // path the pipeline is about to transform so the caller can compare it
|
|
1379
|
+
+ // with the fingerprint of what the caches last served and invalidate on
|
|
1380
|
+
+ // drift — see servedDependencyFileChanged in transform-cache-invalidation.
|
|
1381
|
+
+ const noteServedDependencyFile = (candidate) => {
|
|
1382
|
+
+ if (!notifyServedDependencyFile || !candidate.replace(/[?#].*$/, '').includes('/node_modules/')) {
|
|
1383
|
+
+ return;
|
|
1384
|
+
+ }
|
|
1385
|
+
+ try {
|
|
1386
|
+
+ const resolved = resolveCandidateFilePath(candidate, serverRoot, workspaceRoot);
|
|
1387
|
+
+ if (resolved) {
|
|
1388
|
+
+ notifyServedDependencyFile(resolved);
|
|
1389
|
+
+ }
|
|
1390
|
+
+ }
|
|
1391
|
+
+ catch { }
|
|
1392
|
+
+ };
|
|
1393
|
+
let transformed = null;
|
|
1394
|
+
let resolvedCandidate = null;
|
|
1395
|
+
if (spec.startsWith('/@id/')) {
|
|
1396
|
+
@@ -190,6 +213,7 @@ export async function resolveNsMTransformedModule(options) {
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
for (const candidate of transformCandidates) {
|
|
1400
|
+
+ noteServedDependencyFile(candidate);
|
|
1401
|
+
transformed = await tryTransformRequest(transformRequest, candidate, timeoutMs);
|
|
1402
|
+
if (transformed?.code) {
|
|
1403
|
+
resolvedCandidate = candidate;
|
|
1404
|
+
@@ -198,6 +222,7 @@ export async function resolveNsMTransformedModule(options) {
|
|
1405
|
+
}
|
|
1406
|
+
const resolvedId = await resolveId(spec);
|
|
1407
|
+
if (resolvedId) {
|
|
1408
|
+
+ noteServedDependencyFile(resolvedId);
|
|
1409
|
+
transformed = await tryTransformRequest(transformRequest, resolvedId, timeoutMs);
|
|
1410
|
+
if (transformed?.code) {
|
|
1411
|
+
return { transformed, resolvedCandidate: resolvedId };
|
|
1412
|
+
@@ -209,6 +234,7 @@ export async function resolveNsMTransformedModule(options) {
|
|
1413
|
+
if (bareSpecifier && !bareSpecifier.startsWith('.')) {
|
|
1414
|
+
const resolvedBareId = await resolveId(bareSpecifier);
|
|
1415
|
+
if (resolvedBareId) {
|
|
1416
|
+
+ noteServedDependencyFile(resolvedBareId);
|
|
1417
|
+
transformed = await tryTransformRequest(transformRequest, resolvedBareId, timeoutMs);
|
|
1418
|
+
if (transformed?.code) {
|
|
1419
|
+
return { transformed, resolvedCandidate: resolvedBareId };
|
|
1420
|
+
@@ -216,14 +242,19 @@ export async function resolveNsMTransformedModule(options) {
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
- const fsId = resolveFsAnchoredSpec(spec, serverRoot, workspaceRoot);
|
|
1425
|
+
- if (fsId) {
|
|
1426
|
+
+ // A workspace-relative extensionless URL is not a Vite app URL.
|
|
1427
|
+
+ // Probe the same extension/platform candidates under both source roots.
|
|
1428
|
+
+ for (const candidate of new Set([spec, ...transformCandidates])) {
|
|
1429
|
+
+ const fsId = resolveFsAnchoredSpec(candidate, serverRoot, workspaceRoot);
|
|
1430
|
+
+ if (!fsId) continue;
|
|
1431
|
+
+ noteServedDependencyFile(fsId);
|
|
1432
|
+
transformed = await tryTransformRequest(transformRequest, fsId, timeoutMs);
|
|
1433
|
+
if (transformed?.code) {
|
|
1434
|
+
return { transformed, resolvedCandidate: fsId };
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
for (const candidate of transformCandidates) {
|
|
1438
|
+
+ noteServedDependencyFile(candidate);
|
|
1439
|
+
const importHintCandidate = `${candidate}${candidate.includes('?') ? '&' : '?'}import`;
|
|
1440
|
+
transformed = await tryTransformRequest(transformRequest, importHintCandidate, timeoutMs);
|
|
1441
|
+
if (transformed?.code) {
|
|
1442
|
+
diff --git a/hmr/server/websocket-ns-m.js b/hmr/server/websocket-ns-m.js
|
|
1443
|
+
index fcdcd69776b3f82d3fc7d8dd26e03856177c933e..ec7c439dcd29af5c341b0bc0146243b7855d2a7f 100644
|
|
1444
|
+
--- a/hmr/server/websocket-ns-m.js
|
|
1445
|
+
+++ b/hmr/server/websocket-ns-m.js
|
|
1446
|
+
@@ -6,6 +6,7 @@ import { isRuntimeGraphExcludedPath } from './runtime-graph-filter.js';
|
|
1447
|
+
import { buildPiniaVendorShim, buildVueVendorShim } from './vendor-bare-module-shims.js';
|
|
1448
|
+
import { collapseLegacyNsMTags } from './websocket-ns-m-paths.js';
|
|
1449
|
+
import { createNsMRequestContext, resolveFsAnchoredSpec, resolveNsMTransformedModule } from './websocket-ns-m-request.js';
|
|
1450
|
+
+import { purgeTransformCachesForHotUpdate, servedDependencyFileChanged } from './transform-cache-invalidation.js';
|
|
1451
|
+
import { setDeviceModuleHeaders } from './route-helpers.js';
|
|
1452
|
+
import { RAW_QUERY_PATTERN } from './constants.js';
|
|
1453
|
+
import { CSS_MODULE_RE, buildCssRegisterSnippetFromVar, normalizeCssForDevice } from './css-device-module.js';
|
|
1454
|
+
@@ -98,7 +99,7 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1455
|
+
// internal virtual modules (e.g., \0nsvite:nsconfig-json for
|
|
1456
|
+
// ~/package.json) that don't exist on disk and must NOT run
|
|
1457
|
+
// through the device post-processing pipeline below.
|
|
1458
|
+
- if (spec.startsWith('/@id/')) {
|
|
1459
|
+
+ if (spec.startsWith('/@id/') && !CSS_MODULE_RE.test(spec)) {
|
|
1460
|
+
try {
|
|
1461
|
+
// First try Vite's transform pipeline directly
|
|
1462
|
+
const vr = await sharedTransformRequest(spec);
|
|
1463
|
+
@@ -167,8 +168,21 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1464
|
+
// Workspace css outside the vite root must be anchored to /@fs or
|
|
1465
|
+
// `?inline` is denied and the DOM css module (__vite__updateStyle)
|
|
1466
|
+
// is served instead.
|
|
1467
|
+
- const inlineSpec = resolveFsAnchoredSpec(spec, serverRoot, monorepoWorkspaceRoot) || spec;
|
|
1468
|
+
- const inlineRes = await sharedTransformRequest(`${inlineSpec}?inline`);
|
|
1469
|
+
+ const inlineSpec = spec.startsWith('/@id/')
|
|
1470
|
+
+ ? spec.slice('/@id/'.length).replace(/__x00__/g, '\0')
|
|
1471
|
+
+ : resolveFsAnchoredSpec(spec, serverRoot, monorepoWorkspaceRoot) || spec;
|
|
1472
|
+
+ // Keep the canonical sheet's watch edges and CSS HMR boundary alive.
|
|
1473
|
+
+ // The inline variant alone is not the node stylesheet plugins reload.
|
|
1474
|
+
+ const virtualCss = spec.startsWith('/@id/');
|
|
1475
|
+
+ // Plugin reloads can invalidate only the canonical sheet, not its
|
|
1476
|
+
+ // inline sibling or the NativeScript transform-result TTL cache.
|
|
1477
|
+
+ const compileCss = virtualCss ? (url) => server.transformRequest(url) : sharedTransformRequest;
|
|
1478
|
+
+ if (virtualCss) {
|
|
1479
|
+
+ await compileCss(inlineSpec);
|
|
1480
|
+
+ const inlineModule = server.moduleGraph.getModuleById(`${inlineSpec}?inline`);
|
|
1481
|
+
+ if (inlineModule) server.moduleGraph.invalidateModule(inlineModule);
|
|
1482
|
+
+ }
|
|
1483
|
+
+ const inlineRes = await compileCss(`${inlineSpec}?inline`);
|
|
1484
|
+
const inlineCode = inlineRes?.code || '';
|
|
1485
|
+
// `?inline` output is `export default "<compiled css>"`.
|
|
1486
|
+
const m = inlineCode.match(/export\s+default\s+("(?:[^"\\]|\\.)*")\s*;?/s);
|
|
1487
|
+
@@ -178,7 +192,14 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1488
|
+
css = JSON.parse(m[1]);
|
|
1489
|
+
}
|
|
1490
|
+
catch { }
|
|
1491
|
+
- css = normalizeCssForDevice(css);
|
|
1492
|
+
+ css = normalizeCssForDevice(css) || '/* empty stylesheet */';
|
|
1493
|
+
+ // HMR fetches adapted text through this same compiler and tag.
|
|
1494
|
+
+ if (urlObj.searchParams.has('direct')) {
|
|
1495
|
+
+ res.setHeader('Content-Type', 'text/css; charset=utf-8');
|
|
1496
|
+
+ res.statusCode = 200;
|
|
1497
|
+
+ res.end(css);
|
|
1498
|
+
+ return;
|
|
1499
|
+
+ }
|
|
1500
|
+
const out = `// [ns:m][css] ${spec}\n` + `const __ns_css_text__ = ${JSON.stringify(css)};\n` + buildCssRegisterSnippetFromVar(spec, '__ns_css_text__') + `export default __ns_css_text__;\n`;
|
|
1501
|
+
res.statusCode = 200;
|
|
1502
|
+
res.end(out);
|
|
1503
|
+
@@ -191,12 +212,27 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1504
|
+
if (verbose)
|
|
1505
|
+
console.warn('[ns:m][css] inline compile failed', spec, cssErr?.message);
|
|
1506
|
+
}
|
|
1507
|
+
- // Fall through to default handling if inline compile produced nothing.
|
|
1508
|
+
+ // Never send raw CSS or a DOM injection module to the native loader.
|
|
1509
|
+
+ res.statusCode = 500;
|
|
1510
|
+
+ res.end('throw new Error(' + JSON.stringify('[ns:m] CSS compilation failed: ' + spec) + ');');
|
|
1511
|
+
+ return;
|
|
1512
|
+
}
|
|
1513
|
+
// Queue and dedupe transformRequest calls so heavy app graphs do not
|
|
1514
|
+
// overwhelm Vite with concurrent work. Slow-transform warnings start only
|
|
1515
|
+
// when the transform actually begins executing, and requests stay pending
|
|
1516
|
+
// until Vite returns a real result.
|
|
1517
|
+
+ // A pnpm/bun patch install rewrites node_modules without a Vite
|
|
1518
|
+
+ // file event, so neither handleHotUpdate nor the shared transform
|
|
1519
|
+
+ // cache learns of it. The serve path fingerprints each resolved
|
|
1520
|
+
+ // dependency file; a drift purges Vite's module graph plus the
|
|
1521
|
+
+ // shared transform cache before this request re-transforms.
|
|
1522
|
+
+ const notifyServedDependencyFile = (file) => {
|
|
1523
|
+
+ if (!servedDependencyFileChanged(file))
|
|
1524
|
+
+ return;
|
|
1525
|
+
+ if (verbose)
|
|
1526
|
+
+ console.log('[ns:m] dependency file changed outside the watcher; invalidating transform caches', file);
|
|
1527
|
+
+ purgeTransformCachesForHotUpdate({ file, server, sharedTransformRequest, verbose, label: 'ns:m-deps' });
|
|
1528
|
+
+ };
|
|
1529
|
+
const transformWithTimeout = async (url, timeoutMs = 120000) => {
|
|
1530
|
+
const r = await sharedTransformRequest(url, timeoutMs);
|
|
1531
|
+
// A type-only .ts module legitimately transforms to EMPTY code
|
|
1532
|
+
@@ -230,6 +266,7 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1533
|
+
transformRequest: transformWithTimeout,
|
|
1534
|
+
resolveId: resolvePluginContainerId,
|
|
1535
|
+
loadVirtualId,
|
|
1536
|
+
+ notifyServedDependencyFile,
|
|
1537
|
+
});
|
|
1538
|
+
let transformed = resolution.transformed;
|
|
1539
|
+
const resolvedCandidate = resolution.resolvedCandidate;
|
|
1540
|
+
@@ -513,6 +550,8 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1541
|
+
continue;
|
|
1542
|
+
}
|
|
1543
|
+
else if (u.pathname.startsWith('/ns/m')) {
|
|
1544
|
+
+ // The CSS route synthesizes a default string export after compilation.
|
|
1545
|
+
+ if (CSS_MODULE_RE.test(u.pathname)) continue;
|
|
1546
|
+
// Resolve the import target through the SAME
|
|
1547
|
+
// canonical pipeline the /ns/m route itself uses
|
|
1548
|
+
// (websocket-ns-m-request.ts) instead of a third
|
|
1549
|
+
@@ -532,6 +571,7 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1550
|
+
},
|
|
1551
|
+
resolveId: resolvePluginContainerId,
|
|
1552
|
+
loadVirtualId,
|
|
1553
|
+
+ notifyServedDependencyFile,
|
|
1554
|
+
});
|
|
1555
|
+
targetCode = targetResolution.transformed?.code || '';
|
|
1556
|
+
}
|
|
1557
|
+
@@ -546,7 +586,17 @@ export function registerNsModuleServerRoute(server, options) {
|
|
1558
|
+
catch { }
|
|
1559
|
+
if (!targetCode)
|
|
1560
|
+
continue;
|
|
1561
|
+
- const hasDefault = /\bexport\s+default\b/.test(targetCode) || /export\s*\{\s*default\s*(?:as\s*default)?\s*\}/.test(targetCode);
|
|
1562
|
+
+ // Inspect exports, not source text: compilers emit aliases such as
|
|
1563
|
+
+ // `export { Screen as default }`, and comments/strings are not exports.
|
|
1564
|
+
+ const targetAst = babelParse(targetCode, {
|
|
1565
|
+
+ sourceType: 'module',
|
|
1566
|
+
+ plugins: MODULE_IMPORT_ANALYSIS_PLUGINS,
|
|
1567
|
+
+ });
|
|
1568
|
+
+ const hasDefault = targetAst.program.body.some((node) =>
|
|
1569
|
+
+ node.type === 'ExportDefaultDeclaration' ||
|
|
1570
|
+
+ (node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type' &&
|
|
1571
|
+
+ node.specifiers.some((specifier) => specifier.exportKind !== 'type' &&
|
|
1572
|
+
+ (specifier.exported?.name === 'default' || specifier.exported?.value === 'default'))));
|
|
1573
|
+
if (!hasDefault) {
|
|
1574
|
+
// CJS/UMD modules won't have `export default` — they get CJS-wrapped
|
|
1575
|
+
// by the serving pipeline. Only warn, don't fatally block the importer.
|
|
1576
|
+
diff --git a/hmr/server/websocket-served-module-helpers.js b/hmr/server/websocket-served-module-helpers.js
|
|
1577
|
+
index b9e3ab67eb4ae7c9b12bc4b02b9aa3660d712644..f857f4a5a5956af229e447ed04bf1a52a90c6399 100644
|
|
1578
|
+
--- a/hmr/server/websocket-served-module-helpers.js
|
|
1579
|
+
+++ b/hmr/server/websocket-served-module-helpers.js
|
|
1580
|
+
@@ -105,8 +105,8 @@ export function classifyServedRequest(spec, resolvedId) {
|
|
1581
|
+
return classifyServedModule(spec);
|
|
1582
|
+
}
|
|
1583
|
+
export const MODULE_IMPORT_ANALYSIS_PLUGINS = ['typescript', 'jsx', 'importMeta', 'topLevelAwait', 'classProperties', 'classPrivateProperties', 'classPrivateMethods', 'decorators-legacy'];
|
|
1584
|
+
-export function collectTopLevelImportRecords(code) {
|
|
1585
|
+
- if (!code || typeof code !== 'string' || !/\bimport\b/.test(code)) {
|
|
1586
|
+
+export function collectTopLevelImportRecords(code, includeReExports = false) {
|
|
1587
|
+
+ if (!code || typeof code !== 'string' || !(includeReExports ? /\b(?:import|export)\b/ : /\bimport\b/).test(code)) {
|
|
1588
|
+
return [];
|
|
1589
|
+
}
|
|
1590
|
+
try {
|
|
1591
|
+
@@ -119,7 +119,7 @@ export function collectTopLevelImportRecords(code) {
|
|
1592
|
+
return [];
|
|
1593
|
+
}
|
|
1594
|
+
return body
|
|
1595
|
+
- .filter((node) => t.isImportDeclaration(node) && typeof node.start === 'number' && typeof node.end === 'number' && typeof node.source?.value === 'string')
|
|
1596
|
+
+ .filter((node) => (t.isImportDeclaration(node) || (includeReExports && (t.isExportNamedDeclaration(node) || t.isExportAllDeclaration(node)))) && typeof node.start === 'number' && typeof node.end === 'number' && typeof node.source?.value === 'string')
|
|
1597
|
+
.map((node) => ({
|
|
1598
|
+
start: node.start,
|
|
1599
|
+
end: node.end,
|
|
1600
|
+
diff --git a/hmr/server/websocket.js b/hmr/server/websocket.js
|
|
1601
|
+
index e6a14437f8990e2c631f23eb8db21aa0b28b5759..2b9fb450511b6e114b6e7e7ac8a48831b4a09dc9 100644
|
|
1602
|
+
--- a/hmr/server/websocket.js
|
|
1603
|
+
+++ b/hmr/server/websocket.js
|
|
1604
|
+
@@ -1,3 +1,5 @@
|
|
1605
|
+
+import { virtualCssUpdates } from './css-device-module.js';
|
|
1606
|
+
+import { buildCssUpdatesMessage } from './css-update-message.js';
|
|
1607
|
+
import { readFileSync } from 'fs';
|
|
1608
|
+
import { WebSocketServer } from 'ws';
|
|
1609
|
+
import * as path from 'path';
|
|
1610
|
+
@@ -341,6 +343,13 @@ function createHmrWebSocketPlugin(opts, strategy) {
|
|
1611
|
+
// to reach the device, since they drive the
|
|
1612
|
+
// in-place `ɵɵreplaceMetadata` template-swap path.
|
|
1613
|
+
// Filter the relay to those.
|
|
1614
|
+
+ const cssUpdates = virtualCssUpdates(normalized);
|
|
1615
|
+
+ if (cssUpdates.length) {
|
|
1616
|
+
+ const message = JSON.stringify(buildCssUpdatesMessage(server, cssUpdates));
|
|
1617
|
+
+ wss?.clients.forEach((client) => {
|
|
1618
|
+
+ if (client?.readyState === 1) client.send(message);
|
|
1619
|
+
+ });
|
|
1620
|
+
+ }
|
|
1621
|
+
if (normalized.type !== 'custom')
|
|
1622
|
+
return;
|
|
1623
|
+
// Root-component guard. Analog's in-place
|
|
1624
|
+
diff --git a/hmr/shared/vendor/manifest-collect.js b/hmr/shared/vendor/manifest-collect.js
|
|
1625
|
+
index 7b3afd4af098cc8587851b04188f6b1c3d5541bc..8951fe0d26c6cd73ad713bf672ca242437678afd 100644
|
|
1626
|
+
--- a/hmr/shared/vendor/manifest-collect.js
|
|
1627
|
+
+++ b/hmr/shared/vendor/manifest-collect.js
|
|
1628
|
+
@@ -527,7 +527,7 @@ export function collectVendorModules(projectRoot, platform, flavor) {
|
|
1629
|
+
if (!deps)
|
|
1630
|
+
return;
|
|
1631
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
1632
|
+
- if (isUnvendorableLocalSource(name, spec, projectRequire, platform))
|
|
1633
|
+
+ if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('workspace:')))
|
|
1634
|
+
continue;
|
|
1635
|
+
// Policy exclusions match PACKAGE NAMES (`@prisma/client` in
|
|
1636
|
+
// ALWAYS_EXCLUDE / NS_VENDOR_EXCLUDE); check here so subpath specs
|
|
1637
|
+
@@ -553,7 +553,8 @@ export function collectVendorModules(projectRoot, platform, flavor) {
|
|
1638
|
+
console.log(`[vendor] skipping root dependency ${name} (no resolvable bare entry)`);
|
|
1639
|
+
continue;
|
|
1640
|
+
}
|
|
1641
|
+
- addCandidate(name);
|
|
1642
|
+
+ if (!isUnvendorableLocalSource(name, spec, projectRequire, platform))
|
|
1643
|
+
+ addCandidate(name);
|
|
1644
|
+
continue;
|
|
1645
|
+
}
|
|
1646
|
+
// Subpath-only evidence: the app never imports the package ROOT, and
|
|
1647
|
+
@@ -573,7 +574,8 @@ export function collectVendorModules(projectRoot, platform, flavor) {
|
|
1648
|
+
}
|
|
1649
|
+
if (debug)
|
|
1650
|
+
console.log(`[vendor] vendoring subpath ${subpath} (root ${name} has subpath-only evidence)`);
|
|
1651
|
+
- addCandidate(subpath);
|
|
1652
|
+
+ if (!isUnvendorableLocalSource(subpath, spec, projectRequire, platform))
|
|
1653
|
+
+ addCandidate(subpath);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
@@ -588,7 +590,7 @@ export function collectVendorModules(projectRoot, platform, flavor) {
|
|
1658
|
+
// Some force-included packages are only present transitively in apps that
|
|
1659
|
+
// actually use them. Skip missing packages quietly so unrelated projects do
|
|
1660
|
+
// not fail vendor collection just because the policy list names them.
|
|
1661
|
+
- if (canResolveDependencyPackageJson(name, projectRequire)) {
|
|
1662
|
+
+ if (isAlwaysIncludeInstalled(name, projectRoot)) {
|
|
1663
|
+
addCandidate(name);
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
@@ -642,7 +644,7 @@ export function collectVendorModules(projectRoot, platform, flavor) {
|
|
1667
|
+
}
|
|
1668
|
+
const peerDependencies = Object.keys(dependencyPkg.peerDependencies ?? {});
|
|
1669
|
+
for (const peer of peerDependencies) {
|
|
1670
|
+
- if (shouldSkipDependency(peer) || localSourceNames.has(peer)) {
|
|
1671
|
+
+ if (shouldSkipDependency(peer) || localSourceNames.has(peer) || classifyPackageEntry(peer, projectRequire, platform) === 'source') {
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
if (projectDeps.dependencies.has(peer) || projectDeps.optional.has(peer) || projectDeps.dev.has(peer)) {
|
|
1675
|
+
@@ -798,6 +800,48 @@ function isUnvendorableLocalSource(name, spec, projectRequire, platform) {
|
|
1676
|
+
return true;
|
|
1677
|
+
return false;
|
|
1678
|
+
}
|
|
1679
|
+
+// These are the explicit conditions used by manifest.ts and deps-bundle.ts.
|
|
1680
|
+
+// Object insertion order, rather than the order of this set, selects a branch.
|
|
1681
|
+
+const VENDOR_ENTRY_CONDITIONS = new Set(['module', 'react-native', 'import', 'browser', 'default']);
|
|
1682
|
+
+function selectVendorExport(exports, subpath) {
|
|
1683
|
+
+ const selectCondition = (node) => {
|
|
1684
|
+
+ if (node === null || typeof node === 'string')
|
|
1685
|
+
+ return node;
|
|
1686
|
+
+ if (Array.isArray(node)) {
|
|
1687
|
+
+ for (const item of node) {
|
|
1688
|
+
+ const selected = selectCondition(item);
|
|
1689
|
+
+ if (selected !== undefined)
|
|
1690
|
+
+ return selected;
|
|
1691
|
+
+ }
|
|
1692
|
+
+ }
|
|
1693
|
+
+ else if (node && typeof node === 'object') {
|
|
1694
|
+
+ for (const [condition, value] of Object.entries(node)) {
|
|
1695
|
+
+ if (!VENDOR_ENTRY_CONDITIONS.has(condition))
|
|
1696
|
+
+ continue;
|
|
1697
|
+
+ const selected = selectCondition(value);
|
|
1698
|
+
+ if (selected !== undefined)
|
|
1699
|
+
+ return selected;
|
|
1700
|
+
+ }
|
|
1701
|
+
+ }
|
|
1702
|
+
+ return undefined;
|
|
1703
|
+
+ };
|
|
1704
|
+
+ if (exports && typeof exports === 'object' && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith('.'))) {
|
|
1705
|
+
+ const paths = exports;
|
|
1706
|
+
+ if (Object.hasOwn(paths, subpath))
|
|
1707
|
+
+ return selectCondition(paths[subpath]);
|
|
1708
|
+
+ // Exact matches win; patterns prefer the longest prefix then suffix.
|
|
1709
|
+
+ const patterns = Object.keys(paths).filter((key) => key.includes('*')).sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length);
|
|
1710
|
+
+ for (const pattern of patterns) {
|
|
1711
|
+
+ const [prefix, suffix] = pattern.split('*');
|
|
1712
|
+
+ if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix) || subpath.length < prefix.length + suffix.length)
|
|
1713
|
+
+ continue;
|
|
1714
|
+
+ const selected = selectCondition(paths[pattern]);
|
|
1715
|
+
+ return typeof selected === 'string' ? selected.replaceAll('*', subpath.slice(prefix.length, subpath.length - suffix.length)) : selected;
|
|
1716
|
+
+ }
|
|
1717
|
+
+ return undefined;
|
|
1718
|
+
+ }
|
|
1719
|
+
+ return subpath === '.' ? selectCondition(exports) : undefined;
|
|
1720
|
+
+}
|
|
1721
|
+
/**
|
|
1722
|
+
* Classify an installed package's entry point:
|
|
1723
|
+
* - `'compiled'` — a `.js`/`.mjs`/`.cjs` entry file (or its platform
|
|
1724
|
+
@@ -810,16 +854,20 @@ function isUnvendorableLocalSource(name, spec, projectRequire, platform) {
|
|
1725
|
+
* its subpaths may still be vendored as monorepo root deps.
|
|
1726
|
+
*/
|
|
1727
|
+
function classifyPackageEntry(name, projectRequire, platform) {
|
|
1728
|
+
+ const packageName = bareSpecifierToPackageName(name);
|
|
1729
|
+
+ if (!packageName)
|
|
1730
|
+
+ return 'unknown';
|
|
1731
|
+
+ const subpath = name === packageName ? '.' : `.${name.slice(packageName.length)}`;
|
|
1732
|
+
let pkgJsonPath = null;
|
|
1733
|
+
try {
|
|
1734
|
+
- pkgJsonPath = projectRequire.resolve(`${name}/package.json`);
|
|
1735
|
+
+ pkgJsonPath = projectRequire.resolve(`${packageName}/package.json`);
|
|
1736
|
+
}
|
|
1737
|
+
catch {
|
|
1738
|
+
// `exports` maps that omit `./package.json` refuse the subpath
|
|
1739
|
+
// resolve — fall back to a direct path probe over the require
|
|
1740
|
+
// resolution dirs.
|
|
1741
|
+
- for (const dir of projectRequire.resolve.paths(name) ?? []) {
|
|
1742
|
+
- const candidate = path.join(dir, name, 'package.json');
|
|
1743
|
+
+ for (const dir of projectRequire.resolve.paths(packageName) ?? []) {
|
|
1744
|
+
+ const candidate = path.join(dir, packageName, 'package.json');
|
|
1745
|
+
if (fs.existsSync(candidate)) {
|
|
1746
|
+
pkgJsonPath = candidate;
|
|
1747
|
+
break;
|
|
1748
|
+
@@ -841,35 +889,23 @@ function classifyPackageEntry(name, projectRequire, platform) {
|
|
1749
|
+
if (typeof value === 'string' && value)
|
|
1750
|
+
candidates.push(value);
|
|
1751
|
+
};
|
|
1752
|
+
- pushCandidate(pkg.module);
|
|
1753
|
+
- pushCandidate(pkg.main);
|
|
1754
|
+
- // Recursively flatten conditional `exports` maps to surface concrete
|
|
1755
|
+
- // file paths. We only need `string` leaves; anything else (function-
|
|
1756
|
+
- // based exports, etc.) doesn't apply to esbuild's resolution.
|
|
1757
|
+
- const visitExports = (node) => {
|
|
1758
|
+
- if (!node)
|
|
1759
|
+
- return;
|
|
1760
|
+
- if (typeof node === 'string') {
|
|
1761
|
+
- pushCandidate(node);
|
|
1762
|
+
- return;
|
|
1763
|
+
- }
|
|
1764
|
+
- if (Array.isArray(node)) {
|
|
1765
|
+
- for (const item of node)
|
|
1766
|
+
- visitExports(item);
|
|
1767
|
+
- return;
|
|
1768
|
+
- }
|
|
1769
|
+
- if (typeof node === 'object') {
|
|
1770
|
+
- for (const value of Object.values(node))
|
|
1771
|
+
- visitExports(value);
|
|
1772
|
+
- }
|
|
1773
|
+
- };
|
|
1774
|
+
- visitExports(pkg.exports);
|
|
1775
|
+
- if (candidates.length === 0) {
|
|
1776
|
+
- // node's default lookup falls back to `index.js`.
|
|
1777
|
+
- candidates.push('index');
|
|
1778
|
+
+ if (pkg.exports != null) {
|
|
1779
|
+
+ // Match the specifier and the conditions of the native ESM vendor build.
|
|
1780
|
+
+ // An unrelated subpath, inactive branch, or legacy main is not evidence
|
|
1781
|
+
+ // about the entry esbuild will actually load. Keep exports encapsulation.
|
|
1782
|
+
+ pushCandidate(selectVendorExport(pkg.exports, subpath));
|
|
1783
|
+
+ }
|
|
1784
|
+
+ else if (subpath !== '.') {
|
|
1785
|
+
+ pushCandidate(subpath);
|
|
1786
|
+
+ }
|
|
1787
|
+
+ else {
|
|
1788
|
+
+ pushCandidate(pkg.module);
|
|
1789
|
+
+ pushCandidate(typeof pkg.browser === 'string' ? pkg.browser : undefined);
|
|
1790
|
+
+ pushCandidate(pkg.main);
|
|
1791
|
+
+ if (candidates.length === 0)
|
|
1792
|
+
+ candidates.push('index');
|
|
1793
|
+
}
|
|
1794
|
+
const extensionsToTry = compiledJsExtensionsForPlatform(platform);
|
|
1795
|
+
- let sourceEntryFound = false;
|
|
1796
|
+
for (const cand of candidates) {
|
|
1797
|
+
const abs = path.resolve(pkgDir, cand);
|
|
1798
|
+
const ext = path.extname(cand);
|
|
1799
|
+
@@ -889,25 +925,47 @@ function classifyPackageEntry(name, projectRequire, platform) {
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
if (!ext) {
|
|
1803
|
+
- // Extensionless main — try plain JS variants AND the
|
|
1804
|
+
- // platform-specific variants NativeScript plugins commonly use
|
|
1805
|
+
- // (`index.ios.js`, `index.android.js`, `index.visionos.js`), as
|
|
1806
|
+
- // both a file (`<abs>.js`) and a directory (`<abs>/index.js`).
|
|
1807
|
+
- for (const e of extensionsToTry) {
|
|
1808
|
+
- if (fs.existsSync(abs + e) || fs.existsSync(path.join(abs, `index${e}`)))
|
|
1809
|
+
- return 'compiled';
|
|
1810
|
+
+ // Match the vendor bundler's file-before-directory lookup and extension
|
|
1811
|
+
+ // order. Only the active platform is eligible; a foreign JS leaf must
|
|
1812
|
+
+ // not hide the source entry that this platform will actually load.
|
|
1813
|
+
+ const suffixes = platform === 'android' ? ['android'] : platform === 'visionos' ? ['visionos', 'ios'] : ['ios', 'visionos'];
|
|
1814
|
+
+ const extensions = ['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs', '.json', ...suffixes.flatMap((suffix) => ['.tsx', '.jsx', '.ts', '.js'].map((e) => `.${suffix}${e}`)), '.tsrx', '.mts', '.cts'];
|
|
1815
|
+
+ for (const base of [abs, path.join(abs, 'index')]) {
|
|
1816
|
+
+ for (const extension of extensions) {
|
|
1817
|
+
+ if (fs.existsSync(base + extension))
|
|
1818
|
+
+ return COMPILED_JS_ENTRY_REGEX.test(extension) ? 'compiled' : 'source';
|
|
1819
|
+
+ }
|
|
1820
|
+
}
|
|
1821
|
+
- if (['.ts', '.tsx', '.mts', '.cts'].some((e) => fs.existsSync(abs + e) || fs.existsSync(path.join(abs, `index${e}`))))
|
|
1822
|
+
- sourceEntryFound = true;
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
// A non-JS extension (typically `.ts`/`.tsx`) means the package
|
|
1826
|
+
// only ships TS source — esbuild's vendor pipeline can't resolve
|
|
1827
|
+
// any tsconfig-aliased imports inside it.
|
|
1828
|
+
if (fs.existsSync(abs))
|
|
1829
|
+
- sourceEntryFound = true;
|
|
1830
|
+
+ return 'source';
|
|
1831
|
+
+ }
|
|
1832
|
+
+ return 'unknown';
|
|
1833
|
+
+}
|
|
1834
|
+
+// Presence for force-included packages is a filesystem node_modules
|
|
1835
|
+
+// ancestor walk from the project root — matching what the esbuild vendor
|
|
1836
|
+
+// pass can actually resolve. projectRequire.resolve would honor NODE_PATH,
|
|
1837
|
+
+// and pnpm's bin shims (`node_modules/.bin/ns`, `xplat`) export NODE_PATH
|
|
1838
|
+
+// containing the hidden `.pnpm/node_modules` hoist, where phantom copies of
|
|
1839
|
+
+// other importers' dependencies (e.g. a package only a different workspace
|
|
1840
|
+
+// app uses) look installed but are unresolvable at bundle time.
|
|
1841
|
+
+function isAlwaysIncludeInstalled(name, projectRoot) {
|
|
1842
|
+
+ let dir = projectRoot;
|
|
1843
|
+
+ for (;;) {
|
|
1844
|
+
+ const inPnpmHiddenHoist =
|
|
1845
|
+
+ path.basename(dir) === '.pnpm' && path.basename(path.dirname(dir)) === 'node_modules';
|
|
1846
|
+
+ if (!inPnpmHiddenHoist && fs.existsSync(path.join(dir, 'node_modules', name, 'package.json'))) {
|
|
1847
|
+
+ return true;
|
|
1848
|
+
+ }
|
|
1849
|
+
+ const parent = path.dirname(dir);
|
|
1850
|
+
+ if (parent === dir)
|
|
1851
|
+
+ return false;
|
|
1852
|
+
+ dir = parent;
|
|
1853
|
+
}
|
|
1854
|
+
- return sourceEntryFound ? 'source' : 'unknown';
|
|
1855
|
+
}
|
|
1856
|
+
function canResolveDependencyPackageJson(specifier, projectRequire) {
|
|
1857
|
+
try {
|
|
1858
|
+
@@ -939,4 +997,3 @@ function parseEnvList(value) {
|
|
1859
|
+
.map((token) => token.trim())
|
|
1860
|
+
.filter(Boolean);
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
-//# sourceMappingURL=manifest-collect.js.map
|
|
1864
|
+
|
|
1865
|
+
diff --git a/hmr/shared/vendor/manifest.js b/hmr/shared/vendor/manifest.js
|
|
1866
|
+
index 54ba11ef9c329df049fa93b01b2ce47c9fb1ac3e..f7e3d0d1bd71919584834ef5a56e42f74ad2cf28 100644
|
|
1867
|
+
--- a/hmr/shared/vendor/manifest.js
|
|
1868
|
+
+++ b/hmr/shared/vendor/manifest.js
|
|
1869
|
+
@@ -6,7 +6,7 @@ import { collectVendorModules } from './manifest-collect.js';
|
|
1870
|
+
import { generatePlatformPolyfills } from '../runtime/platform-polyfills.js';
|
|
1871
|
+
import { createNativeClassEsbuildPlugin } from '../../../helpers/nativeclass-esbuild-plugin.js';
|
|
1872
|
+
import { getGlobalDefines } from '../../../helpers/global-defines.js';
|
|
1873
|
+
-import { createVendorEsbuildPlugin, createSolidJsxEsbuildPlugin, angularLinkerEsbuildPlugin, createUnicodeRegexEsbuildPlugin, createWebpackLoaderStubEsbuildPlugin, createNodeBuiltinPolyfillEsbuildPlugin, createOptionalDependencyStubEsbuildPlugin, createNativeAddonStubEsbuildPlugin } from './vendor-esbuild-plugins.js';
|
|
1874
|
+
+import { createVendorEsbuildPlugin, createSolidJsxEsbuildPlugin, angularLinkerEsbuildPlugin, createUnicodeRegexEsbuildPlugin, createWebpackLoaderStubEsbuildPlugin, createNodeBuiltinPolyfillEsbuildPlugin, createOptionalDependencyStubEsbuildPlugin, createNativeAddonStubEsbuildPlugin , createViteAliasEsbuildPlugin } from './vendor-esbuild-plugins.js';
|
|
1875
|
+
export const VENDOR_MANIFEST_ID = '@nativescript/vendor-manifest';
|
|
1876
|
+
export const VENDOR_MANIFEST_VIRTUAL_ID = '\0' + VENDOR_MANIFEST_ID;
|
|
1877
|
+
export const VENDOR_BUNDLE_ID = '@nativescript/vendor';
|
|
1878
|
+
@@ -264,6 +264,9 @@ async function generateVendorBundle(options) {
|
|
1879
|
+
// plugins) BEFORE resolution — a single `loader!./x` specifier would
|
|
1880
|
+
// otherwise hard-fail the whole bundle. See the plugin for details.
|
|
1881
|
+
createWebpackLoaderStubEsbuildPlugin(),
|
|
1882
|
+
+ // App `resolve.alias` redirects for packages that are NOT installed —
|
|
1883
|
+
+ // without this they look absent and get stubbed below.
|
|
1884
|
+
+ createViteAliasEsbuildPlugin(options.projectRoot),
|
|
1885
|
+
createOptionalDependencyStubEsbuildPlugin(options.projectRoot),
|
|
1886
|
+
// Stub compiled `.node` addons (fsevents & co.) — unloadable by esbuild and
|
|
1887
|
+
// unrunnable on device; a throwing stub preserves optional-dep semantics.
|
|
1888
|
+
diff --git a/hmr/shared/vendor/vendor-esbuild-plugins.js b/hmr/shared/vendor/vendor-esbuild-plugins.js
|
|
1889
|
+
index 4855a85322188435072c21bb72c60ea16d514b37..9a45d264cda57c376239dfe124049b7cb95c34b8 100644
|
|
1890
|
+
--- a/hmr/shared/vendor/vendor-esbuild-plugins.js
|
|
1891
|
+
+++ b/hmr/shared/vendor/vendor-esbuild-plugins.js
|
|
1892
|
+
@@ -5,6 +5,7 @@ import { readFile } from 'fs/promises';
|
|
1893
|
+
import { createRequire } from 'node:module';
|
|
1894
|
+
import { getAngularLinkerFactory, runAngularLinker } from '../../frameworks/angular/build/shared-linker.js';
|
|
1895
|
+
import { vendorModuleShim } from './vendor-device-shim.js';
|
|
1896
|
+
+import { getUserAliasEntries } from '../../../helpers/global-defines.js';
|
|
1897
|
+
export function createVendorEsbuildPlugin(projectRoot) {
|
|
1898
|
+
return {
|
|
1899
|
+
name: 'ns-vendor-resolver',
|
|
1900
|
+
@@ -419,6 +420,119 @@ export function angularLinkerEsbuildPlugin(projectRoot) {
|
|
1901
|
+
* the try/catch-optional semantics instead of masking real missing modules
|
|
1902
|
+
* with `undefined` exports.
|
|
1903
|
+
*/
|
|
1904
|
+
+/**
|
|
1905
|
+
+ * Replay the app's Vite `resolve.alias` entries inside esbuild passes (deps
|
|
1906
|
+
+ * bundle, vendor bundle) for specifiers whose package is NOT installed.
|
|
1907
|
+
+ * esbuild has no `resolve.alias` option; plugins capture them from the
|
|
1908
|
+
+ * resolved Vite config (setUserAliasEntries in configResolved). Without
|
|
1909
|
+
+ * this, a specifier an app aliases to a real directory (e.g.
|
|
1910
|
+
+ * `@octane-xplat/nativescript-masonkit` → the mason-core package) looks
|
|
1911
|
+
+ * absent to the vendor collector and gets a throw-on-evaluate
|
|
1912
|
+
+ * optional-dependency stub that kills device boot. Installed packages keep
|
|
1913
|
+
+ * their default resolution — redirecting those would bundle a second realm
|
|
1914
|
+
+ * (e.g. upstream's own `@nativescript/core` → core-root aliases).
|
|
1915
|
+
+ *
|
|
1916
|
+
+ * Semantics mirror @rollup/plugin-alias (which Vite uses): entries apply in
|
|
1917
|
+
+ * order, first match wins; a string `find` matches the exact specifier or a
|
|
1918
|
+
+ * `find + '/'` prefix; a RegExp `find` is applied via `spec.replace()`. Only
|
|
1919
|
+
+ * bare specifiers are considered (relative and absolute specifiers are
|
|
1920
|
+
+ * importer-anchored and were already filtered at capture time). The rewritten
|
|
1921
|
+
+ * specifier is resolved through `build.resolve` so it inherits the pass's own
|
|
1922
|
+
+ * resolveExtensions/conditions/mainFields; when resolution fails we return
|
|
1923
|
+
+ * null and let the normal pipeline (including the optional-dep stub) decide.
|
|
1924
|
+
+ */
|
|
1925
|
+
+// `@scope/name/sub` → `@scope/name`; `pkg/sub` → `pkg`; `.prisma/client/…` → `.prisma`.
|
|
1926
|
+
+const esbuildPackageNameOf = (spec) => {
|
|
1927
|
+
+ const parts = spec.split('/');
|
|
1928
|
+
+ return spec.startsWith('@') && parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
|
|
1929
|
+
+};
|
|
1930
|
+
+// Is the package physically installed? Walk Node's node_modules lookup
|
|
1931
|
+
+// chain from the importer, then the project root. Presence is judged by the
|
|
1932
|
+
+// package DIRECTORY (its package.json file), never by entry resolution.
|
|
1933
|
+
+// pnpm's hidden hoist (`<root>/node_modules/.pnpm/node_modules/<pkg>`) does
|
|
1934
|
+
+// not count: those entries are phantom copies of other importers'
|
|
1935
|
+
+// dependencies, not packages installed for this importer — an unrelated
|
|
1936
|
+
+// workspace app's hoisted copy (e.g. a Windows-only package) must not
|
|
1937
|
+
+// disable the alias.
|
|
1938
|
+
+const esbuildPackagePresenceCache = new Map();
|
|
1939
|
+
+const isEsbuildPackageInstalled = (pkgName, fromDir, projectRoot) => {
|
|
1940
|
+
+ const cacheKey = `${pkgName}\0${fromDir}`;
|
|
1941
|
+
+ const cached = esbuildPackagePresenceCache.get(cacheKey);
|
|
1942
|
+
+ if (cached !== undefined)
|
|
1943
|
+
+ return cached;
|
|
1944
|
+
+ let present = false;
|
|
1945
|
+
+ let dir = fromDir;
|
|
1946
|
+
+ for (;;) {
|
|
1947
|
+
+ const inPnpmHiddenHoist =
|
|
1948
|
+
+ path.basename(dir) === '.pnpm' && path.basename(path.dirname(dir)) === 'node_modules';
|
|
1949
|
+
+ if (!inPnpmHiddenHoist &&
|
|
1950
|
+
+ fs.existsSync(path.join(dir, 'node_modules', pkgName, 'package.json'))) {
|
|
1951
|
+
+ present = true;
|
|
1952
|
+
+ break;
|
|
1953
|
+
+ }
|
|
1954
|
+
+ const parent = path.dirname(dir);
|
|
1955
|
+
+ if (parent === dir)
|
|
1956
|
+
+ break;
|
|
1957
|
+
+ dir = parent;
|
|
1958
|
+
+ }
|
|
1959
|
+
+ if (!present)
|
|
1960
|
+
+ present = fs.existsSync(path.join(projectRoot, 'node_modules', pkgName, 'package.json'));
|
|
1961
|
+
+ esbuildPackagePresenceCache.set(cacheKey, present);
|
|
1962
|
+
+ return present;
|
|
1963
|
+
+};
|
|
1964
|
+
+export function createViteAliasEsbuildPlugin(projectRoot) {
|
|
1965
|
+
+ return {
|
|
1966
|
+
+ name: 'ns-vite-alias',
|
|
1967
|
+
+ setup(build) {
|
|
1968
|
+
+ build.onResolve({ filter: /^[^./]|^\.[^./]|^\.\.[^/]/ }, async (args) => {
|
|
1969
|
+
+ if (args.pluginData?.nsViteAlias)
|
|
1970
|
+
+ return undefined;
|
|
1971
|
+
+ const entries = getUserAliasEntries();
|
|
1972
|
+
+ if (!entries.length)
|
|
1973
|
+
+ return undefined;
|
|
1974
|
+
+ for (const { find, replacement } of entries) {
|
|
1975
|
+
+ if (find instanceof RegExp)
|
|
1976
|
+
+ find.lastIndex = 0;
|
|
1977
|
+
+ const matches = find instanceof RegExp
|
|
1978
|
+
+ ? find.test(args.path)
|
|
1979
|
+
+ : args.path === find || args.path.startsWith(find + '/');
|
|
1980
|
+
+ if (!matches)
|
|
1981
|
+
+ continue;
|
|
1982
|
+
+ // Only redirect packages that are NOT installed — upstream's
|
|
1983
|
+
+ // own resolve.alias (@nativescript/core → the installed core
|
|
1984
|
+
+ // root & friends) must keep its default resolution or the
|
|
1985
|
+
+ // pass bundles a second realm of an already-present package.
|
|
1986
|
+
+ if (args.importer &&
|
|
1987
|
+
+ isEsbuildPackageInstalled(esbuildPackageNameOf(args.path), path.dirname(args.importer), projectRoot))
|
|
1988
|
+
+ return undefined;
|
|
1989
|
+
+ const next = args.path.replace(find, replacement);
|
|
1990
|
+
+ if (next === args.path)
|
|
1991
|
+
+ return undefined;
|
|
1992
|
+
+ try {
|
|
1993
|
+
+ const resolved = await build.resolve(next, {
|
|
1994
|
+
+ kind: args.kind,
|
|
1995
|
+
+ importer: args.importer,
|
|
1996
|
+
+ resolveDir: args.resolveDir,
|
|
1997
|
+
+ pluginData: { nsViteAlias: true },
|
|
1998
|
+
+ });
|
|
1999
|
+
+ if (resolved.errors?.length)
|
|
2000
|
+
+ return undefined;
|
|
2001
|
+
+ return {
|
|
2002
|
+
+ path: resolved.path,
|
|
2003
|
+
+ namespace: resolved.namespace,
|
|
2004
|
+
+ external: resolved.external,
|
|
2005
|
+
+ sideEffects: resolved.sideEffects,
|
|
2006
|
+
+ };
|
|
2007
|
+
+ }
|
|
2008
|
+
+ catch {
|
|
2009
|
+
+ return undefined;
|
|
2010
|
+
+ }
|
|
2011
|
+
+ }
|
|
2012
|
+
+ return undefined;
|
|
2013
|
+
+ });
|
|
2014
|
+
+ },
|
|
2015
|
+
+ };
|
|
2016
|
+
+}
|
|
2017
|
+
export function createOptionalDependencyStubEsbuildPlugin(projectRoot) {
|
|
2018
|
+
const requireFromProject = createRequire(path.join(projectRoot, 'package.json'));
|
|
2019
|
+
// `@scope/name/sub` → `@scope/name`; `pkg/sub` → `pkg`; `.prisma/client/…` → `.prisma`.
|