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.
Files changed (77) hide show
  1. package/README.md +2 -144
  2. package/compatibility.json +97 -19
  3. package/compatibility.ts +141 -72
  4. package/dist/compatibility.js +66 -26
  5. package/dist/index.js +127 -64
  6. package/dist/package-manager.js +62 -0
  7. package/dist/scaffold.js +377 -127
  8. package/index.ts +256 -154
  9. package/library-template/AGENTS.md +6 -4
  10. package/library-template/README.md +22 -18
  11. package/library-template/bunfig +4 -0
  12. package/library-template/package.json +115 -18
  13. package/library-template/patches/@nativescript-community__octane@0.2.5.patch +1018 -0
  14. package/library-template/patches/@nativescript-community__sqlite-bridge@4.1.1.patch +30 -0
  15. package/library-template/patches/@nativescript-community__vite-octane@0.2.1.patch +72 -0
  16. package/library-template/patches/@nativescript__core@9.1.3.patch +1280 -0
  17. package/library-template/patches/@nativescript__doctor@2.0.18.patch +13 -0
  18. package/library-template/patches/@nativescript__vite@8.0.20.patch +2019 -0
  19. package/library-template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
  20. package/library-template/patches/@octanejs__tiptap@0.0.62.patch +12 -0
  21. package/library-template/patches/@sveltejs__acorn-typescript@1.0.13.patch +16 -0
  22. package/library-template/patches/css@3.0.0.patch +52 -0
  23. package/library-template/patches/octane@0.16.3.patch +1479 -0
  24. package/library-template/src/Badge.tsx +7 -6
  25. package/library-template/src/Badge.web.tsx +7 -6
  26. package/library-template/src/Welcome.stories.tsx +12 -0
  27. package/library-template/src/normalizeBadgeLabel.ts +1 -1
  28. package/library-template/src/props.ts +11 -11
  29. package/library-template/tests/normalizeBadgeLabel.test.ts +1 -1
  30. package/library-template/tests/packed-consumer.mjs +140 -123
  31. package/library-template/tsconfig.envs.json +1 -0
  32. package/library-template/tsconfig.json +1 -0
  33. package/library-template/tsconfig.types.json +15 -1
  34. package/library-template/tsrx-typegen.json +1 -1
  35. package/library-template/workshop.config.ts +3 -0
  36. package/package-manager.ts +93 -0
  37. package/package.json +70 -58
  38. package/scaffold.ts +1056 -526
  39. package/template/.agents/skills/xplat/SKILL.md +6 -6
  40. package/template/.agents/skills/xplat/references/components.md +1 -1
  41. package/template/.agents/skills/xplat/references/navigation.md +1 -1
  42. package/template/.agents/skills/xplat/references/styling.md +14 -14
  43. package/template/AGENTS.md +10 -10
  44. package/template/bunfig +4 -0
  45. package/template/gitignore +1 -0
  46. package/template/nativescript.config.ts +13 -16
  47. package/template/package.json +119 -10
  48. package/template/patches/@nativescript-community__octane@0.2.5.patch +1018 -0
  49. package/template/patches/@nativescript-community__sqlite-bridge@4.1.1.patch +30 -0
  50. package/template/patches/@nativescript-community__vite-octane@0.2.1.patch +72 -0
  51. package/template/patches/@nativescript__core@9.1.3.patch +1280 -0
  52. package/template/patches/@nativescript__doctor@2.0.18.patch +13 -0
  53. package/template/patches/@nativescript__vite@8.0.20.patch +2019 -0
  54. package/template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
  55. package/template/patches/@octanejs__tiptap@0.0.62.patch +12 -0
  56. package/template/patches/@sveltejs__acorn-typescript@1.0.13.patch +16 -0
  57. package/template/patches/css@3.0.0.patch +52 -0
  58. package/template/patches/octane@0.16.3.patch +1479 -0
  59. package/template/src/App.tsrx +77 -42
  60. package/template/src/Welcome.stories.tsx +22 -0
  61. package/template/src/app.spec.tsrx +169 -163
  62. package/template/src/app.web.test.tsx +18 -13
  63. package/template/src/failure-reporting.spec.ts +3 -3
  64. package/template/src/main.ts +14 -13
  65. package/template/src/main.tsrx +2 -0
  66. package/template/src/main.web.tsrx +5 -5
  67. package/template/src/native-runtime.spec.ts +13 -11
  68. package/template/src/test-setup.web.ts +9 -8
  69. package/template/src/test.ts +6 -6
  70. package/template/tsconfig.json +17 -1
  71. package/template/vite.config.native.mts +1 -2
  72. package/template/vite.config.ts +29 -23
  73. package/template/vitest.config.mts +18 -18
  74. package/template/vitest.web.config.mts +7 -7
  75. package/template/workshop.config.ts +3 -0
  76. package/library-template/pnpm-workspace.yaml +0 -171
  77. package/template/pnpm-workspace.yaml +0 -192
package/scaffold.ts CHANGED
@@ -2,23 +2,35 @@
2
2
  // CLI's `xplat add`. compatibility.json owns version pins; the generated
3
3
  // templates own script bodies and the dependency set for each starter.
4
4
  import {
5
- cpSync,
6
- existsSync,
7
- mkdirSync,
8
- readdirSync,
9
- readFileSync,
10
- statSync,
11
- writeFileSync,
5
+ cpSync,
6
+ lstatSync,
7
+ existsSync,
8
+ mkdirSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ statSync,
12
+ writeFileSync,
12
13
  } from 'node:fs'
13
14
 
14
- import { basename, dirname, join, resolve } from 'node:path'
15
+ import { basename, dirname, join, resolve, relative, isAbsolute, sep } from 'node:path'
15
16
  import { fileURLToPath } from 'node:url'
16
- import { parseDocument } from 'yaml'
17
- import { ensureCompatibilityCatalog } from './compatibility.ts'
17
+ import { createHash } from 'node:crypto'
18
+ import { isMap, parseDocument, stringify } from 'yaml'
19
+ import {
20
+ compatibility,
21
+ mergeCompatibilityCatalog,
22
+ compatibilityRoot,
23
+ requestedCatalogPins,
24
+ } from './compatibility.ts'
25
+
26
+ import type { PackageManager } from './package-manager.ts'
27
+
28
+ export type { PackageManager } from './package-manager.ts'
18
29
 
19
30
  const moduleDir = dirname(fileURLToPath(import.meta.url))
20
31
  // dist/ emit sits one level deeper than the root sources it mirrors.
21
32
  const pkgRoot = basename(moduleDir) === 'dist' ? join(moduleDir, '..') : moduleDir
33
+
22
34
  export const TEMPLATE_DIR = join(pkgRoot, 'template')
23
35
  export const LIBRARY_TEMPLATE_DIR = join(pkgRoot, 'library-template')
24
36
 
@@ -27,80 +39,87 @@ export const LIBRARY_TEMPLATE_DIR = join(pkgRoot, 'library-template')
27
39
  * values come from template/package.json. `typecheck` contributes one clause
28
40
  * to the generated typecheck script. */
