@nativue/core 0.13.0 → 0.14.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 (57) hide show
  1. package/AGENTS.md +31 -7
  2. package/README.md +1 -0
  3. package/android/build.gradle.kts +4 -0
  4. package/android/nativue.settings.gradle.kts +2 -0
  5. package/android/src/main/java/dev/nativue/Bridge.kt +66 -7
  6. package/android/src/main/java/dev/nativue/NativueActivity.kt +12 -5
  7. package/android/src/main/java/dev/nativue/Permissions.kt +107 -0
  8. package/android/src/main/java/dev/nativue/Plugins.kt +98 -15
  9. package/cli/android-project.mjs +377 -0
  10. package/cli/app-config.mjs +515 -0
  11. package/cli/config.d.mts +162 -3
  12. package/cli/ios-project.mjs +652 -0
  13. package/cli/link.mjs +66 -71
  14. package/cli/nativue.mjs +39 -5
  15. package/cli/plugins.mjs +236 -0
  16. package/cli/prebuild.mjs +458 -0
  17. package/cli/run.mjs +2 -2
  18. package/cli/serialize.mjs +168 -0
  19. package/ios/AppLifecycle.swift +165 -0
  20. package/ios/Bridge.swift +53 -4
  21. package/ios/NativueView.swift +5 -1
  22. package/ios/Permissions.swift +19 -0
  23. package/ios/Plugins.swift +24 -0
  24. package/package.json +3 -2
  25. package/src/globals.ts +7 -1
  26. package/src/native-events.ts +99 -0
  27. package/src/native-functions.ts +16 -2
  28. package/src/permissions.ts +57 -0
  29. package/src/renderer.ts +5 -1
  30. package/src/router.ts +2 -1
  31. package/src/types.ts +3 -0
  32. package/template/android/app/src/debug/AndroidManifest.xml +4 -0
  33. package/template/android/app/src/main/java/MainActivity.kt +5 -0
  34. package/template/android/app/src/main/res/drawable-night-xxxhdpi/splash_logo.png +0 -0
  35. package/template/android/app/src/main/res/drawable-xxxhdpi/splash_logo.png +0 -0
  36. package/template/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +6 -0
  37. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  38. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  39. package/template/android/app/src/main/res/values/colors.xml +4 -0
  40. package/template/android/app/src/main/res/values/styles.xml +15 -0
  41. package/template/android/app/src/main/res/values-night/styles.xml +5 -0
  42. package/template/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  43. package/template/android/gradle/wrapper/gradle-wrapper.properties +9 -0
  44. package/template/android/gradlew +248 -0
  45. package/template/android/gradlew.bat +112 -0
  46. package/template/ios/App/App.swift +18 -0
  47. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json +1 -0
  48. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/icon.png +0 -0
  49. package/template/ios/App/Assets.xcassets/Contents.json +1 -0
  50. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/Contents.json +11 -0
  51. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@1x.png +0 -0
  52. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@2x.png +0 -0
  53. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@3x.png +0 -0
  54. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@1x.png +0 -0
  55. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@2x.png +0 -0
  56. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@3x.png +0 -0
  57. package/template/ios/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +15 -0
