@ng-native/migrate 0.26.1 → 0.28.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/migrations.cjs CHANGED
@@ -23,6 +23,7 @@ const { engineNodeFields } = require('./engine-node-fields.cjs');
23
23
  const { engineNodeTag } = require('./engine-node-tag.cjs');
24
24
  const { libraryTypecheckDeclarationMap } = require('./library-typecheck-declaration-map.cjs');
25
25
  const { nativeTypecheckTarget } = require('./native-typecheck-target.cjs');
26
+ const { osComparisonsOnLinux } = require('./os-comparisons-on-linux.cjs');
26
27
  const { osComparisonsOnMacos } = require('./os-comparisons-on-macos.cjs');
27
28
  const { splitStoreAndPlayer } = require('./split-store-and-player.cjs');
28
29
  const { stopWatchingConditions } = require('./stop-watching-conditions.cjs');
@@ -96,7 +97,7 @@ const migrations = [
96
97
  name: 'vitest-tsconfig-paths',
97
98
  version: '0.18.1',
98
99
  description:
99
- "Resolve the workspace's path aliases in Nx Vitest configs with vite-tsconfig-paths, as nxViteTsPaths does nothing from Nx 24.",
100
+ "Resolve the workspace's path aliases in Nx Vitest configs with Vite's resolve.tsconfigPaths where Vite 8 or later runs the tests and any Vitest listed is 4.1 or later, and with vite-tsconfig-paths otherwise, as nxViteTsPaths does nothing from Nx 24.",
100
101
  run: vitestTsconfigPaths,
101
102
  },
102
103
  {
@@ -113,6 +114,13 @@ const migrations = [
113
114
  "Call each service's available, now a Signal<boolean> on every service, and stop awaiting it.",
114
115
  run: availableSignal,
115
116
  },
117
+ {
118
+ name: 'os-comparisons-on-linux',
119
+ version: '0.24.0',
120
+ description:
121
+ "Note each comparison with 'ios', 'macos' or !== 'android', which answers differently now that Linux is reported as 'linux'.",
122
+ run: osComparisonsOnLinux,
123
+ },
116
124
  ];
117
125
 
118
126
  module.exports = { migrations };
package/native-app.cjs CHANGED
@@ -36,7 +36,7 @@ const dependencies = {
36
36
  'expo-system-ui': '~58.0.6',
37
37
  react: '19.3.0',
38
38
  'react-native': '0.88.0',
39
- 'react-native-safe-area-context': '~5.10.1',
39
+ 'react-native-safe-area-context': '~5.11.1',
40
40
  };
41
41
 
42
42
  /** @type {Record<string, string>} */
@@ -159,7 +159,10 @@ function bundleIdentifier(name, scope) {
159
159
  return ['com', ...(valid(org) ? [org] : []), valid(app) ? app : `app${app}`].join('.');
160
160
  }
161
161
 
162
- /** The package that builds and packages the macOS app, and its config plugin's name. */
162
+ /** The OSes a desktop app runs on, in the order its `platforms` lists them. */
163
+ const DESKTOP_OSES = ['macos', 'linux'];
164
+
165
+ /** The package that builds and packages the desktop app, and its config plugin's name. */
163
166
  const DESKTOP_PACKAGE = '@ng-native/desktop';
164
167
 
165
168
  /** What a desktop app adds to its dependencies: the host and the `ng-native-desktop` command. */
@@ -178,7 +181,7 @@ const desktopOnlyDependencies = Object.fromEntries(
178
181
  ...desktopDependencies,
179
182
  '@ng-native/expo': version,
180
183
  // Exactly the version the prebuilt desktop host is built with, so the app runs on it.
181
- 'react-native-safe-area-context': '5.10.1',
184
+ 'react-native-safe-area-context': '5.11.1',
182
185
  })
183
186
  .filter(([name]) => name !== 'expo-status-bar' && name !== 'expo-system-ui')
184
187
  .sort(([a], [b]) => (a < b ? -1 : 1)),
@@ -195,30 +198,40 @@ const mobileDependencies = Object.fromEntries(
195
198
  );
196
199
 