29
41
  export const targets: Record<string, any> = {
30
- web: {
31
- label: 'Web (Vite)',
32
- files: [
33
- 'index.html',
34
- 'vite.config.ts',
35
- 'src/main.web.tsrx',
36
- 'vitest.web.config.mts',
37
- 'src/app.web.test.tsx',
38
- 'src/test-setup.web.ts',
39
- ],
40
- scripts: ['dev', 'build', 'test', 'test:web'],
41
- devDeps: ['@octanejs/vite-plugin', 'jsdom'],
42
- },
43
- ios: {
44
- label: 'iOS (NativeScript)',
45
- requires: ['native-shared'],
46
- files: ['App_Resources/iOS'],
47
- scripts: ['dev:ios', 'build:ios', 'test:ios'],
48
- devDeps: ['@nativescript/ios'],
49
- note: 'needs macOS + Xcode — `pnpm xplat doctor` checks the toolchain',
50
- },
51
- android: {
52
- label: 'Android (NativeScript)',
53
- requires: ['native-shared'],
54
- files: ['App_Resources/Android'],
55
- scripts: ['dev:android', 'build:android', 'test:android'],
56
- devDeps: ['@nativescript/android'],
57
- note: 'needs Android SDK + a compatible JDK — `pnpm xplat doctor` checks the toolchain',
58
- },
59
- // Shared NativeScript machinery pulled in by ios/android. Not user-
60
- // selectable on its own. `patches` names the packages whose
61
- // patchedDependencies entries in pnpm-workspace.yaml belong to this
62
- // fragment — pnpm hard-fails installs on unused patch entries, so a
63
- // scaffold must not carry patches for deps it doesn't install.
64
- 'native-shared': {
65
- hidden: true,
66
- patches: [
67
- '@nativescript/core',
68
- '@nativescript/types',
69
- 'css',
70
- '@nativescript/vite',
71
- '@nativescript-community/octane',
72
- '@nativescript-community/vite-octane',
73
- ],
74
- files: [
75
- 'nativescript.config.ts',
76
- 'vite.config.native.mts',
77
- 'references.d.ts',
78
- 'src/main.ts',
79
- 'vitest.config.mts',
80
- 'src/test.ts',
81
- 'src/app.spec.tsrx',
82
- 'src/native-runtime.spec.ts',
83
- 'src/failure-reporting.spec.ts',
84
- ],
85
- deps: [
86
- '@nativescript-community/octane',
87
- '@nativescript/core',
88
- '@valor/nativescript-websockets',
89
- ],
90
- devDeps: [
91
- '@nativescript-community/vite-octane',
92
- '@nativescript/types',
93
- '@nativescript/unit-test-runner',
94
- '@nativescript/vite',
95
- 'nativescript',
96
- ],
97
- typecheck: 'xplat typecheck',
98
- },
42
+ web: {
43
+ label: 'Web (Vite)',
44
+ files: [
45
+ 'index.html',
46
+ 'vite.config.ts',
47
+ 'src/main.web.tsrx',
48
+ 'vitest.web.config.mts',
49
+ 'src/app.web.test.tsx',
50
+ 'src/test-setup.web.ts',
51
+ ],
52
+ scripts: ['dev', 'build', 'test', 'test:web', 'workshop'],
53
+ devDeps: ['@octanejs/vite-plugin', 'jsdom', '@octane-xplat/workshop'],
54
+ },
55
+ ios: {
56
+ label: 'iOS (NativeScript)',
57
+ requires: ['native-shared'],
58
+ files: ['App_Resources/iOS'],
59
+ scripts: ['dev:ios', 'build:ios', 'test:ios'],
60
+ devDeps: ['@nativescript/ios'],
61
+ note: 'needs macOS + Xcode — `bun run xplat doctor` checks the toolchain',
62
+ },
63
+ android: {
64
+ label: 'Android (NativeScript)',
65
+ requires: ['native-shared'],
66
+ files: ['App_Resources/Android'],
67
+ scripts: ['dev:android', 'build:android', 'test:android'],
68
+ devDeps: ['@nativescript/android'],
69
+ note: 'needs Android SDK + a compatible JDK — `bun run xplat doctor` checks the toolchain',
70
+ },
71
+ // Shared NativeScript machinery pulled in by ios/android. Not user-
72
+ // selectable on its own. `patches` names the packages whose
73
+ // patchedDependencies entries in package.json belong to this
74
+ // fragment — Bun hard-fails installs on unused patch entries, so a
75
+ // scaffold must not carry patches for deps it doesn't install.
76
+ 'native-shared': {
77
+ hidden: true,
78
+ // Build-script approvals claimed by this target — the scaffolded
79
+ // allowBuilds entry for `nativescript` only exists once native-shared
80
+ // resolves (web-only trees never install it).
81
+ builds: ['nativescript'],
82
+ patches: [
83
+ '@nativescript/core',
84
+ '@nativescript/types',
85
+ 'css',
86
+ '@nativescript/vite',
87
+ '@nativescript-community/octane',
88
+ '@nativescript-community/vite-octane',
89
+ ],
90
+ files: [
91
+ 'nativescript.config.ts',
92
+ 'vite.config.native.mts',
93
+ 'references.d.ts',
94
+ 'src/main.ts',
95
+ 'vitest.config.mts',
96
+ 'src/test.ts',
97
+ 'src/app.spec.tsrx',
98
+ 'src/native-runtime.spec.ts',
99
+ 'src/failure-reporting.spec.ts',
100
+ ],
101
+ deps: [
102
+ '@nativescript-community/octane',
103
+ '@nativescript/core',
104
+ '@valor/nativescript-websockets',
105
+ ],
106
+ devDeps: [
107
+ '@octane-xplat/workshop',
108
+ '@nativescript-community/vite-octane',
109
+ '@nativescript/types',
110
+ '@nativescript/unit-test-runner',
111
+ '@nativescript/vite',
112
+ 'nativescript',
113
+ // The classic-API checker path used by the native Vite plugin.
114
+ 'typescript-classic',
115
+ ],
116
+ typecheck: 'xplat typecheck',
117
+ },
99
118
  }
100
119
 
101
120
  export const selectableTargets = Object.keys(targets).filter((id) => !targets[id].hidden)
102
121
 
103
- /** `pnpm create` without --targets and `xplat add`'s prompt default. */
122
+ /** `bun create` without --targets and `xplat add`'s prompt default. */
104
123
  export const defaultTargets = ['web', 'ios', 'android']
105
124
 
106
125
  const BASE_TYPECHECK = 'xplat typecheck'
@@ -111,274 +130,383 @@ const BASE_SCRIPTS = ['xplat', 'lint', 'lint:fix', 'format']
111
130
 
112
131
  /** Expand `requires` edges, dependencies first. Throws on unknown ids. */
113
132
  export function resolveTargets(ids) {
114
- const resolved: string[] = []
115
- const visit = (id) => {
116
- const t = targets[id]
117
- if (!t) {
118
- throw new Error(`unknown target "${id}" — expected one of: ${selectableTargets.join(', ')}`)
119
- }
120
-
121
- for (const req of t.requires ?? []) {
122
- visit(req)
123
- }
124
-
125
- if (!resolved.includes(id)) {
126
- resolved.push(id)
127
- }
128
- }
129
-
130
- for (const id of ids) {
131
- visit(id)
132
- }
133
-
134
- return resolved
133
+ const resolved: string[] = []
134
+ const visit = (id) => {
135
+ const t = targets[id]
136
+
137
+ if (!t) {
138
+ throw new Error(`unknown target "${id}" — expected one of: ${selectableTargets.join(', ')}`)
139
+ }
140
+
141
+ for (const req of t.requires ?? []) {
142
+ visit(req)
143
+ }
144
+
145
+ if (!resolved.includes(id)) {
146
+ resolved.push(id)
147
+ }
148
+ }
149
+
150
+ for (const id of ids) {
151
+ visit(id)
152
+ }
153
+
154
+ return resolved
135
155
  }
136
156
 
137
157
  const templateManifest = () => JSON.parse(readFileSync(join(TEMPLATE_DIR, 'package.json'), 'utf8'))
138
158
 
139
159
  /** Which target claims a template-relative path (entries may be dirs). */
140
160
  function ownerOf(path) {
141
- for (const [id, t] of Object.entries(targets)) {
142
- for (const entry of t.files) {
143
- if (path === entry || path.startsWith(entry + '/')) {
144
- return id
145
- }
146
- }
147
- }
148
-
149
- return null
161
+ for (const [id, t] of Object.entries(targets)) {
162
+ for (const entry of t.files) {
163
+ if (path === entry || path.startsWith(entry + '/')) {
164
+ return id
165
+ }
166
+ }
167
+ }
168
+
169
+ return null
150
170
  }
151
171
 
152
172
  function walk(dir, prefix = '') {
153
- const out: string[] = []
154
- for (const name of readdirSync(dir)) {
155
- if (name === 'node_modules') {
156
- continue
157
- }
158
-
159
- const rel = prefix ? `${prefix}/${name}` : name
160
- if (statSync(join(dir, name)).isDirectory()) {
161
- out.push(...walk(join(dir, name), rel))
162
- } else {
163
- out.push(rel)
164
- }
165
- }
166
-
167
- return out
173
+ const out: string[] = []
174
+
175
+ for (const name of readdirSync(dir)) {
176
+ if (name === 'node_modules') {
177
+ continue
178
+ }
179
+
180
+ const rel = prefix ? `${prefix}/${name}` : name
181
+
182
+ if (statSync(join(dir, name)).isDirectory()) {
183
+ out.push(...walk(join(dir, name), rel))
184
+ } else {
185
+ out.push(rel)
186
+ }
187
+ }
188
+
189
+ return out
168
190
  }
169
191
 
170
192
  function pickKeys(source, names, label) {
171
- const out: Record<string, string> = {}
172
- for (const name of names) {
173
- if (source[name] === undefined) {
174
- throw new Error(`template/package.json has no ${label} entry "${name}"`)
175
- }
193
+ const out: Record<string, string> = {}
176
194
 
177
- out[name] = source[name]
178
- }
195
+ for (const name of names) {
196
+ if (source[name] === undefined) {
197
+ throw new Error(`template/package.json has no ${label} entry "${name}"`)
198
+ }
179
199
 
180
- return out
200
+ out[name] = source[name]
201
+ }
202
+
203
+ return out
181
204
  }
182
205
 