@@ -0,0 +1,458 @@
1
+ // `nativue prebuild [ios | android] [--force]`, also run by dev, build and run: generates the app's
2
+ // ios/ and android/ from the template next to this file, nativue.config.ts and the app's packages.
3
+ // Every run starts from the template, so the projects depend only on those inputs; it writes only
4
+ // what changed, keeping Xcode's and Gradle's incremental builds.
5
+ // Each folder's .nativue/generated.json records a hash of every file it wrote. A file that no longer
6
+ // matches was edited by hand, and one it never wrote was added by hand: either stops prebuild before
7
+ // it writes anything, since the next run would lose that work. --force overwrites and deletes them.
8
+ // With `prebuild: false` in the config, the app keeps ios/ and android/ by hand: only the packages'
9
+ // native code is linked (ios/NativuePlugins), as before prebuild existed.
10
+ import { spawnSync } from 'node:child_process'
11
+ import { createHash } from 'node:crypto'
12
+ import {
13
+ existsSync,
14
+ lstatSync,
15
+ mkdirSync,
16
+ mkdtempSync,
17
+ readdirSync,
18
+ readFileSync,
19
+ readlinkSync,
20
+ rmdirSync,
21
+ rmSync,
22
+ symlinkSync,
23
+ writeFileSync,
24
+ } from 'node:fs'
25
+ import { tmpdir } from 'node:os'
26
+ import { dirname, join, relative } from 'node:path'
27
+ import { androidProjectFiles, nativueManifest } from './android-project.mjs'
28
+ import { appConfig, validateConfig } from './app-config.mjs'
29
+ import { iosProjectFiles } from './ios-project.mjs'
30
+ import { iosPluginFiles, toPosixPath } from './link.mjs'
31
+ import { checkManualProjects } from './plugins.mjs'
32
+
33
+ export const PLATFORMS = ['ios', 'android']
34
+
35
+ const RECORD_PATH = '.nativue/generated.json'
36
+ const MIGRATION_GUIDE_URL =
37
+ 'https://github.com/nativue/nativue/blob/main/docs/migrating-to-prebuild.md'
38
+ const TEMPLATE_TEXT_FILE = /\.(kts|kt|xml|swift|json)$/
39
+ // What Xcode, Gradle, Android Studio and the bundler write next to the generated files: never
40
+ // checked, deleted or walked into.
41
+ const IGNORED_DIRECTORIES = new Set([
42
+ 'build',
43
+ '.build',
44
+ '.gradle',
45
+ '.kotlin',
46
+ '.cxx',
47
+ '.idea',
48
+ '.swiftpm',
49
+ '.nativue',
50
+ 'xcuserdata',
51
+ ])
52
+ const IGNORED_FILES = new Set(['.DS_Store', 'local.properties', 'main.bundle.js'])
53
+ const IGNORED_PATHS = new Set(['App.xcodeproj/project.xcworkspace'])
54
+ // Written only when missing: Xcode keeps the resolved Swift package versions up to date afterwards.
55
+ const SEEDED_PATHS = new Set([
56
+ 'App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved',
57
+ ])
58
+
59
+ function isIgnored(path) {
60
+ const name = path.split('/').pop()
61
+
62
+ return (
63
+ IGNORED_DIRECTORIES.has(name) ||
64
+ IGNORED_FILES.has(name) ||
65
+ IGNORED_PATHS.has(path) ||
66
+ name.endsWith('.iml')
67
+ )
68
+ }
69
+
70
+ function hash(data) {
71
+ return createHash('sha256').update(data).digest('hex')
72
+ }
73
+
74
+ function entryHash(entry) {
75
+ return entry.symlink === undefined ? hash(entry.content) : hash(`symlink:${entry.symlink}`)
76
+ }
77
+
78
+ /** Files and links under directory, by path relative to it, skipping what tools own. */
79
+ function filesIn(directory, base = directory) {
80
+ if (!existsSync(directory)) return []
81
+
82
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
83
+ const path = join(directory, entry.name)
84
+ const relativePath = toPosixPath(relative(base, path))
85
+
86
+ if (isIgnored(relativePath)) return []
87
+
88
+ return entry.isDirectory() ? filesIn(path, base) : [relativePath]
89
+ })
90
+ }
91
+
92
+ function readEntry(path) {
93
+ if (lstatSync(path).isSymbolicLink()) return { symlink: readlinkSync(path) }
94
+
95
+ return { content: readFileSync(path) }
96
+ }
97
+
98
+ function readRecord(platformDirectory) {
99
+ const path = join(platformDirectory, RECORD_PATH)
100
+
101
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null
102
+ }
103
+
104
+ function writeRecord(platformDirectory, record) {
105
+ const path = join(platformDirectory, RECORD_PATH)
106
+
107
+ mkdirSync(dirname(path), { recursive: true })
108
+ writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`)
109
+ }
110
+
111
+ function fillPlaceholders(text, values) {
112
+ return Object.entries(values).reduce(
113
+ (filled, [placeholder, value]) => filled.replaceAll(placeholder, value),
114
+ text,
115
+ )
116
+ }
117
+
118
+ /** All of the template, including the seeded files under the paths isIgnored skips in the app. */
119
+ function templatePaths(templateDirectory) {
120
+ return readdirSync(templateDirectory, { recursive: true, withFileTypes: true })
121
+ .filter((entry) => entry.isFile() && entry.name !== '.DS_Store')
122
+ .map((entry) => toPosixPath(relative(templateDirectory, join(entry.parentPath, entry.name))))
123
+ }
124
+
125
+ function templateFiles(templateDirectory, placeholders) {
126
+ return Object.fromEntries(
127
+ templatePaths(templateDirectory).map((path) => {
128
+ const source = join(templateDirectory, path)
129
+ const content = readFileSync(source)
130
+ const executable = (lstatSync(source).mode & 0o111) !== 0
131
+ const filled = TEMPLATE_TEXT_FILE.test(path)
132
+ ? fillPlaceholders(content.toString('utf8'), placeholders)
133
+ : content
134
+
135
+ return [path, { content: filled, executable }]
136
+ }),
137
+ )
138
+ }
139
+
140
+ function asEntries(files) {
141
+ return Object.fromEntries(
142
+ Object.entries(files).map(([path, file]) => [
143
+ path,
144
+ typeof file === 'string' ? { content: file } : file,
145
+ ]),
146
+ )
147
+ }
148
+
149
+ /** Every file of platform's folder, by path relative to it: { content, executable } or { symlink }. */
150
+ function generatedFiles(platform, { app, plugins, appDirectory, coreDirectory }) {
151
+ const platformDirectory = join(appDirectory, platform)
152
+ const placeholders = {
153
+ __ANDROID_PACKAGE__: app.android.package,
154
+ __CORE_PATH__: toPosixPath(relative(platformDirectory, coreDirectory)),
155
+ __SPLASH_BACKGROUND__: app.splash.backgroundColor,
156
+ __DARK_SPLASH_BACKGROUND__: app.splash.darkBackgroundColor,
157
+ __ICON_BACKGROUND__: app.iconBackgroundColor,
158
+ }
159
+ const template = templateFiles(join(coreDirectory, 'template', platform), placeholders)
160
+ const generated =
161
+ platform === 'ios'
162
+ ? {
163
+ ...iosProjectFiles(app, appDirectory, plugins),
164
+ ...iosPluginFiles(appDirectory, coreDirectory),
165
+ }
166
+ : androidProjectFiles(app, { appDirectory, corePath: placeholders.__CORE_PATH__, plugins })
167
+ const files = { ...template, ...generated }
168
+
169
+ // A null replaces a template file with nothing.
170
+ return asEntries(Object.fromEntries(Object.entries(files).filter(([, file]) => file !== null)))
171
+ }
172
+
173
+ /** What the folder holds that prebuild didn't write, or wrote and was changed since. */
174
+ function findManualChanges(existingPaths, record, platformDirectory) {
175
+ if (existingPaths.length > 0 && !record) return { notGenerated: true, edited: [], added: [] }
176
+
177
+ const recordedHashes = { ...record?.pending, ...record?.files }
178
+ const isRecorded = (path) => path in recordedHashes
179
+ const matchesRecord = (path) => {
180
+ const current = entryHash(readEntry(join(platformDirectory, path)))
181
+
182
+ return current === record.files?.[path] || current === record.pending?.[path]
183
+ }
184
+ const edited = existingPaths.filter(
185
+ (path) => isRecorded(path) && !SEEDED_PATHS.has(path) && !matchesRecord(path),
186
+ )
187
+ const added = existingPaths.filter((path) => !isRecorded(path) && !SEEDED_PATHS.has(path))
188
+
189
+ return { notGenerated: false, edited, added }
190
+ }
191
+
192
+ function hasManualChanges({ notGenerated, edited, added }) {
193
+ return notGenerated || edited.length > 0 || added.length > 0
194
+ }
195
+
196
+ /** git's diff of the file on disk (label) against what prebuild generates, or nothing without git. */
197
+ function diffAgainstGenerated(path, label, entry) {
198
+ if (entry?.content === undefined) return ''
199
+
200
+ const directory = mkdtempSync(join(tmpdir(), 'nativue-prebuild-'))
201
+ const generatedPath = join(directory, 'generated')
202
+
203
+ writeFileSync(generatedPath, entry.content)
204
+
205
+ const { stdout } = spawnSync(
206
+ 'git',
207
+ ['diff', '--no-index', '--no-prefix', '--color=always', '--', generatedPath, path],
208
+ { encoding: 'utf8' },
209
+ )
210
+ rmSync(directory, { recursive: true, force: true })
211
+
212
+ // Without a prefix, git prints absolute paths without their leading slash.
213
+ return (stdout ?? '')
214
+ .replaceAll(generatedPath.slice(1), `${label} (generated)`)
215
+ .replaceAll(path.slice(1), `${label} (yours)`)
216
+ }
217
+
218
+ // Where a hand edit of each generated file belongs instead.
219
+ const DESTINATIONS = [
220
+ [/^Info\.plist$/, 'ios.infoPlist in nativue.config.ts'],
221
+ [/^App\.entitlements$/, 'ios.entitlements in nativue.config.ts'],
222
+ [
223
+ /^App\.xcodeproj\//,
224
+ 'nativue.config.ts: version, buildNumber, ios.appleTeamId, ios.entitlements',
225
+ ],
226
+ [/^App\/Assets\.xcassets\//, 'icon or splash in nativue.config.ts'],
227
+ [
228
+ /^app\/src\/main\/AndroidManifest\.xml$/,
229
+ 'android.permissions, or a plugin with an android.manifest mod (docs/packages.md)',
230
+ ],
231
+ [
232
+ /^app\/build\.gradle\.kts$/,
233
+ 'nativue.config.ts: version, buildNumber, android.signing, android.gradle',
234
+ ],
235
+ [
236
+ /^(build\.gradle\.kts|settings\.gradle\.kts|gradle\.properties)$/,
237
+ 'android.gradle in nativue.config.ts',
238
+ ],
239
+ [/^app\/src\/main\/res\/values\/strings\.xml$/, 'name in nativue.config.ts'],
240
+ [
241
+ /^app\/src\/main\/res\/values(-night)?\/(styles|colors)\.xml$/,
242
+ 'splash or android.adaptiveIcon.backgroundColor in nativue.config.ts',
243
+ ],
244
+ [
245
+ /^app\/src\/main\/res\/(mipmap|drawable)/,
246
+ 'icon, android.adaptiveIcon or splash in nativue.config.ts',
247
+ ],
248
+ [
249
+ /^(Extensions|ExtensionSupport)\//,
250
+ "an extension target: native/extensions/<name>/, or a plugin's ios.targets mod",
251
+ ],
252
+ [/\.(swift|kt|java)$/, 'a module in native/<name>/'],
253
+ [
254
+ /^(App\/Resources\/|app\/src\/main\/(assets\/|res\/(raw|font|xml|drawable)\/))/,
255
+ 'resources in nativue.config.ts',
256
+ ],
257
+ ]
258
+
259
+ function destination(path) {
260
+ const match = DESTINATIONS.find(([pattern]) => pattern.test(path))
261
+
262
+ return match ? ` → ${match[1]}` : ''
263
+ }
264
+
265
+ /** For a team picked in Xcode, the config field that keeps it. */
266
+ function teamHint(path, platformDirectory) {
267
+ if (!path.endsWith('project.pbxproj')) return ''
268
+
269
+ const team = readFileSync(join(platformDirectory, path), 'utf8').match(
270
+ /DEVELOPMENT_TEAM = "?(\w+)"?;/,
271
+ )?.[1]
272
+
273
+ return team ? `\nThe signing team goes in nativue.config.ts: ios: { appleTeamId: '${team}' }` : ''
274
+ }
275
+
276
+ function notGeneratedMessage(platforms) {
277
+ const folders = platforms.map((platform) => `${platform}/`).join(' and ')
278
+ const verb = platforms.length > 1 ? "weren't" : "wasn't"
279
+
280
+ return `${folders} ${verb} generated by nativue: from before nativue generated the native projects, so nativue left them alone.
281
+ Move its settings into nativue.config.ts and let nativue generate it: ${MIGRATION_GUIDE_URL}
282
+ Or keep it by hand, with this nativue.config.ts:
283
+
284
+ import { defineConfig } from '@nativue/core/config'
285
+
286
+ export default defineConfig({ prebuild: false })`
287
+ }
288
+
289
+ function manualChangesMessage(platform, changes, files, appDirectory) {
290
+ const platformDirectory = join(appDirectory, platform)
291
+
292
+ const diffs = changes.edited.map(
293
+ (path) =>
294
+ diffAgainstGenerated(join(platformDirectory, path), `${platform}/${path}`, files[path]) +
295
+ teamHint(path, platformDirectory),
296
+ )
297
+ const lines = [
298
+ ...changes.edited.map((path) => ` changed: ${platform}/${path}${destination(path)}`),
299
+ ...changes.added.map((path) => ` added: ${platform}/${path}${destination(path)}`),
300
+ ]
301
+
302
+ return `${platform}/ is generated by nativue, but was changed by hand: the next prebuild would lose this.
303
+ ${lines.join('\n')}
304
+ ${diffs.filter(Boolean).join('\n')}
305
+ Move these changes into nativue.config.ts or native/, or keep ios/ and android/ by hand with
306
+ prebuild: false in nativue.config.ts (${MIGRATION_GUIDE_URL}).
307
+ To discard them instead: npx nativue prebuild --force`
308
+ }
309
+
310
+ function writeEntry(path, entry) {
311
+ mkdirSync(dirname(path), { recursive: true })
312
+ rmSync(path, { recursive: true, force: true })
313
+
314
+ if (entry.symlink !== undefined) {
315
+ symlinkSync(entry.symlink, path)
316
+ return
317
+ }
318
+
319
+ writeFileSync(path, entry.content, { mode: entry.executable ? 0o755 : 0o644 })
320
+ }
321
+
322
+ /** Removes the folders that deleting path left empty, up to the platform folder. */
323
+ function removeEmptyParents(path, platformDirectory) {
324
+ for (
325
+ let directory = dirname(path);
326
+ directory !== platformDirectory;
327
+ directory = dirname(directory)
328
+ ) {
329
+ if (readdirSync(directory).length > 0) return
330
+
331
+ rmdirSync(directory)
332
+ }
333
+ }
334
+
335
+ /** Writes what changed and deletes what prebuild no longer generates; returns the paths it touched. */
336
+ function writePlatform(platformDirectory, files, existingPaths, record, version) {
337
+ const hashes = Object.fromEntries(
338
+ Object.entries(files)
339
+ .filter(([path]) => !SEEDED_PATHS.has(path))
340
+ .map(([path, entry]) => [path, entryHash(entry)]),
341
+ )
342
+ const existingHashes = Object.fromEntries(
343
+ existingPaths.map((path) => [path, entryHash(readEntry(join(platformDirectory, path)))]),
344
+ )
345
+ const isUpToDate = (path) =>
346
+ SEEDED_PATHS.has(path)
347
+ ? existsSync(join(platformDirectory, path))
348
+ : existingHashes[path] === hashes[path]
349
+ const changedPaths = Object.keys(files).filter((path) => !isUpToDate(path))
350
+ const removedPaths = existingPaths.filter((path) => !(path in files))
351
+
352
+ if (changedPaths.length === 0 && removedPaths.length === 0 && record?.version === version) {
353
+ return []
354
+ }
355
+
356
+ // Saved first, with both sets of hashes: a prebuild that stops halfway isn't taken for manual edits.
357
+ writeRecord(platformDirectory, { version, files: record?.files ?? {}, pending: hashes })
358
+ // Removed first: a file may take the place of a folder that held removed files.
359
+ removedPaths.forEach((path) => {
360
+ rmSync(join(platformDirectory, path), { force: true })
361
+ removeEmptyParents(join(platformDirectory, path), platformDirectory)
362
+ })
363
+ changedPaths.forEach((path) => writeEntry(join(platformDirectory, path), files[path]))
364
+ writeRecord(platformDirectory, { version, files: hashes })
365
+
366
+ return [...changedPaths, ...removedPaths]
367
+ }
368
+
369
+ /**
370
+ * Generates platforms' folders in appDirectory. Throws, before writing anything, when one was
371
+ * changed by hand, unless force. Returns the paths written or deleted, relative to appDirectory.
372
+ */
373
+ export function prebuild({
374
+ config,
375
+ plugins = [],
376
+ appDirectory,
377
+ coreDirectory,
378
+ platforms = PLATFORMS,
379
+ force = false,
380
+ }) {
381
+ // An app from before prebuild has no config for it yet: say why first, not which fields are missing.
382
+ const handKept = platforms.filter((platform) => {
383
+ const platformDirectory = join(appDirectory, platform)
384
+
385
+ return filesIn(platformDirectory).length > 0 && !readRecord(platformDirectory)
386
+ })
387
+
388
+ if (handKept.length > 0 && !force) throw new Error(notGeneratedMessage(handKept))
389
+
390
+ validateConfig(config, appDirectory, plugins)
391
+
392
+ const app = appConfig(config)
393
+ const { version } = JSON.parse(readFileSync(join(coreDirectory, 'package.json'), 'utf8'))
394
+ const plans = platforms.map((platform) => {
395
+ const platformDirectory = join(appDirectory, platform)
396
+ const files = generatedFiles(platform, { app, plugins, appDirectory, coreDirectory })
397
+ const existingPaths = filesIn(platformDirectory)
398
+ const record = readRecord(platformDirectory)
399
+ const changes = findManualChanges(existingPaths, record, platformDirectory)
400
+
401
+ return { platform, platformDirectory, files, existingPaths, record, changes }
402
+ })
403
+
404
+ const blocked = plans.filter((plan) => hasManualChanges(plan.changes))
405
+ if (blocked.length > 0 && !force) {
406
+ const messages = blocked.map(({ platform, changes, files }) =>
407
+ manualChangesMessage(platform, changes, files, appDirectory),
408
+ )
409
+ throw new Error(messages.join('\n\n'))
410
+ }
411
+
412
+ return plans.flatMap(({ platform, platformDirectory, files, existingPaths, record }) =>
413
+ writePlatform(platformDirectory, files, existingPaths, record, version).map(
414
+ (path) => `${platform}/${path}`,
415
+ ),
416
+ )
417
+ }
418
+
419
+ /**
420
+ * With `prebuild: false`: only ios/NativuePlugins, the packages' native code, written into the app's
421
+ * own ios/ when it has one, as before prebuild existed.
422
+ */
423
+ export function linkNativePackages({
424
+ config,
425
+ plugins = [],
426
+ appDirectory,
427
+ coreDirectory,
428
+ platforms = PLATFORMS,
429
+ }) {
430
+ validateConfig(config, appDirectory)
431
+ checkManualProjects(plugins, {
432
+ config,
433
+ appDirectory,
434
+ platforms,
435
+ manifest: nativueManifest({ schemes: [] }),
436
+ })
437
+
438
+ const iosDirectory = join(appDirectory, 'ios')
439
+ if (!existsSync(iosDirectory)) return []
440
+
441
+ const files = asEntries(iosPluginFiles(appDirectory, coreDirectory))
442
+ const isCurrent = (path) =>
443
+ lstatSync(join(iosDirectory, path), { throwIfNoEntry: false }) &&
444
+ entryHash(readEntry(join(iosDirectory, path))) === entryHash(files[path])
445
+ const changedPaths = Object.keys(files).filter((path) => !isCurrent(path))
446
+ // Links of packages the app no longer has.
447
+ const modulePaths = filesIn(join(iosDirectory, 'NativuePlugins/Sources')).map(
448
+ (path) => `NativuePlugins/Sources/${path.split('/')[0]}`,
449
+ )
450
+ const stalePaths = [...new Set(modulePaths)].filter(
451
+ (path) => !Object.keys(files).some((file) => file.startsWith(path)),
452
+ )
453
+
454
+ changedPaths.forEach((path) => writeEntry(join(iosDirectory, path), files[path]))
455
+ stalePaths.forEach((path) => rmSync(join(iosDirectory, path), { recursive: true, force: true }))
456
+
457
+ return [...changedPaths, ...stalePaths].map((path) => `ios/${path}`)
458
+ }
package/cli/run.mjs CHANGED
@@ -150,7 +150,7 @@ function signingSettings() {
150
150
  ? 'No Apple Development certificate on this Mac: sign in to your Apple account in Xcode > Settings > Accounts,'
151
151
  : 'Your certificates belong to several teams:'
152
152
  throw new Error(
153
- `${reason} then pick your team in ios/App.xcodeproj, under Signing & Capabilities.`,
153
+ `${reason} then set your team id in nativue.config.ts: ios: { appleTeamId: 'ABCDE12345' } (it's under Signing & Capabilities in Xcode). With prebuild: false, pick the team in ios/App.xcodeproj instead.`,
154
154
  )
155
155
  }