197
200
  /**
198
- * The scripts a desktop app adds: `npm run macos` builds the host and opens the app from the dev
199
- * server `npm start` runs, and `npm run package` makes the `.app`, `.dmg` or Mac App Store package.
200
- * The Expo CLI has no `run:macos`: its `run` commands are a fixed list.
201
+ * The scripts a desktop app adds: `npm run macos` and `npm run linux` build the host and open the
202
+ * app from the dev server `npm start` runs, and `npm run package` makes the `.app`, `.dmg` or Mac
203
+ * App Store package, or on Linux the `app`, `deb`, `rpm` or `flatpak` one. The Expo CLI has no
204
+ * `run:macos` or `run:linux`: its `run` commands are a fixed list.
201
205
  */
202
- const DESKTOP_SCRIPTS = { macos: 'ng-native-desktop run', package: 'ng-native-desktop package' };
206
+ const DESKTOP_SCRIPTS = {
207
+ macos: 'ng-native-desktop run',
208
+ linux: 'ng-native-desktop run --os linux',
209
+ package: 'ng-native-desktop package',
210
+ };
203
211
 
204
212
  /** What `ng-native-desktop package` writes into the app's directory, for its `.gitignore`. */
205
- const DESKTOP_GITIGNORE = ['# Built by ng-native-desktop package', '/dist/macos', ''].join('\n');
213
+ const DESKTOP_GITIGNORE = [
214
+ '# Built by ng-native-desktop package',
215
+ ...DESKTOP_OSES.map((os) => `/dist/${os}`),
216
+ '',
217
+ ].join('\n');
206
218
 
207
219
  /**
208
- * An Expo config with macOS added: `macos` in `platforms` (with iOS and Android when the config
209
- * named none, which is Expo's default), Expo's `experiments.outOfTreePlatforms`, without which Expo
210
- * drops `macos` from every bundle and export without a word, and the desktop config plugin. Adding
211
- * twice changes nothing.
220
+ * An Expo config with desktop OSes added: each of `oses` in `platforms` (with iOS and Android when
221
+ * the config named none, which is Expo's default), Expo's `experiments.outOfTreePlatforms`, without
222
+ * which Expo drops `macos` and `linux` from every bundle and export without a word, and the desktop
223
+ * config plugin. Adding twice changes nothing.
212
224
  *
213
225
  * @param {Record<string, any>} expo
226
+ * @param {readonly string[]} [oses] the desktop OSes to add, every one by default
214
227
  */