183
206
  /**
184
207
  * The package.json a given target set produces. With every target selected
185
- * this is identical to template/package.json.
208
+ * this is identical to template/package.json. For pnpm the Bun-config homes
209
+ * move to pnpm-workspace.yaml — composePnpmWorkspace emits the other half.
186
210
  */
187
- export function composeManifest(ids) {
188
- const resolved = resolveTargets(ids)
189
- const tpl = templateManifest()
190
- const manifest: Record<string, any> = { ...tpl }
191
-
192
- for (const section of ['dependencies', 'devDependencies']) {
193
- const key = section === 'dependencies' ? 'deps' : 'devDeps'
194
- const wanted = new Set<string>()
195
- for (const id of resolved) {
196
- for (const name of targets[id][key] ?? []) {
197
- wanted.add(name)
198
- }
199
- }
200
-
201
- const next = {}
202
- for (const [name, spec] of Object.entries(tpl[section] ?? {})) {
203
- // Unclaimed entries are base; claimed entries follow their target.
204
- const claimed = Object.keys(targets).some((id) => (targets[id][key] ?? []).includes(name))
205
-
206
- if (!claimed || wanted.has(name)) {
207
- next[name] = spec
208
- }
209
- }
210
-
211
- manifest[section] = next
212
- }
213
-
214
- const wantedScripts = new Set(BASE_SCRIPTS)
215
- for (const id of resolved) {
216
- for (const name of targets[id].scripts ?? []) {
217
- wantedScripts.add(name)
218
- }
219
- }
220
-
221
- const scripts = pickKeys(tpl.scripts ?? {}, [...wantedScripts].sort(), 'script')
222
- const typecheck: string[] = [BASE_TYPECHECK]
223
- for (const id of resolved) {
224
- if (targets[id].typecheck) {
225
- typecheck.push(targets[id].typecheck)
226
- }
227
- }
228
-
229
- scripts.typecheck = [...new Set(typecheck)].join(' && ')
230
- // Keep the template's key order: scripts sit where they were.
231
- manifest.scripts = {}
232
- for (const name of Object.keys(tpl.scripts ?? {})) {
233
- if (name === 'typecheck' || wantedScripts.has(name)) {
234
- manifest.scripts[name] = scripts[name]
235
- }
236
- }
237
-
238
- if (!resolved.includes('native-shared')) {
239
- // "main" points at the native entry — meaningless without it.
240
- delete manifest.main
241
- }
242
-
243
- return manifest
211
+ export function composeManifest(ids: string[], packageManager: PackageManager = 'bun') {
212
+ const resolved = resolveTargets(ids)
213
+ const tpl = templateManifest()
214
+ const manifest: Record<string, any> = { ...tpl }
215
+
216
+ for (const section of ['dependencies', 'devDependencies']) {
217
+ const key = section === 'dependencies' ? 'deps' : 'devDeps'
218
+ const wanted = new Set<string>()
219
+
220
+ for (const id of resolved) {
221
+ for (const name of targets[id][key] ?? []) {
222
+ wanted.add(name)
223
+ }
224
+ }
225
+
226
+ const next = {}
227
+
228
+ for (const [name, spec] of Object.entries(tpl[section] ?? {})) {
229
+ // Unclaimed entries are base; claimed entries follow their target.
230
+ const claimed = Object.keys(targets).some((id) => (targets[id][key] ?? []).includes(name))
231
+
232
+ if (!claimed || wanted.has(name)) {
233
+ next[name] = spec
234
+ }
235
+ }
236
+
237
+ manifest[section] = next
238
+ }
239
+
240
+ const wantedScripts = new Set(BASE_SCRIPTS)
241
+
242
+ for (const id of resolved) {
243
+ for (const name of targets[id].scripts ?? []) {
244
+ wantedScripts.add(name)
245
+ }
246
+ }
247
+
248
+ const scripts = pickKeys(tpl.scripts ?? {}, [...wantedScripts].sort(), 'script')
249
+ const typecheck: string[] = [BASE_TYPECHECK]
250
+
251
+ for (const id of resolved) {
252
+ if (targets[id].typecheck) {
253
+ typecheck.push(targets[id].typecheck)
254
+ }
255
+ }
256
+
257
+ scripts.typecheck = [...new Set(typecheck)].join(' && ')
258
+ // Keep the template's key order: scripts sit where they were.
259
+ manifest.scripts = {}
260
+ for (const name of Object.keys(tpl.scripts ?? {})) {
261
+ if (name === 'typecheck' || wantedScripts.has(name)) {
262
+ manifest.scripts[name] = scripts[name]
263
+ }
264
+ }
265
+
266
+ if (!resolved.includes('native-shared')) {
267
+ // "main" points at the native entry — meaningless without it.
268
+ delete manifest.main
269
+ }
270
+
271
+ const drop = new Set(
272
+ Object.entries(targets)
273
+ .filter(([id]) => !resolved.includes(id))
274
+ .flatMap(([, target]) => target.patches ?? []),
275
+ )
276
+
277
+ manifest.patchedDependencies = Object.fromEntries(
278
+ Object.entries(tpl.patchedDependencies).filter(
279
+ ([key]) => !drop.has(key.slice(0, key.indexOf('@', 1))),
280
+ ),
281
+ )
282
+
283
+ const used = new Set([
284
+ ...Object.keys(manifest.dependencies),
285
+ ...Object.keys(manifest.devDependencies),
286
+ ])
287
+
288
+ manifest.workspaces = {
289
+ ...tpl.workspaces,
290
+ catalogs: {
291
+ ...tpl.workspaces.catalogs,
292
+ xplat: Object.fromEntries(
293
+ Object.entries(tpl.workspaces.catalogs.xplat).filter(([name]) => used.has(name)),
294
+ ),
295
+ },
296
+ }
297
+
298
+ if (packageManager === 'bun') {
299
+ return manifest
300
+ }
301
+
302
+ return splitForPnpm(manifest, new Set(resolved)).manifest
244
303
  }
245
304
 
246
- // --- pnpm-workspace.yaml patchedDependencies --------------------------------
247
- // Patch entries look like ` octane@0.6.3: <path>` or
248
- // ` "@nativescript/core@9.1.2": <path>`, each preceded by a comment block.
249
- // Ownership comes from each target's `patches` list; unclaimed entries are
250
- // base and ship in every scaffold.
251
- const PATCH_ENTRY = /^\s+"?(@?[\w./-]+@[\w.-]+)"?:\s+\S+\s*$/
305
+ // pnpm 11 fails an install when a dependency's build scripts are neither
306
+ // approved nor denied in allowBuilds, where Bun silently skips untrusted
307
+ // ones. These are the packages real pnpm installs reported that are not
308
+ // trusted — `target` scopes an entry to the target set whose dependency
309
+ // tree contains it. Approved entries are not listed here: they come from
310
+ // the manifest's trustedDependencies filtered by target `builds` claims.
311
+ const deniedBuilds: { name: string; target?: string }[] = [
312
+ // @octane-xplat/nativescript-mason-core pulls @nativescript/core into even
313
+ // the web-only tree; its build scripts are not trusted.
314
+ { name: '@nativescript/core' },
315
+ // onnxruntime-web (via @octane-xplat/docs-search) pulls protobufjs into the
316
+ // tree; its postinstall is a no-op and must not run.
317
+ { name: 'protobufjs' },
318
+ ]
252
319
 
253
- const patchPkg = (key) => key.replace(/@[^@]+$/, '')
320
+ /**
321
+ * The allowBuilds map for a resolved target set: trusted dependencies (with
322
+ * target claims applied) approve, everything pnpm reported denies.
323
+ */
324
+ function allowBuildsFor(manifest, resolved: Set<string>) {
325
+ const wanted = new Set<string>()
326
+
327
+ for (const id of resolved) {
328
+ for (const name of targets[id].builds ?? []) {
329
+ wanted.add(name)
330
+ }
331
+ }
332
+
333
+ const builds: Record<string, boolean> = {}
334
+
335
+ for (const name of manifest.trustedDependencies ?? []) {
336
+ const claimed = Object.values(targets).some((target) => (target.builds ?? []).includes(name))
337
+
338
+ if (!claimed || wanted.has(name)) {
339
+ builds[name] = true
340
+ }
341
+ }
342
+
343
+ for (const entry of deniedBuilds) {
344
+ if (!entry.target || resolved.has(entry.target)) {
345
+ builds[entry.name] = false
346
+ }
347
+ }
348
+
349
+ return Object.fromEntries(
350
+ Object.keys(builds)
351
+ .sort()
352
+ .map((name) => [name, builds[name]]),
353
+ )
354
+ }
355
+
356
+ /**
357
+ * Move Bun's config homes — catalogs, overrides, patches, trusted
358
+ * dependencies, the bun engine — out of the composed manifest into the
359
+ * pnpm-workspace.yaml object. Both manager variants come from the same
360
+ * composed manifest so pins can never disagree.
361
+ */
362
+ function splitForPnpm(manifest, resolved: Set<string>) {
363
+ const next = { ...manifest }
364
+ const workspace: Record<string, any> = {}
365
+
366
+ workspace.packages = next.workspaces?.packages ?? []
367
+ if (next.workspaces?.catalogs) {
368
+ workspace.catalogs = next.workspaces.catalogs
369
+ }
370
+
371
+ delete next.workspaces
372
+ if (next.overrides) {
373
+ workspace.overrides = next.overrides
374
+ delete next.overrides
375
+ }
376
+
377
+ if (next.patchedDependencies) {
378
+ workspace.patchedDependencies = next.patchedDependencies
379
+ delete next.patchedDependencies
380
+ }
381
+
382
+ // Matches what `xplat upgrade` writes; shipped patch files may sit unused
383
+ // for a target set (tiptap, doctor, sqlite-bridge are always copied).
384
+ workspace.allowUnusedPatches = true
385
+ workspace.allowBuilds = allowBuildsFor(next, resolved)
386
+ delete next.trustedDependencies
387
+ // NativeScript resolves plugins from a flat tree — same reason bunfig sets
388
+ // the hoisted linker for Bun.
389
+ workspace.nodeLinker = 'hoisted'
390
+ workspace.saveExact = true
391
+ if (next.engines) {
392
+ delete next.engines.bun
393
+ if (Object.keys(next.engines).length === 0) {
394
+ delete next.engines
395
+ }
396
+ }
397
+
398
+ next.packageManager = `pnpm@${compatibility.tools.pnpm}`
399
+ return { manifest: next, workspace }
400
+ }
254
401
 
255
402
  /** The pnpm-workspace.yaml a given target set produces. */
256
- export function composeWorkspaceYaml(ids) {
257
- const resolved = new Set(resolveTargets(ids))
258
- const drop = new Set<string>()
259
- for (const [id, t] of Object.entries(targets)) {
260
- if (!resolved.has(id)) {
261
- for (const name of t.patches ?? []) {
262
- drop.add(name)
263
- }
264
- }
265
- }
266
-
267
- const lines = readFileSync(join(TEMPLATE_DIR, 'pnpm-workspace.yaml'), 'utf8').split('\n')
268
- const out: string[] = []
269
- let inPatches = false
270
- let pending: string[] = []
271
- for (const line of lines) {
272
- if (/^\S/.test(line)) {
273
- out.push(...pending, line)
274
- pending = []
275
- inPatches = line.startsWith('patchedDependencies')
276
- continue
277
- }
278
-
279
- if (!inPatches) {
280
- out.push(line)
281
- continue
282
- }
283
-
284
- const m = line.match(PATCH_ENTRY)
285
- if (!m) {
286
- pending.push(line) // comment/blank inside the section
287
- continue
288
- }
289
-
290
- if (drop.has(patchPkg(m[1]))) {
291
- pending = []
292
- continue
293
- }
294
-
295
- out.push(...pending, line)
296
- pending = []
297
- }
298
-
299
- out.push(...pending)
300
- const doc = parseDocument(out.join('\n'))
301
- const manifest = composeManifest(ids)
302
- const used = new Set([
303
- ...Object.keys(manifest.dependencies),
304
- ...Object.keys(manifest.devDependencies),
305
- ])
306
- for (const name of Object.keys(doc.toJS().catalogs?.xplat ?? {})) {
307
- if (!used.has(name)) {
308
- doc.deleteIn(['catalogs', 'xplat', name])
309
- }
310
- }
311
- return String(doc)
403
+ export function composePnpmWorkspace(ids: string[]): string {
404
+ const resolved = resolveTargets(ids)
405
+ const { workspace } = splitForPnpm(composeManifest(resolved), new Set(resolved))
406
+
407
+ return stringify(workspace)
408
+ }
409
+
410
+ /** Patch [specifier, path] entries the enabled targets need and `present` lacks. */
411
+ function neededPatchEntries(enabledIds, present: Set<string>): [string, string][] {
412
+ const needed = new Set(enabledIds.flatMap((id) => targets[id].patches ?? []))
413
+ const out: [string, string][] = []
414
+
415
+ for (const [specifier, path] of Object.entries(templateManifest().patchedDependencies) as [
416
+ string,
417
+ string,
418
+ ][]) {
419
+ const name = specifier.slice(0, specifier.indexOf('@', 1))
420
+
421
+ if (!needed.has(name) || present.has(name)) {
422
+ continue
423
+ }
424
+
425
+ out.push([specifier, path])
426
+ }
427
+
428
+ return out
429
+ }
430
+
431
+ /** Copy a canonical patch into the root patches/ dir unless it already matches. */
432
+ function stagePatchFile(root, path, read, write) {
433
+ const source = join(TEMPLATE_DIR, path)
434
+ const destination = join(root, path)
435
+ const before = read(destination)
436
+
437
+ if (before !== null && !readFileSync(source).equals(before)) {
438
+ throw new Error(
439
+ `Custom patch ${destination} differs from the framework patch; reconcile it first`,
440
+ )
441
+ }
442
+
443
+ write(destination, readFileSync(source), statSync(source).mode & 0o777)
444
+ }
445
+
446
+ const specifierName = (specifier: string) => specifier.slice(0, specifier.indexOf('@', 1))
447
+
448
+ /** Add target-owned local patches before installing newly enabled dependencies. */
449
+ function ensurePatchEntries(enabledIds, root, pkg, read, write) {
450
+ const present = new Set(Object.keys(pkg.patchedDependencies ?? {}).map(specifierName))
451
+
452
+ pkg.patchedDependencies ??= {}
453
+
454
+ let changed = false
455
+
456
+ for (const [specifier, path] of neededPatchEntries(enabledIds, present)) {
457
+ stagePatchFile(root, path, read, write)
458
+ pkg.patchedDependencies[specifier] = path
459
+ changed = true
460
+ }
461
+
462
+ return changed
463
+ }
464
+
465
+ /** The selected manager at a workspace root — mirrors the CLI's detection. */
466
+ function managerForRoot(root: string, pkg) {
467
+ const declared = pkg?.packageManager?.split('@')[0]
468
+
469
+ if (declared !== undefined) {
470
+ if (declared === 'bun' || declared === 'pnpm') {
471
+ return declared
472
+ }
473
+
474
+ throw new Error(`Xplat supports Bun and pnpm projects; found packageManager ${declared}.`)
475
+ }
476
+
477
+ const bun = existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb'))
478
+ const pnpm = existsSync(join(root, 'pnpm-lock.yaml'))
479
+
480
+ if (bun && pnpm) {
481
+ throw new Error(
482
+ 'Both Bun and pnpm lockfiles exist. Set packageManager in package.json or pass --package-manager.',
483
+ )
484
+ }
485
+
486
+ if (bun) {
487
+ return 'bun'
488
+ }
489
+
490
+ if (pnpm) {
491
+ return 'pnpm'
492
+ }
493
+
494
+ if (pkg?.patchedDependencies) {
495
+ return 'bun'
496
+ }
497
+
498
+ return existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm' : 'bun'
312
499
  }
313
500
 
314
501
  /**
315
- * Add the patch entries that `enabledIds` owns to the owning workspace's
316
- * pnpm-workspace.yaml. Entries already present (by package name, any
317
- * version) are kept. Returns true if the file changed.
502
+ * Native tsconfig `paths` pinning `@nativescript/core` to the app's own
503
+ * install. Without it, a `link:`/`file:`/`portal:` framework checkout's core
504
+ * imports resolve to that checkout's own copy and checkers see two distinct
505
+ * `View`/`Page`/`Color` type identities (private-member conflicts, issue #66).
318
506
  */
319
- function ensurePatchEntries(appRoot, enabledIds) {
320
- const needed = new Set()
321
- for (const id of enabledIds) {
322
- for (const name of targets[id].patches ?? []) {
323
- needed.add(name)
324
- }
325
- }
326
-
327
- if (!needed.size) {
328
- return false
329
- }
330
-
331
- // Match catalog ownership: adding a target must not split an existing
332
- // monorepo into a new, nested workspace.
333
- let workspace = resolve(appRoot)
334
- while (!existsSync(join(workspace, 'pnpm-workspace.yaml')) && dirname(workspace) !== workspace) {
335
- workspace = dirname(workspace)
336
- }
337
- if (!existsSync(join(workspace, 'pnpm-workspace.yaml'))) {
338
- workspace = appRoot
339
- }
340
- const yamlPath = join(workspace, 'pnpm-workspace.yaml')
341
- const appText = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf8') : ''
342
- if (!appText.trim()) {
343
- writeFileSync(yamlPath, composeWorkspaceYaml(enabledIds))
344
- return true
345
- }
346
-
347
- const doc = parseDocument(appText)
348
- if (doc.errors.length) {
349
- throw new Error(`${yamlPath}: ${doc.errors[0].message}`)
350
- }
351
- const present = new Set(Object.keys(doc.toJS()?.patchedDependencies ?? {}).map(patchPkg))
352
- const template = parseDocument(
353
- readFileSync(join(TEMPLATE_DIR, 'pnpm-workspace.yaml'), 'utf8'),
354
- ).toJS()
355
- let changed = false
356
- for (const [key, path] of Object.entries(template.patchedDependencies)) {
357
- const name = patchPkg(key)
358
- if (needed.has(name) && !present.has(name)) {
359
- doc.setIn(['patchedDependencies', key], path)
360
- changed = true
361
- }
362
- }
363
-
364
- // Template paths are relative to the owning workspace. pnpm installs the
365
- // config package there before resolving its patch files on the first install.
366
- for (const [name, spec] of Object.entries(template.configDependencies)) {
367
- const prefix = `node_modules/.pnpm-config/${name}/`
368
- const usesPackage = Object.values(doc.toJS()?.patchedDependencies ?? {}).some(
369
- (path) => typeof path === 'string' && path.startsWith(prefix),
370
- )
371
-
372
- if (usesPackage && !doc.hasIn(['configDependencies', name])) {
373
- doc.setIn(['configDependencies', name], spec)
374
- changed = true
375
- }
376
- }
377
-
378
- if (changed) {
379
- writeFileSync(yamlPath, String(doc))
380
- }
381
- return changed
507
+ export const nativeCorePaths = {
508
+ '@nativescript/core': ['./node_modules/@nativescript/core'],
509
+ '@nativescript/core/*': ['./node_modules/@nativescript/core/*'],
382
510
  }
383
511
 
384
512
  /**
@@ -387,119 +515,218 @@ function ensurePatchEntries(appRoot, enabledIds) {
387
515
  * scaffold just drops the native ambient root and entrypoint.
388
516
  */
389
517
  export function composeTsconfig(ids) {
390
- const resolved = new Set(resolveTargets(ids))
391
- const config = JSON.parse(readFileSync(join(TEMPLATE_DIR, 'tsconfig.json'), 'utf8'))
392
- if (!resolved.has('native-shared')) {
393
- delete config.files
394
- config.compilerOptions.types = (config.compilerOptions.types ?? []).filter(
395
- (t) => t !== '@nativescript/types',
396
- )
397
-
398
- config.exclude = [...new Set([...(config.exclude ?? []), 'src/main.ts'])]
399
- }
400
-
401
- return JSON.stringify(config, null, '\t') + '\n'
518
+ const resolved = new Set(resolveTargets(ids))
519
+ const config = JSON.parse(readFileSync(join(TEMPLATE_DIR, 'tsconfig.json'), 'utf8'))
520
+
521
+ if (!resolved.has('native-shared')) {
522
+ delete config.files
523
+ delete config.compilerOptions.paths
524
+ config.compilerOptions.types = (config.compilerOptions.types ?? []).filter(
525
+ (t) => t !== '@nativescript/types',
526
+ )
527
+
528
+ config.exclude = [...new Set([...(config.exclude ?? []), 'src/main.ts'])]
529
+ }
530
+
531
+ return JSON.stringify(config, null, '\t') + '\n'
532
+ }
533
+
534
+ /**
535
+ * Starter text files whose command forms follow the chosen package manager.
536
+ * Nothing under patches/ is ever transformed — patch bytes must equal the
537
+ * canonical copies.
538
+ */
539
+ const managerTextFiles = [
540
+ 'AGENTS.md',
541
+ 'README.md',
542
+ 'nativescript.config.ts',
543
+ 'vitest.config.mts',
544
+ 'src/app.spec.tsrx',
545
+ ]
546
+
547
+ const isManagerTextFile = (rel: string) =>
548
+ managerTextFiles.includes(rel) || rel.startsWith('.agents/skills/xplat/')
549
+
550
+ // Template file names that differ from their scaffolded names: dotfiles and
551
+ // bunfig ship without their final names because npm/bun packing drops them.
552
+ const renamedFiles: Record<string, string> = {
553
+ gitignore: '.gitignore',
554
+ bunfig: 'bunfig.toml',
555
+ }
556
+
557
+ const destName = (rel: string) => renamedFiles[rel] ?? rel
558
+
559
+ /**
560
+ * Rewrite the canonical Bun command forms in starter text for another
561
+ * manager. Applied only to managerTextFiles.
562
+ */
563
+ export function localizeCommands(text: string, manager: PackageManager): string {
564
+ if (manager === 'bun') {
565
+ return text
566
+ }
567
+
568
+ return (
569
+ text
570
+ // `bun run script -- args`: pnpm forwards a literal `--`, bun strips it.
571
+ .replace(/\bbun run (\S+) -- /g, 'pnpm run $1 ')
572
+ .replace(/\bbunx\b/g, 'pnpm dlx')
573
+ .replace(/\bbun pm pack\b/g, 'pnpm pack')
574
+ .replace(/\bbun run\b/g, 'pnpm run')
575
+ .replace(/\bbun add\b/g, 'pnpm add')
576
+ .replace(/\bbun install\b/g, 'pnpm install')
577
+ .replace(/packageManager: 'bun'/g, "packageManager: 'pnpm'")
578
+ )
402
579
  }
403
580
 
404
581
  /** Write a scaffold with tests for `ids` into `dir` (must not exist or be empty). */
405
- export function composeTargets(ids, dir) {
406
- const resolved = new Set(resolveTargets(ids))
407
- mkdirSync(dir, { recursive: true })
408
-
409
- for (const rel of walk(TEMPLATE_DIR)) {
410
- if (rel === 'package.json' || rel === 'pnpm-workspace.yaml' || rel === 'tsconfig.json') {
411
- continue // generated below
412
- }
413
-
414
- const owner = ownerOf(rel)
415
- if (owner && !resolved.has(owner)) {
416
- continue
417
- }
418
-
419
- const dest = join(dir, rel === 'gitignore' ? '.gitignore' : rel)
420
- mkdirSync(dirname(dest), { recursive: true })
421
- cpSync(join(TEMPLATE_DIR, rel), dest, { recursive: true })
422
- }
423
-
424
- writeFileSync(join(dir, 'package.json'), JSON.stringify(composeManifest(ids), null, '\t') + '\n')
425
- writeFileSync(join(dir, 'pnpm-workspace.yaml'), composeWorkspaceYaml(ids))
426
- writeFileSync(join(dir, 'tsconfig.json'), composeTsconfig(ids))
427
- return [...resolved]
582
+ export function composeTargets(ids, dir, options?: { packageManager?: PackageManager }) {
583
+ const packageManager = options?.packageManager ?? 'bun'
584
+ const resolved = new Set(resolveTargets(ids))
585
+
586
+ mkdirSync(dir, { recursive: true })
587
+
588
+ for (const rel of walk(TEMPLATE_DIR)) {
589
+ if (rel === 'package.json' || rel === 'tsconfig.json') {
590
+ continue // generated below
591
+ }
592
+
593
+ if (packageManager === 'pnpm' && rel === 'bunfig') {
594
+ continue
595
+ }
596
+
597
+ const owner = ownerOf(rel)
598
+
599
+ if (owner && !resolved.has(owner)) {
600
+ continue
601
+ }
602
+
603
+ const source = join(TEMPLATE_DIR, rel)
604
+ const dest = join(dir, destName(rel))
605
+
606
+ mkdirSync(dirname(dest), { recursive: true })
607
+ if (packageManager === 'pnpm' && isManagerTextFile(rel)) {
608
+ writeFileSync(dest, localizeCommands(readFileSync(source, 'utf8'), packageManager))
609
+ } else {
610
+ cpSync(source, dest, { recursive: true })
611
+ }
612
+ }
613
+
614
+ writeFileSync(
615
+ join(dir, 'package.json'),
616
+ JSON.stringify(composeManifest(ids, packageManager), null, '\t') + '\n',
617
+ )
618
+
619
+ writeFileSync(join(dir, 'tsconfig.json'), composeTsconfig(ids))
620
+ if (packageManager === 'pnpm') {
621
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), composePnpmWorkspace(ids))
622
+ }
623
+
624
+ return [...resolved]
428
625
  }
429
626
 
430
627
  /** Write the cross-platform library starter into `dir`. */
431
- export function composeLibrary(dir, packageName = basename(resolve(dir))) {
432
- if (
433
- packageName.length > 214 ||
434
- !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(packageName)
435
- ) {
436
- throw new Error(
437
- `invalid npm package name "${packageName}" — use lowercase letters, numbers, dots, underscores, or hyphens`,
438
- )
439
- }
440
-
441
- mkdirSync(dir, { recursive: true })
442
- for (const rel of walk(LIBRARY_TEMPLATE_DIR)) {
443
- if (rel === 'package.json') {
444
- continue
445
- }
446
-
447
- const dest = join(dir, rel === 'gitignore' ? '.gitignore' : rel)
448
- mkdirSync(dirname(dest), { recursive: true })
449
- const source = join(LIBRARY_TEMPLATE_DIR, rel)
450
- if (/\.(?:md|ts|tsx|mjs|json)$/.test(rel)) {
451
- const content = readFileSync(source, 'utf8').replaceAll('octane-xplat-library', packageName)
452
- writeFileSync(dest, content)
453
- } else {
454
- cpSync(source, dest, { recursive: true })
455
- }
456
- }
457
-
458
- const manifest = JSON.parse(readFileSync(join(LIBRARY_TEMPLATE_DIR, 'package.json'), 'utf8'))
459
- manifest.name = packageName
460
- writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest, null, '\t') + '\n')
628
+ export function composeLibrary(
629
+ dir,
630
+ packageName = basename(resolve(dir)),
631
+ options?: { packageManager?: PackageManager },
632
+ ) {
633
+ if (
634
+ packageName.length > 214 ||
635
+ !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(packageName)
636
+ ) {
637
+ throw new Error(
638
+ `invalid npm package name "${packageName}" — use lowercase letters, numbers, dots, underscores, or hyphens`,
639
+ )
640
+ }
641
+
642
+ const packageManager = options?.packageManager ?? 'bun'
643
+
644
+ mkdirSync(dir, { recursive: true })
645
+ for (const rel of walk(LIBRARY_TEMPLATE_DIR)) {
646
+ if (rel === 'package.json' || (packageManager === 'pnpm' && rel === 'bunfig')) {
647
+ continue
648
+ }
649
+
650
+ const dest = join(dir, destName(rel))
651
+
652
+ mkdirSync(dirname(dest), { recursive: true })
653
+
654
+ const source = join(LIBRARY_TEMPLATE_DIR, rel)
655
+
656
+ if (/\.(?:md|ts|tsx|mjs|json)$/.test(rel)) {
657
+ let content = readFileSync(source, 'utf8').replaceAll('octane-xplat-library', packageName)
658
+
659
+ if (packageManager === 'pnpm' && isManagerTextFile(rel)) {
660
+ content = localizeCommands(content, packageManager)
661
+ }
662
+
663
+ writeFileSync(dest, content)
664
+ } else {
665
+ cpSync(source, dest, { recursive: true })
666
+ }
667
+ }
668
+
669
+ const manifest = JSON.parse(readFileSync(join(LIBRARY_TEMPLATE_DIR, 'package.json'), 'utf8'))
670
+
671
+ manifest.name = packageName
672
+ if (packageManager === 'pnpm') {
673
+ for (const [name, script] of Object.entries(manifest.scripts ?? {})) {
674
+ manifest.scripts[name] = localizeCommands(String(script), packageManager)
675
+ }
676
+
677
+ // The library exercises web and native builds — its dependency tree spans
678
+ // the native toolchain, so target claims resolve as native-shared.
679
+ const { manifest: split, workspace } = splitForPnpm(manifest, new Set(['native-shared']))
680
+
681
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(split, null, '\t') + '\n')
682
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), stringify(workspace))
683
+ return
684
+ }
685
+
686
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest, null, '\t') + '\n')
461
687
  }