156
156
 
@@ -184,7 +184,7 @@ function buildIOSApp(destination, isSimulator) {
184
184
  if (isSimulator) throw error
185
185
 
186
186
  throw new Error(
187
- 'The build for the phone failed. If it is about signing, open ios/App.xcodeproj in Xcode and check Signing & Capabilities.',
187
+ 'The build for the phone failed. If it is about signing, check ios.appleTeamId in nativue.config.ts, and your account in Xcode > Settings > Accounts.',
188
188
  )
189
189
  }
190
190
  }
@@ -0,0 +1,168 @@
1
+ // Writers for the native files prebuild generates from plain objects: plists, the Xcode project
2
+ // (an OpenStep plist) and Android XML. Only writers: nativue builds these files, it never reads them.
3
+
4
+ const PLIST_HEADER = `<?xml version="1.0" encoding="UTF-8"?>
5
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
6
+ <plist version="1.0">
7
+ `
8
+
9
+ export function escapeXml(text) {
10
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
11
+ }
12
+
13
+ function escapeXmlAttribute(text) {
14
+ return escapeXml(text).replaceAll('"', '&quot;')
15
+ }
16
+
17
+ function plistValue(value, depth) {
18
+ const indent = '\t'.repeat(depth)
19
+
20
+ if (typeof value === 'boolean') return `${indent}<${value}/>`
21
+ if (typeof value === 'number') {
22
+ const type = Number.isInteger(value) ? 'integer' : 'real'
23
+
24
+ return `${indent}<${type}>${value}</${type}>`
25
+ }
26
+ if (typeof value === 'string') return `${indent}<string>${escapeXml(value)}</string>`
27
+ if (Array.isArray(value)) {
28
+ if (value.length === 0) return `${indent}<array/>`
29
+
30
+ const items = value.map((item) => plistValue(item, depth + 1))
31
+
32
+ return [`${indent}<array>`, ...items, `${indent}</array>`].join('\n')
33
+ }
34
+
35
+ const keys = Object.keys(value)
36
+ .filter((key) => value[key] !== undefined)
37
+ .sort()
38
+ if (keys.length === 0) return `${indent}<dict/>`
39
+
40
+ const entries = keys.flatMap((key) => [
41
+ `${indent}\t<key>${escapeXml(key)}</key>`,
42
+ plistValue(value[key], depth + 1),
43
+ ])
44
+
45
+ return [`${indent}<dict>`, ...entries, `${indent}</dict>`].join('\n')
46
+ }
47
+
48
+ /** An XML property list (Info.plist, entitlements). Keys are sorted, as Xcode writes them. */
49
+ export function plist(dictionary) {
50
+ return `${PLIST_HEADER}${plistValue(dictionary, 0)}\n</plist>\n`
51
+ }
52
+
53
+ // Strings the OpenStep format leaves unquoted; anything else is quoted and escaped.
54
+ const OPENSTEP_BARE_STRING = /^[A-Za-z0-9_$./]+$/
55
+ // Objects Xcode writes on a single line.
56
+ const SINGLE_LINE_ISAS = new Set(['PBXBuildFile', 'PBXFileReference'])
57
+
58
+ function openStepString(text) {
59
+ if (OPENSTEP_BARE_STRING.test(text)) return text
60
+
61
+ const escaped = text.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n')
62
+
63
+ return `"${escaped}"`
64
+ }
65
+
66
+ /** isa first, then the rest in alphabetical order: Xcode's own order, so saving in Xcode changes nothing. */
67
+ function sortedKeys(dictionary) {
68
+ const keys = Object.keys(dictionary).filter(
69
+ (key) => key !== 'isa' && dictionary[key] !== undefined,
70
+ )
71
+
72
+ keys.sort()
73
+
74
+ return 'isa' in dictionary ? ['isa', ...keys] : keys
75
+ }
76
+
77
+ /**
78
+ * The Xcode project file, from `{ objectVersion, objects, rootObject, comments }`: objects by id,
79
+ * and the comment Xcode writes after each id that has one ("App", "Project object"...).
80
+ */
81
+ export function pbxproj({ objectVersion, objects, rootObject, comments }) {
82
+ const reference = (id) => (comments[id] ? `${id} /* ${comments[id]} */` : id)
83
+ const value = (item) => (typeof item === 'string' && item in objects ? reference(item) : item)
84
+
85
+ function render(item, depth) {
86
+ const indent = '\t'.repeat(depth)
87
+
88
+ if (Array.isArray(item)) {
89
+ const lines = item.map((element) => `${indent}\t${render(element, depth + 1)},\n`)
90
+
91
+ return `(\n${lines.join('')}${indent})`
92
+ }
93
+ if (typeof item === 'object') {
94
+ const lines = sortedKeys(item).map(
95
+ (key) => `${indent}\t${openStepString(key)} = ${render(item[key], depth + 1)};\n`,
96
+ )
97
+
98
+ return `{\n${lines.join('')}${indent}}`
99
+ }
100
+
101
+ return value(item) === item ? openStepString(String(item)) : value(item)
102
+ }
103
+
104
+ function renderObject(id, object) {
105
+ if (!SINGLE_LINE_ISAS.has(object.isa)) return `\t\t${reference(id)} = ${render(object, 2)};\n`
106
+
107
+ const entries = sortedKeys(object).map((key) => `${key} = ${render(object[key], 3)}; `)
108
+
109
+ return `\t\t${reference(id)} = {${entries.join('')}};\n`
110
+ }
111
+
112
+ const isas = [...new Set(Object.values(objects).map((object) => object.isa))].sort()
113
+ const sections = isas.map((isa) => {
114
+ const ids = Object.keys(objects)
115
+ .filter((id) => objects[id].isa === isa)
116
+ .sort()
117
+
118
+ return `/* Begin ${isa} section */\n${ids.map((id) => renderObject(id, objects[id])).join('')}/* End ${isa} section */\n`
119
+ })
120
+
121
+ return `// !$*UTF8*$!
122
+ {
123
+ \tarchiveVersion = 1;
124
+ \tclasses = {
125
+ \t};
126
+ \tobjectVersion = ${objectVersion};
127
+ \tobjects = {
128
+
129
+ ${sections.join('\n')}\t};
130
+ \trootObject = ${reference(rootObject)};
131
+ }
132
+ `
133
+ }
134
+
135
+ /**
136
+ * Android XML from `{ tag, attributes, children }`. Attribute names keep their prefix
137
+ * ('android:name', 'tools:node'). One attribute stays on the element's line; more go one per line.
138
+ */
139
+ export function xml(element) {
140
+ return `<?xml version="1.0" encoding="utf-8"?>\n${xmlElement(element, 0)}\n`
141
+ }
142
+
143
+ function xmlElement({ tag, attributes = {}, children = [], text }, depth) {
144
+ const indent = ' '.repeat(depth)
145
+ const pairs = Object.entries(attributes).map(
146
+ ([name, value]) => `${name}="${escapeXmlAttribute(value)}"`,
147
+ )
148
+ const opening =
149
+ pairs.length <= 1
150
+ ? `${indent}<${[tag, ...pairs].join(' ')}`
151
+ : `${indent}<${tag}\n${pairs.map((pair) => `${indent} ${pair}`).join('\n')}`
152
+
153
+ if (text !== undefined) return `${opening}>${escapeXml(text)}</${tag}>`
154
+ if (children.length === 0) return `${opening} />`
155
+
156
+ const content = children.map((child) => xmlElement(child, depth + 1)).join('\n')
157
+
158
+ return `${opening}>\n${content}\n${indent}</${tag}>`
159
+ }
160
+
161
+ /** A string resource's text: Android reads quotes, backslashes and a leading @ or ? specially. */
162
+ export function androidString(text) {
163
+ return text
164
+ .replaceAll('\\', '\\\\')
165
+ .replaceAll("'", "\\'")
166
+ .replaceAll('"', '\\"')
167
+ .replace(/^([@?])/, '\\$1')
168
+ }