215
- function withDesktop(expo) {
228
+ function withDesktop(expo, oses = DESKTOP_OSES) {
216
229
  const platforms = expo.platforms ?? ['ios', 'android'];
217
230
  const plugins = expo.plugins ?? [];
218
231
  const named = (plugin) => (Array.isArray(plugin) ? plugin[0] : plugin);
219
232
  return {
220
233
  ...expo,
221
- platforms: platforms.includes('macos') ? platforms : [...platforms, 'macos'],
234
+ platforms: [...platforms, ...oses.filter((os) => !platforms.includes(os))],
222
235
  experiments: { ...expo.experiments, outOfTreePlatforms: true },
223
236
  plugins: plugins.some((plugin) => named(plugin) === DESKTOP_PACKAGE)
224
237
  ? plugins
@@ -259,14 +272,16 @@ function withMobile(expo) {
259
272
  * @param {string} name the project name, which is also the Expo slug once any scope is removed
260
273
  * @param {string} [id] the iOS bundle identifier and Android package, by default one from `name`
261
274
  * @param {readonly string[]} [platforms] the OSes the app runs on, iOS and Android by default. With
262
- * `macos`, Expo's `experiments.outOfTreePlatforms` is set too: without it Expo drops `macos` from
263
- * every bundle and export without a word.
275
+ * a desktop OS, Expo's `experiments.outOfTreePlatforms` is set too: without it Expo drops `macos`
276
+ * and `linux` from every bundle and export without a word. Only desktop OSes make the desktop
277
+ * template's app, with no phone settings.
264
278
  */
265
279
  function appJson(name, id, platforms = ['ios', 'android']) {
266
280
  const slug = name.replace(/^@[^/]+\//, '');
267
281
  const bundle = id ?? bundleIdentifier(slug, name.match(/^@[^/]+/)?.[0]);
268
- if (platforms.length === 1 && platforms[0] === 'macos') {
269
- return JSON.stringify({ expo: desktopOnlyExpo(slug, bundle) }, null, 2) + '\n';
282
+ const desktop = platforms.some((os) => DESKTOP_OSES.includes(os));
283
+ if (desktop && platforms.every((os) => DESKTOP_OSES.includes(os))) {
284
+ return JSON.stringify({ expo: desktopOnlyExpo(slug, bundle, platforms) }, null, 2) + '\n';
270
285
  }
271
286
  const expo = {
272
287
  name: slug,
@@ -274,7 +289,7 @@ function appJson(name, id, platforms = ['ios', 'android']) {
274
289
  version: '1.0.0',
275
290
  // Not left to Expo, which adds `web` whenever `react-dom` resolves, and @nx/react puts one there.
276
291
  platforms: [...platforms],
277
- ...(platforms.includes('macos') ? { experiments: { outOfTreePlatforms: true } } : {}),
292
+ ...(desktop ? { experiments: { outOfTreePlatforms: true } } : {}),
278
293
  orientation: 'portrait',
279
294
  userInterfaceStyle: 'automatic',
280
295
  ios: { supportsTablet: true, bundleIdentifier: bundle },
@@ -282,25 +297,26 @@ function appJson(name, id, platforms = ['ios', 'android']) {
282
297
  scheme: slug.replace(/[^a-z0-9]/gi, '').toLowerCase(),
283
298
  // The template's: Expo otherwise guesses a router root from src/app and says so on every start.
284
299
  extra: { router: { root: 'src/app' } },
285
- plugins: ['@ng-native/metro', ...(platforms.includes('macos') ? [DESKTOP_PACKAGE] : [])],
300
+ plugins: ['@ng-native/metro', ...(desktop ? [DESKTOP_PACKAGE] : [])],
286
301
  };
287
302
  return JSON.stringify({ expo }, null, 2) + '\n';
288
303
  }
289
304
 
290
305
  /**
291
- * The desktop template's `app.json`, named for this app: macOS alone, with no phone settings. The
292
- * bundle identifier stays in `ios.bundleIdentifier`, the key a Mac app's is read from, since Apple
293
- * shares one identifier across its OSes.
306
+ * The desktop template's `app.json`, named for this app: the desktop OSes alone, with no phone
307
+ * settings. The bundle identifier stays in `ios.bundleIdentifier`, the key a desktop app's is read
308
+ * from, since Apple shares one identifier across its OSes and a Linux app takes its id from it.
294
309
  *
295
310
  * @param {string} slug
296
311
  * @param {string} bundle
312
+ * @param {readonly string[]} [platforms] the desktop OSes, every one by default
297
313
  */
298
- function desktopOnlyExpo(slug, bundle) {
314
+ function desktopOnlyExpo(slug, bundle, platforms = DESKTOP_OSES) {
299
315
  return {
300
316
  name: slug,
301
317
  slug,
302
318
  version: '1.0.0',
303
- platforms: ['macos'],
319
+ platforms: [...platforms],
304
320
  experiments: { outOfTreePlatforms: true },
305
321
  userInterfaceStyle: 'automatic',
306
322
  ios: { bundleIdentifier: bundle },
@@ -372,12 +388,41 @@ function conflicts(manifest, { linter = 'none' } = {}) {
372
388
  return problems;
373
389
  }
374
390
 
391
+ /**
392
+ * Whether the tests' path aliases can be left to Vite's own `resolve.tsconfigPaths`, which Vite 8
393
+ * added, in a workspace whose root `package.json` is `manifest`: the Vite it lists is 8 or later,
394
+ * or it lists none, and the Vitest it lists, if any, is confirmed to take Vite 8 (Vitest 4.1 and
395
+ * later do). A Vitest older than 4.1 keeps `vite-tsconfig-paths` whatever Vite is listed, since it
396
+ * runs on its own Vite 6 or 7, and so does one whose version cannot be read: `workspace:`,
397
+ * `catalog:`, a tag other than `latest`, a URL. A range, an exact version, an `npm:vitest@<range>`
398
+ * alias and `latest` (the newest release) are read. A Vite it lists that is older, or that is not
399
+ * a range, keeps the plugin too.
400
+ *
401
+ * @param {{ dependencies?: Record<string, string>, devDependencies?: Record<string, string> }} manifest
402
+ */
403
+ function viteResolvesPaths(manifest) {
404
+ const listed = { ...manifest.dependencies, ...manifest.devDependencies };
405
+ const first = (range) => (semver.validRange(range) ? semver.minVersion(range) : null);
406
+ const vitestVersion = (spec) => {
407
+ const range = spec.replace(/^npm:vitest@/, '');
408
+ return range === 'latest' ? semver.coerce('999.0.0') : first(range);
409
+ };
410
+ // Vitest loads the config with the Vite it depends on, so one older than 4.1 (Vite 6 or 7), or
411
+ // one that is not known to be newer, wins over a Vite 8 at the root.
412
+ const vitest = listed.vitest === undefined ? undefined : vitestVersion(listed.vitest);
413
+ const vitestTakesVite8 = vitest === undefined || (vitest !== null && semver.gte(vitest, '4.1.0'));
414
+ if (listed.vite) return (first(listed.vite)?.major ?? 0) >= 8 && vitestTakesVite8;
415
+ return vitestTakesVite8;
416
+ }
417
+
375
418
  module.exports = {
419
+ viteResolvesPaths,
376
420
  dependencies,
377
421
  devDependencies,
378
422
  lintDevDependencies,
379
423
  ESLINT_CONFIG,
380
424
  GITIGNORE,
425
+ DESKTOP_OSES,
381
426
  DESKTOP_PACKAGE,
382
427
  DESKTOP_SCRIPTS,
383
428
  DESKTOP_GITIGNORE,
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 0.24.0 adds Linux as an OS: the `OS` token and `Platform.OS` say `'linux'` there. A Linux bundle
3
+ * takes React Native's iOS files, as a macOS one does, but app code sees `'linux'`, so a check an
4
+ * app wrote for the OSes it knew can be wrong there:
5
+ *
6
+ * - `=== 'ios'` is false on Linux, and `!== 'ios'` true;
7
+ * - `=== 'macos'` is false on Linux, where a check meant as "a desktop OS" wants `DESKTOP`;
8
+ * `!== 'macos'` is true there;
9
+ * - `!== 'android'` is true on Linux, which then takes a branch that may be written for iOS.
10
+ *
11
+ * Which of these an app wants is its own to say, so nothing is rewritten: each comparison in the
12
+ * app's TypeScript, JavaScript, templates and inline templates is noted with its file and line, as
13
+ * `os-comparisons-on-macos` did for macOS. An exhaustive `switch` or a `Record` over the OS type is
14
+ * a compile error until it has a `linux` entry, so tsc finds those.
15
+ */
16
+ const { osComparisonNotes } = require('./os-comparisons-on-macos.cjs');
17
+
18
+ const EQUALITY = new Set(['===', '==', '!==', '!=']);
19
+
20
+ /**
21
+ * Why a comparison answers differently on Linux, or null when it does not.
22
+ *
23
+ * @param {string} operator
24
+ * @param {string} literal the string compared with
25
+ */
26
+ function why(operator, literal) {
27
+ if (!EQUALITY.has(operator)) return null;
28
+ const negated = operator.startsWith('!');
29
+ if (literal === 'ios') {
30
+ return negated
31
+ ? "is true on Linux, where the OS is 'linux'. Check that the branch is right there."
32
+ : "is false on Linux, where the OS is 'linux'. If the branch is about React Native's iOS behaviour, which Linux shares, check for 'linux' too.";
33
+ }
34
+ if (literal === 'macos') {
35
+ return negated
36
+ ? "is true on Linux, where the OS is 'linux'. If the branch is for every OS but a desktop one, check that DESKTOP is false instead, injected into a field where a template reads it."
37
+ : "is false on Linux, where the OS is 'linux'. If the branch is for every desktop OS, check DESKTOP instead, injected into a field where a template reads it.";
38
+ }
39
+ if (literal === 'android' && negated) {
40
+ return 'is true on Linux too, so Linux takes this branch. Check that it is right there.';
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /** @param {import('./host.cjs').Host} host */
46
+ const osComparisonsOnLinux = (host) => osComparisonNotes(host, 'ios|android|macos', why);
47
+
48
+ module.exports = { osComparisonsOnLinux };
@@ -19,27 +19,34 @@ const EQUALITY = new Set(['===', '==', '!==', '!=']);
19
19
  const ORDER = new Set(['<', '<=', '>', '>=', '===', '==', '!==', '!=']);
20
20
 
21
21
  /**
22
- * Whether a file can hold a comparison worth a note at all, before it is parsed. A quote may be
23
- * escaped, as one in a single-quoted inline template is.
22
+ * Whether a file can hold a comparison worth a note at all, before it is parsed: a quoted OS of
23
+ * `oses`, or `OS_VERSION`. A quote may be escaped, as one in a single-quoted inline template is.
24
+ *
25
+ * @param {string} oses the OS names, as a regular expression alternation: `ios|android`
24
26
  */
25
- const mentions = (text) =>
26
- text !== null && (/['"`](ios|android)\\?['"`]/.test(text) || text.includes('OS_VERSION'));
27
+ const mentionsOf = (oses) => {
28
+ const quoted = new RegExp(/['"`](ios|android)\\?['"`]/.source.replace('ios|android', oses));
29
+ return (text) => text !== null && (quoted.test(text) || text.includes('OS_VERSION'));
30
+ };
27
31
 
28
32
  /**
29
- * A comparison in a template binding: with a quoted OS on either side, or of `OS_VERSION` with a
30
- * number on either side.
33
+ * A comparison in a template binding: with a quoted OS of `oses` on either side, or of
34
+ * `OS_VERSION` with a number on either side.
35
+ *
36
+ * @param {string} oses
31
37
  */
32
- const COMPARISON = new RegExp(
33
- [
34
- /(?<os>[\w.$?!]+(?:\(\))?)\s*(?<osOperator>===|!==|==|!=)\s*(?<quote>['"`])(?<literal>ios|android)\k<quote>/,
35
- /(?<firstQuote>['"`])(?<firstLiteral>ios|android)\k<firstQuote>\s*(?<firstOperator>===|!==|==|!=)\s*[\w$][\w.$?!]*(?:\(\))?/,
36
- /\bOS_VERSION\b(?:\(\))?\s*(?<versionOperator><=|>=|<|>|===|!==|==|!=)\s*\d+/,
37
- /\b\d+\s*(?<reversedOperator><=|>=|<|>|===|!==|==|!=)\s*OS_VERSION\b(?:\(\))?/,
38
- ]
39
- .map((pattern) => pattern.source)
40
- .join('|'),
41
- 'g',
42
- );
38
+ const comparisonOf = (oses) =>
39
+ new RegExp(
40
+ [
41
+ /(?<os>[\w.$?!]+(?:\(\))?)\s*(?<osOperator>===|!==|==|!=)\s*(?<quote>['"`])(?<literal>ios|android)\k<quote>/,
42
+ /(?<firstQuote>['"`])(?<firstLiteral>ios|android)\k<firstQuote>\s*(?<firstOperator>===|!==|==|!=)\s*[\w$][\w.$?!]*(?:\(\))?/,
43
+ /\bOS_VERSION\b(?:\(\))?\s*(?<versionOperator><=|>=|<|>|===|!==|==|!=)\s*\d+/,
44
+ /\b\d+\s*(?<reversedOperator><=|>=|<|>|===|!==|==|!=)\s*OS_VERSION\b(?:\(\))?/,
45
+ ]
46
+ .map((pattern) => pattern.source.replace('ios|android', oses))
47
+ .join('|'),
48
+ 'g',
49
+ );
43
50
 
44
51
  /**
45
52
  * Why a comparison answers differently on a Mac, or null when it does not.
@@ -67,8 +74,13 @@ function why(operator, literal, version) {
67
74
  return null;
68
75
  }
69
76
 
70
- /** Notes for the comparisons in a TypeScript or JavaScript file. */
71
- function scriptNotes(ts, file, text) {
77
+ /**
78
+ * Notes for the comparisons in a TypeScript or JavaScript file.
79
+ *
80
+ * @param {(operator: string, literal: string, version: boolean) => string | null} why
81
+ * @param {RegExp} comparison
82
+ */
83
+ function scriptNotes(ts, file, text, why, comparison) {
72
84
  const source = ts.createSourceFile(
73
85
  file,
74
86
  text,
@@ -80,7 +92,7 @@ function scriptNotes(ts, file, text) {
80
92
  const visit = (node) => {
81
93
  if (isInlineTemplate(ts, node)) {
82
94
  const line = source.getLineAndCharacterOfPosition(node.initializer.getStart()).line + 1;
83
- notes.push(...templateNotes(file, node.initializer.text, line));
95
+ notes.push(...templateNotes(file, node.initializer.text, why, comparison, line));
84
96
  }
85
97
  if (ts.isBinaryExpression(node)) {
86
98
  const operator = ts.tokenToString(node.operatorToken.kind) ?? '';
@@ -113,12 +125,14 @@ const isInlineTemplate = (ts, node) =>
113
125
  *
114
126
  * @param {string} file
115
127
  * @param {string} text
128
+ * @param {(operator: string, literal: string, version: boolean) => string | null} why
129
+ * @param {RegExp} comparison
116
130
  * @param {number} [first] the file's line the template starts on, past 1 for an inline one
117
131
  */
118
- function templateNotes(file, text, first = 1) {
132
+ function templateNotes(file, text, why, comparison, first = 1) {
119
133
  const notes = [];
120
134
  // The whole template, since a comparison may break over lines; noted at the line it starts on.
121
- for (const match of text.matchAll(COMPARISON)) {
135
+ for (const match of text.matchAll(comparison)) {
122
136
  const { osOperator, literal, firstOperator, firstLiteral, versionOperator, reversedOperator } =
123
137
  match.groups ?? {};
124
138
  const reason = osOperator
@@ -132,18 +146,34 @@ function templateNotes(file, text, first = 1) {
132
146
  return notes;
133
147
  }
134
148
 
135
- /** @param {import('./host.cjs').Host} host */
136
- function osComparisonsOnMacos(host) {
149
+ /**
150
+ * A note, with its file and line, at each comparison in the app's TypeScript, JavaScript, templates
151
+ * and inline templates with a quoted OS of `oses`, or of `OS_VERSION`, that `why` has a reason for.
152
+ *
153
+ * @param {import('./host.cjs').Host} host
154
+ * @param {string} oses the OS names to look for, as a regular expression alternation
155
+ * @param {(operator: string, literal: string, version: boolean) => string | null} why
156
+ */
157
+ function osComparisonNotes(host, oses, why) {
137
158
  const ts = typescript();
159
+ const mentions = mentionsOf(oses);
160
+ const comparison = comparisonOf(oses);
138
161
  const notes = [];
139
162
  for (const file of files(host)) {
140
163
  const script = SOURCE.test(file) && !file.endsWith('.d.ts');
141
164
  if (!script && !TEMPLATE.test(file)) continue;
142
165
  const text = host.read(file);
143
166
  if (!mentions(text)) continue;
144
- notes.push(...(script ? scriptNotes(ts, file, text) : templateNotes(file, text)));
167
+ notes.push(
168
+ ...(script
169
+ ? scriptNotes(ts, file, text, why, comparison)
170
+ : templateNotes(file, text, why, comparison)),
171
+ );
145
172
  }
146
173
  return notes;
147
174
  }
148
175
 
149
- module.exports = { osComparisonsOnMacos };
176
+ /** @param {import('./host.cjs').Host} host */
177
+ const osComparisonsOnMacos = (host) => osComparisonNotes(host, 'ios|android', why);
178
+
179
+ module.exports = { osComparisonsOnMacos, osComparisonNotes };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-native/migrate",
3
- "version": "0.26.1",
3
+ "version": "0.28.0",
4
4
  "description": "The migrations that update an Angular Native app to a new release, for nx migrate, ng update and npx.",
5
5
  "keywords": [
6
6
  "angular",
@@ -8,44 +8,81 @@
8
8
  * imports `tsconfigPaths` from `vite-tsconfig-paths` in its place, and the root `package.json`
9
9
  * gains `vite-tsconfig-paths` when it lists neither. A config the generator did not write is left
10
10
  * as it is.
11
+ *
12
+ * Where the workspace's Vite resolves tsconfig paths itself (Vite 8 and later, with a Vitest that
13
+ * takes it: the same test the generators use), each config gets Vite's `resolve.tsconfigPaths`
14
+ * instead, with no import, and the root `package.json` gains `vite` where it lists none. A config
15
+ * that cannot take the option, one with a `resolve` of its own or the call somewhere other than
16
+ * first in a `plugins` list, gets the plugin as before. A config already on `vite-tsconfig-paths`
17
+ * or on `resolve.tsconfigPaths` no longer matches and is left as it is, so running the migration
18
+ * on a workspace that has had it changes nothing.
11
19
  */
12
20
  const { files } = require('./host.cjs');
13
21
  const { formatted } = require('./sync-app-versions.cjs');
22
+ const { viteResolvesPaths } = require('./native-app.cjs');
14
23
 
15
24
  // Either quote, as the workspace's Prettier formats it.
16
25
  const FROM =
17
26
  /import \{ nxViteTsPaths \} from (['"])@nx\/vite\/plugins\/nx-tsconfig-paths\.plugin\1;/;
18
27
  const TO = 'import tsconfigPaths from $1vite-tsconfig-paths$1;';
19
- const DEPENDENCY = { name: 'vite-tsconfig-paths', range: '^5.1.4' };
28
+ const PLUGIN = { name: 'vite-tsconfig-paths', range: '^5.1.4' };
29
+ const VITE = { name: 'vite', range: '^8.0.0' };
30
+ const FIRST_PLUGIN = /plugins: \[nxViteTsPaths\(\), /g;
31
+
32
+ /** The config with Vite's own option in place of the plugin, or null where it cannot take it. */
33
+ function viaVite(text) {
34
+ if (/\bresolve['"]?\s*:/.test(text)) return null;
35
+ const next = text
36
+ .replace(new RegExp(`${FROM.source}\\r?\\n?`), '')
37
+ .replace(FIRST_PLUGIN, 'resolve: { tsconfigPaths: true }, plugins: [');
38
+ return next.includes('nxViteTsPaths') ? null : next;
39
+ }
20
40
 
21
41
  /**
22
- * Rewrites each config the generators wrote, and answers whether there was one.
42
+ * Rewrites each config the generators wrote, and answers which dependency the root `package.json`
43
+ * needs for the ones it rewrote. `vite` is the one a config that
44
+ * left the aliases to Vite needs; `vite-tsconfig-paths` is the one any other config does.
23
45
  *
24
46
  * @param {import('./host.cjs').Host} host
47
+ * @param {() => boolean} resolvesPaths whether the workspace's Vite resolves the aliases itself,
48
+ * asked only once a config needs the answer
25
49
  */
26
- function rewriteConfigs(host) {
27
- let changed = false;
50
+ function rewriteConfigs(host, resolvesPaths) {
51
+ const needed = new Set();
28
52
  for (const file of files(host)) {
29
53
  if (file !== 'vitest.config.mts' && !file.endsWith('/vitest.config.mts')) continue;
30
54
  const text = host.read(file) ?? '';
31
55
  if (!FROM.test(text) || !text.includes('@ng-native/testing/vitest')) continue;
32
- host.write(file, text.replace(FROM, TO).replace(/\bnxViteTsPaths\(\)/g, 'tsconfigPaths()'));
33
- changed = true;
56
+ const native = resolvesPaths() ? viaVite(text) : null;
57
+ host.write(
58
+ file,
59
+ native ?? text.replace(FROM, TO).replace(/\bnxViteTsPaths\(\)/g, 'tsconfigPaths()'),
60
+ );
61
+ needed.add(native === null ? PLUGIN : VITE);
34
62
  }
35
- return changed;
63
+ return needed;
36
64
  }
37
65
 
38
66
  /** @param {import('./host.cjs').Host} host */
39
67
  function vitestTsconfigPaths(host) {
40
- const original = rewriteConfigs(host) ? host.read('package.json') : null;
41
- if (original === null) return [];
68
+ const original = host.read('package.json');
69
+ // With no manifest to read the Vite from, the plugin works on any Vite.
70
+ const needed = rewriteConfigs(
71
+ host,
72
+ () => original !== null && viteResolvesPaths(JSON.parse(original)),
73
+ );
74
+ if (original === null || needed.size === 0) return [];
42
75
  const manifest = JSON.parse(original);
43
- if (manifest.dependencies?.[DEPENDENCY.name] || manifest.devDependencies?.[DEPENDENCY.name]) {
44
- return [];
45
- }
46
- manifest.devDependencies = { ...manifest.devDependencies, [DEPENDENCY.name]: DEPENDENCY.range };
76
+ const added = [...needed].filter(
77
+ ({ name }) => !manifest.dependencies?.[name] && !manifest.devDependencies?.[name],
78
+ );
79
+ if (added.length === 0) return [];
80
+ manifest.devDependencies = {
81
+ ...manifest.devDependencies,
82
+ ...Object.fromEntries(added.map(({ name, range }) => [name, range])),
83
+ };
47
84
  host.write('package.json', formatted(manifest, original));
48
- return ['Install vite-tsconfig-paths, which the root package.json now lists.'];
85
+ return added.map(({ name }) => `Install ${name}, which the root package.json now lists.`);
49
86
  }
50
87
 
51
88
  module.exports = { vitestTsconfigPaths };