462
688
 
463
689
  const readJson = (file) => {
464
- try {
465
- return JSON.parse(readFileSync(file, 'utf8'))
466
- } catch {
467
- return null
468
- }
690
+ try {
691
+ return JSON.parse(readFileSync(file, 'utf8'))
692
+ } catch {
693
+ return null
694
+ }
469
695
  }
470
696
 
471
697
  /** Sentinel-based enablement check, mirroring the CLI's targets.mjs. */
472
698
  export function targetEnabled(appRoot, id) {
473
- if (id === 'web') {
474
- return (
475
- existsSync(join(appRoot, 'vite.config.ts')) || existsSync(join(appRoot, 'vite.config.mts'))
476
- )
477
- }
478
-
479
- if (id === 'native-shared') {
480
- return existsSync(join(appRoot, 'nativescript.config.ts'))
481
- }
482
-
483
- // ios/android: declared runtime devDep is the canonical signal — App_Resources
484
- // alone doesn't reach the bundler config.
485
- const manifest: Record<string, any> = readJson(join(appRoot, 'package.json')) ?? {}
486
- const declared = { ...manifest.dependencies, ...manifest.devDependencies }
487
- const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[id]
488
- return runtime ? typeof declared[runtime] === 'string' : false
699
+ if (id === 'web') {
700
+ return (
701
+ existsSync(join(appRoot, 'vite.config.ts')) || existsSync(join(appRoot, 'vite.config.mts'))
702
+ )
703
+ }
704
+
705
+ if (id === 'native-shared') {
706
+ return existsSync(join(appRoot, 'nativescript.config.ts'))
707
+ }
708
+
709
+ // ios/android: declared runtime devDep is the canonical signal — App_Resources
710
+ // alone doesn't reach the bundler config.
711
+ const manifest: Record<string, any> = readJson(join(appRoot, 'package.json')) ?? {}
712
+ const declared = { ...manifest.dependencies, ...manifest.devDependencies }
713
+ const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[id]
714
+
715
+ return runtime ? typeof declared[runtime] === 'string' : false
489
716
  }
490
717
 
491
718
  /** Copy a template file/dir into the app unless the destination exists. */
492
- function copyMissing(rel, appRoot, report) {
493
- const src = join(TEMPLATE_DIR, rel)
494
- const dest = join(appRoot, rel === 'gitignore' ? '.gitignore' : rel)
495
- if (existsSync(dest)) {
496
- report.skipped.push(rel)
497
- return
498
- }
499
-
500
- mkdirSync(dirname(dest), { recursive: true })
501
- cpSync(src, dest, { recursive: true })
502
- report.copied.push(rel)
719
+ function copyMissing(rel, appRoot, report, present, copy) {
720
+ const src = join(TEMPLATE_DIR, rel)
721
+ const dest = join(appRoot, destName(rel))
722
+
723
+ if (present(dest)) {
724
+ report.skipped.push(rel)
725
+ return
726
+ }
727
+
728
+ copy(src, dest)
729
+ report.copied.push(rel)
503
730
  }
504
731
 
505
732
  /**
@@ -508,118 +735,421 @@ function copyMissing(rel, appRoot, report) {
508
735
  * suffix — so enabling native means wiring the ambient declaration file and
509
736
  * the entrypoint into the app's own config.
510
737
  */
511
- function enableNativeInTsconfig(appRoot) {
512
- const path = join(appRoot, 'tsconfig.json')
513
- const text = existsSync(path) ? readFileSync(path, 'utf8') : ''
514
- const config = readJson(path)
515
- if (!config || typeof config !== 'object') {
516
- return false
517
- }
518
-
519
- const indent = text.match(/\n(\s+)"/)?.[1] ?? '\t'
520
- config.files = [...new Set(['references.d.ts', ...(config.files ?? [])])]
521
- config.exclude = (config.exclude ?? []).filter((e) => e !== 'src/main.ts')
522
-
523
- const types = config.compilerOptions?.types
524
- if (config.compilerOptions && Array.isArray(types) && !types.includes('@nativescript/types')) {
525
- config.compilerOptions.types = [...types, '@nativescript/types']
526
- }
527
-
528
- writeFileSync(path, JSON.stringify(config, null, indent) + '\n')
529
- return true
738
+ function enableNativeInTsconfig(appRoot, read, write) {
739
+ const path = join(appRoot, 'tsconfig.json')
740
+ const text = read(path)?.toString('utf8') ?? ''
741
+ let config
742
+
743
+ try {
744
+ config = JSON.parse(text)
745
+ } catch {
746
+ return false
747
+ }
748
+
749
+ if (!config || typeof config !== 'object') {
750
+ return false
751
+ }
752
+
753
+ const indent = text.match(/\n(\s+)"/)?.[1] ?? '\t'
754
+
755
+ config.files = [...new Set(['references.d.ts', ...(config.files ?? [])])]
756
+ config.exclude = (config.exclude ?? []).filter((e) => e !== 'src/main.ts')
757
+
758
+ const types = config.compilerOptions?.types
759
+
760
+ if (config.compilerOptions && Array.isArray(types) && !types.includes('@nativescript/types')) {
761
+ config.compilerOptions.types = [...types, '@nativescript/types']
762
+ }
763
+
764
+ // Pin core's type identity for linked checkouts; user-authored paths and
765
+ // an existing core mapping always win.
766
+ if (config.compilerOptions && typeof config.compilerOptions === 'object') {
767
+ const paths = (config.compilerOptions.paths ??= {})
768
+
769
+ for (const [key, value] of Object.entries(nativeCorePaths)) {
770
+ if (!(key in paths)) {
771
+ paths[key] = value
772
+ }
773
+ }
774
+ }
775
+
776
+ write(path, Buffer.from(JSON.stringify(config, null, indent) + '\n'), 0o644)
777
+ return true
530
778
  }
531
779
 
532
780
  /**
533
- * Enable `id` (plus unmet `requires`) inside an existing app at `appRoot`.
534
- * Additive only: existing files, scripts, and dep entries are skipped, never
535
- * overwritten. Returns a report for the caller to render.
781
+ * Plan enabling `id` and unmet requirements without writing. Existing target
782
+ * files, scripts and dependency choices stay intact; managed config and catalog
783
+ * changes carry raw-byte input hashes for the publisher.
536
784
  */
785
+ export function planTarget(appRoot, id) {
786
+ appRoot = resolve(appRoot)
787
+
788
+ const root = compatibilityRoot(appRoot)
789
+ const inputs = new Map<string, any>()
790
+ const contents = new Map<string, Buffer>()
791
+ const files = new Map<string, any>()
792
+ const directories = new Map<string, number>()
793
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
794
+ const within = (path) => {
795
+ const rel = relative(root, path)
796
+
797
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel))
798
+ }
799
+
800
+ const observe = (path) => {
801
+ path = resolve(path)
802
+ if (!within(path)) {
803
+ throw new Error(`Scaffold path leaves its workspace: ${path}`)
804
+ }
805
+
806
+ if (inputs.has(path)) {
807
+ return inputs.get(path)
808
+ }
809
+
810
+ let info
811
+
812
+ try {
813
+ info = lstatSync(path)
814
+ } catch (error) {
815
+ if (error.code !== 'ENOENT') {
816
+ throw error
817
+ }
818
+
819
+ const input = { path, kind: 'missing' }
820
+
821
+ inputs.set(path, input)
822
+ return input
823
+ }
824
+
825
+ if (info.isSymbolicLink() || (!info.isDirectory() && !info.isFile())) {
826
+ throw new Error(`Scaffold path must be an ordinary file or directory: ${path}`)
827
+ }
828
+
829
+ const input: Record<string, any> = {
830
+ path,
831
+ kind: info.isDirectory() ? 'directory' : 'file',
832
+ mode: info.mode & 0o777,
833
+ }
834
+
835
+ if (input.kind === 'file') {
836
+ if (info.size > 16 * 1024 * 1024) {
837
+ throw new Error(`Scaffold input exceeds 16 MiB: ${path}`)
838
+ }
839
+
840
+ const bytes = readFileSync(path)
841
+
842
+ input.sha256 = hash(bytes)
843
+ contents.set(path, bytes)
844
+ }
845
+
846
+ inputs.set(path, input)
847
+ return input
848
+ }
849
+
850
+ const read = (path) => {
851
+ const input = observe(path)
852
+
853
+ if (input.kind === 'missing') {
854
+ return null
855
+ }
856
+
857
+ if (input.kind !== 'file') {
858
+ throw new Error(`Expected scaffold file: ${path}`)
859
+ }
860
+
861
+ return contents.get(resolve(path))!
862
+ }
863
+
864
+ const directory = (path, mode = 0o755) => {
865
+ if (path === root || path === appRoot) {
866
+ return
867
+ }
868
+
869
+ const input = observe(path)
870
+
871
+ if (input.kind === 'directory') {
872
+ return
873
+ }
874
+
875
+ if (input.kind !== 'missing') {
876
+ throw new Error(`Expected scaffold directory: ${path}`)
877
+ }
878
+
879
+ directory(dirname(path))
880
+ directories.set(path, mode)
881
+ }
882
+
883
+ const write = (path, bytes, mode) => {
884
+ const before = read(path)
885
+
886
+ if (before !== null && before.equals(bytes)) {
887
+ return
888
+ }
889
+
890
+ directory(dirname(path))
891
+ files.set(path, {
892
+ path,
893
+ before: before === null ? null : hash(before),
894
+ content: bytes.toString('base64'),
895
+ mode: before === null ? mode : observe(path).mode,
896
+ })
897
+ }
898
+
899
+ const copy = (source, dest) => {
900
+ const info = lstatSync(source)
901
+
902
+ if (info.isDirectory()) {
903
+ directory(dest, info.mode & 0o777)
904
+ for (const name of readdirSync(source).sort()) {
905
+ copy(join(source, name), join(dest, name))
906
+ }
907
+ } else if (info.isFile()) {
908
+ write(dest, readFileSync(source), info.mode & 0o777)
909
+ } else {
910
+ throw new Error(`Scaffold template must not contain aliases: ${source}`)
911
+ }
912
+ }
913
+
914
+ const manifestPath = join(appRoot, 'package.json')
915
+ const raw = read(manifestPath)?.toString('utf8')
916
+
917
+ if (raw === undefined) {
918
+ throw new Error(`No package.json at ${appRoot}`)
919
+ }
920
+
921
+ const manifest: Record<string, any> = JSON.parse(raw)
922
+ const tpl = templateManifest()
923
+ const report: Record<string, any> = {
924
+ enabled: [],
925
+ already: [],
926
+ copied: [],
927
+ skipped: [],
928
+ scriptsAdded: [],
929
+ scriptsSkipped: [],
930
+ depsAdded: [],
931
+ }
932
+
933
+ for (const tid of resolveTargets([id])) {
934
+ const declared = { ...manifest.dependencies, ...manifest.devDependencies }
935
+ const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[tid]
936
+ const enabled =
937
+ tid === 'web'
938
+ ? observe(join(appRoot, 'vite.config.ts')).kind !== 'missing' ||
939
+ observe(join(appRoot, 'vite.config.mts')).kind !== 'missing'
940
+ : tid === 'native-shared'
941
+ ? observe(join(appRoot, 'nativescript.config.ts')).kind !== 'missing'
942
+ : runtime !== undefined && typeof declared[runtime] === 'string'
943
+
944
+ if (enabled) {
945
+ report.already.push(tid)
946
+ continue
947
+ }
948
+
949
+ report.enabled.push(tid)
950
+
951
+ const t = targets[tid]
952
+
953
+ for (const rel of t.files) {
954
+ copyMissing(rel, appRoot, report, (path) => observe(path).kind !== 'missing', copy)
955
+ }
956
+
957
+ for (const [section, key] of [
958
+ ['dependencies', 'deps'],
959
+ ['devDependencies', 'devDeps'],
960
+ ]) {
961
+ for (const name of t[key] ?? []) {
962
+ manifest[section] ??= {}
963
+ if (manifest[section][name] === undefined) {
964
+ manifest[section][name] = tpl[section][name]
965
+ report.depsAdded.push(name)
966
+ }
967
+ }
968
+ }
969
+
970
+ manifest.scripts ??= {}
971
+ for (const name of t.scripts ?? []) {
972
+ if (manifest.scripts[name] === undefined) {
973
+ manifest.scripts[name] = tpl.scripts[name]
974
+ report.scriptsAdded.push(name)
975
+ } else if (manifest.scripts[name] !== tpl.scripts[name]) {
976
+ report.scriptsSkipped.push(name)
977
+ }
978
+ }
979
+
980
+ if (t.typecheck) {
981
+ const current = manifest.scripts.typecheck ?? ''
982
+
983
+ if (!current.includes(t.typecheck)) {
984
+ manifest.scripts.typecheck = current ? `${current} && ${t.typecheck}` : t.typecheck
985
+ report.scriptsAdded.push('typecheck')
986
+ }
987
+ }
988
+
989
+ if (tid === 'native-shared') {
990
+ if (manifest.main === undefined) {
991
+ manifest.main = tpl.main
992
+ }
993
+
994
+ // Native sources join the app's single typecheck program — pull the
995
+ // ambient declaration entry into the roots and un-exclude the
996
+ // NativeScript entry that a web-only scaffold skips.
997
+ report.tsconfigUpdated = enableNativeInTsconfig(appRoot, read, write)
998
+ }
999
+ }
1000
+
1001
+ // Newly enabled targets may carry patch entries the scaffolded
1002
+ // package.json never had — without them the next install misses the
1003
+ // framework patches. enabled+already covers the yaml-missing case, where
1004
+ // the file is regenerated for the whole enabled set.
1005
+ const enabledTargets = [...report.enabled, ...report.already]
1006
+ const manager = managerForRoot(
1007
+ root,
1008
+ root === appRoot
1009
+ ? manifest
1010
+ : JSON.parse(read(join(root, 'package.json'))?.toString('utf8') ?? 'null'),
1011
+ )
1012
+
1013
+ if (manager === 'pnpm') {
1014
+ const yamlPath = join(root, 'pnpm-workspace.yaml')
1015
+ const doc = parseDocument(read(yamlPath)?.toString('utf8') ?? 'packages: []\n')
1016
+ const { catalog, pins } = requestedCatalogPins(manifest)
1017
+
1018
+ for (const [name, spec] of Object.entries(pins)) {
1019
+ if (doc.getIn(['catalogs', catalog, name]) === undefined) {
1020
+ doc.setIn(['catalogs', catalog, name], spec)
1021
+ }
1022
+ }
1023
+
1024
+ const existing = doc.get('patchedDependencies')
1025
+ const present = new Set<string>(
1026
+ (isMap(existing) ? existing.items : []).map((pair) => specifierName(String(pair.key))),
1027
+ )
1028
+
1029
+ const patches = neededPatchEntries(enabledTargets, present)
1030
+
1031
+ for (const [specifier, path] of patches) {
1032
+ stagePatchFile(root, path, read, write)
1033
+ doc.setIn(['patchedDependencies', specifier], path)
1034
+ }
1035
+
1036
+ if (patches.length) {
1037
+ report.patchesAdded = true
1038
+ }
1039
+
1040
+ const resolved = new Set(resolveTargets(enabledTargets))
1041
+
1042
+ for (const id of resolved) {
1043
+ for (const name of targets[id].builds ?? []) {
1044
+ if (doc.getIn(['allowBuilds', name]) === undefined) {
1045
+ doc.setIn(['allowBuilds', name], true)
1046
+ report.allowBuildsAdded = true
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ for (const entry of deniedBuilds) {
1052
+ if (
1053
+ (!entry.target || resolved.has(entry.target)) &&
1054
+ doc.getIn(['allowBuilds', entry.name]) === undefined
1055
+ ) {
1056
+ doc.setIn(['allowBuilds', entry.name], false)
1057
+ report.allowBuildsAdded = true
1058
+ }
1059
+ }
1060
+
1061
+ write(yamlPath, Buffer.from(String(doc)), 0o644)
1062
+ } else {
1063
+ const owner =
1064
+ root === appRoot ? manifest : JSON.parse(read(join(root, 'package.json'))!.toString('utf8'))
1065
+
1066
+ if (ensurePatchEntries(enabledTargets, root, owner, read, write)) {
1067
+ report.patchesAdded = true
1068
+ }
1069
+
1070
+ mergeCompatibilityCatalog(manifest, owner)
1071
+ if (root !== appRoot) {
1072
+ write(
1073
+ join(root, 'package.json'),
1074
+ Buffer.from(JSON.stringify(owner, null, '\t') + '\n'),
1075
+ 0o644,
1076
+ )
1077
+ }
1078
+ }
1079
+
1080
+ if (JSON.stringify(manifest) !== JSON.stringify(JSON.parse(raw))) {
1081
+ // Match the file's existing indent so diffs stay minimal.
1082
+ const indent = raw.match(/\n(\s+)"/)?.[1] ?? '\t'
1083
+
1084
+ write(manifestPath, Buffer.from(JSON.stringify(manifest, null, indent) + '\n'), 0o644)
1085
+ }
1086
+
1087
+ if (files.size > 8192 || inputs.size > 20000 || directories.size > 8192) {
1088
+ throw new Error('Scaffold plan exceeds inventory limits')
1089
+ }
1090
+
1091
+ let total = 0
1092
+
1093
+ for (const file of files.values()) {
1094
+ const bytes = Buffer.from(file.content, 'base64').length
1095
+
1096
+ total += bytes
1097
+ if (bytes > 16 * 1024 * 1024 || total > 32 * 1024 * 1024) {
1098
+ throw new Error('Scaffold plan exceeds byte limits')
1099
+ }
1100
+ }
1101
+
1102
+ return {
1103
+ version: 1,
1104
+ root,
1105
+ appRoot,
1106
+ id,
1107
+ files: [...files.values()],
1108
+ directories: [...directories].map(([path, mode]) => ({ path, mode })),
1109
+ inputs: [...inputs.values()],
1110
+ report,
1111
+ }
1112
+ }
1113
+
1114
+ /** Apply the same read-only plan used by native CLI orchestration. */
537
1115
  export function applyTarget(appRoot, id) {
538
- const manifestPath = join(appRoot, 'package.json')
539
- const raw = readFileSync(manifestPath, 'utf8')
540
- const manifest: Record<string, any> = JSON.parse(raw)
541
- const tpl = templateManifest()
542
- const report: Record<string, any> = {
543
- enabled: [],
544
- already: [],
545
- copied: [],
546
- skipped: [],
547
- scriptsAdded: [],
548
- scriptsSkipped: [],
549
- depsAdded: [],
550
- }
551
-
552
- let touched = false
553
- for (const tid of resolveTargets([id])) {
554
- if (targetEnabled(appRoot, tid)) {
555
- report.already.push(tid)
556
- continue
557
- }
558
-
559
- report.enabled.push(tid)
560
- const t = targets[tid]
561
- for (const rel of t.files) {
562
- copyMissing(rel, appRoot, report)
563
- }
564
-
565
- for (const [section, key] of [
566
- ['dependencies', 'deps'],
567
- ['devDependencies', 'devDeps'],
568
- ]) {
569
- for (const name of t[key] ?? []) {
570
- manifest[section] ??= {}
571
- if (manifest[section][name] === undefined) {
572
- manifest[section][name] = tpl[section][name]
573
- report.depsAdded.push(name)
574
- }
575
- }
576
- }
577
-
578
- manifest.scripts ??= {}
579
- for (const name of t.scripts ?? []) {
580
- if (manifest.scripts[name] === undefined) {
581
- manifest.scripts[name] = tpl.scripts[name]
582
- report.scriptsAdded.push(name)
583
- } else if (manifest.scripts[name] !== tpl.scripts[name]) {
584
- report.scriptsSkipped.push(name)
585
- }
586
- }
587
-
588
- if (t.typecheck) {
589
- const current = manifest.scripts.typecheck ?? ''
590
- if (!current.includes(t.typecheck)) {
591
- manifest.scripts.typecheck = current ? `${current} && ${t.typecheck}` : t.typecheck
592
- report.scriptsAdded.push('typecheck')
593
- }
594
- }
595
-
596
- if (tid === 'native-shared') {
597
- if (manifest.main === undefined) {
598
- manifest.main = tpl.main
599
- }
600
-
601
- // Native sources join the app's single typecheck program — pull the
602
- // ambient declaration entry into the roots and un-exclude the
603
- // NativeScript entry that a web-only scaffold skips.
604
- report.tsconfigUpdated = enableNativeInTsconfig(appRoot)
605
- }
606
-
607
- touched = true
608
- }
609
-
610
- // Newly enabled targets may carry patch entries the scaffolded
611
- // pnpm-workspace.yaml never had — without them the next install misses the
612
- // framework patches. enabled+already covers the yaml-missing case, where
613
- // the file is regenerated for the whole enabled set.
614
- if (ensurePatchEntries(appRoot, [...report.enabled, ...report.already])) {
615
- report.patchesAdded = true
616
- }
617
- ensureCompatibilityCatalog(appRoot, manifest)
618
-
619
- if (touched) {
620
- // Match the file's existing indent so diffs stay minimal.
621
- const indent = raw.match(/\n(\s+)"/)?.[1] ?? '\t'
622
- writeFileSync(manifestPath, JSON.stringify(manifest, null, indent) + '\n')
623
- }
624
- return report
1116
+ const plan = planTarget(appRoot, id)
1117
+
1118
+ for (const input of plan.inputs) {
1119
+ let info
1120
+
1121
+ try {
1122
+ info = lstatSync(input.path)
1123
+ } catch (error) {
1124
+ if (error.code !== 'ENOENT') {
1125
+ throw error
1126
+ }
1127
+ }
1128
+
1129
+ const kind = !info
1130
+ ? 'missing'
1131
+ : info.isFile()
1132
+ ? 'file'
1133
+ : info.isDirectory()
1134
+ ? 'directory'
1135
+ : 'alias'
1136
+
1137
+ if (
1138
+ kind !== input.kind ||
1139
+ (kind === 'file' &&
1140
+ createHash('sha256').update(readFileSync(input.path)).digest('hex') !== input.sha256)
1141
+ ) {
1142
+ throw new Error(`Scaffold input changed; retry: ${input.path}`)
1143
+ }
1144
+ }
1145
+
1146
+ for (const entry of plan.directories) {
1147
+ mkdirSync(entry.path, { recursive: true, mode: entry.mode })
1148
+ }
1149
+
1150
+ for (const entry of plan.files) {
1151
+ writeFileSync(entry.path, Buffer.from(entry.content, 'base64'), { mode: entry.mode })
1152
+ }
1153
+
1154
+ return plan.report
625
1155
  }