lecodes-cli 2.4.2 → 2.4.3

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.
@@ -11,16 +11,17 @@ import {
11
11
  type AppConfig, ANDROID_SDK_VARIANTS, type AndroidSdkVariant, VERSION_RE, androidSdkArtifact, androidVariantEngines,
12
12
  childEnv, cmpVersion, ensureShellIgnored, fetchLatestSdkVersion,
13
13
  projectRoot, readAppConfigAt, readJson, resolvePlugin, resolveSdkVersion, resolveVariant, runTool, sdkSatisfies, slugify,
14
- writeJson, type LockEntry, resolveUpdateUrl, urlSchemeOf,
14
+ writeJson, type LockEntry, resolveUpdateUrl, urlSchemeOf, appLinksOf, appLinksSiteNote, type AppLink,
15
15
  } from "./shared"
16
16
  import { loadIconMaster, restampManifestIcon, writeAndroidIcons } from "./icon"
17
+ import { androidSplashThemeHint, loadSplashMaster, writeAndroidSplash } from "./splash"
17
18
  import {
18
19
  ANDROID_GITIGNORE, ANDROID_README, APP_PROGUARD_RULES, COLORS_XML, GRADLE_PROPERTIES, GRADLE_VERSION,
19
20
  GRADLE_PLUGIN_VERSIONS, IC_LAUNCHER_XML, aarWrapperBuildGradle, appBuildGradleTemplate,
20
21
  appManifestTemplate, appViewModelTemplate, gradleWrapperProperties, mainActivityTemplate,
21
22
  pluginBuildGradleTemplate, rootBuildGradleTemplate, runtimeBuildGradleTemplate,
22
- runtimeKotlinTemplate, settingsGradleTemplate, stringsXmlTemplate, themesXmlTemplate,
23
- type AndroidRuntimePlugin, type AndroidShellIdentity, runtimeManifestTemplate, urlSchemeFilter,
23
+ runtimeKotlinTemplate, runtimeThemeTemplate, settingsGradleTemplate, stringsXmlTemplate, themesXmlTemplate,
24
+ type AndroidRuntimePlugin, type AndroidShellIdentity, runtimeManifestTemplate, urlSchemeFilter, appLinksFilter,
24
25
  } from "./templates/android"
25
26
  import { GRADLEW_BAT, GRADLEW_SH } from "./templates/gradlew"
26
27
 
@@ -38,6 +39,10 @@ export const ANDROID_SDK_REPO = "letary/lecodes-android-sdk"
38
39
  * :lecodes-ui). A 2.x bundle is refused by a 1.x runtime (`_creatorApp.run()` gates on the major),
39
40
  * so a shell pinned below this would install and show nothing; `lecodes app update` moves a 1.x
40
41
  * shell here. (1.2.0 was the 1.x floor: system back moved into engine.attach().) */
42
+ // TODO(docs/plans/ota-splash-plan.md step 1): raise to the first lecodes-android-sdk release with
43
+ // `LeCodesShell.boot(engine, activity, …)` (the first-launch wait + the splash hold), which the
44
+ // AppViewModel template now calls — the owner fills the version in at release time. (Against an
45
+ // older AAR the call still compiles: it lands on the context form, which never waits.)
41
46
  export const ANDROID_SDK_MIN_VERSION = "2.0.13"
42
47
 
43
48
  /** First lecodes-android-sdk release that publishes the variant matrix (lecodes-sdk-3d / -2d /
@@ -171,7 +176,7 @@ export const initAndroid = async (opts: AndroidInitOptions) => {
171
176
 
172
177
  write("app/build.gradle.kts", appBuildGradleTemplate(identity, config.android!.minify ?? true))
173
178
  write("app/proguard-rules.pro", APP_PROGUARD_RULES)
174
- write("app/src/main/AndroidManifest.xml", appManifestTemplate(urlSchemeOf(config)))
179
+ write("app/src/main/AndroidManifest.xml", appManifestTemplate(urlSchemeOf(config), appLinksOf(config)))
175
180
  write(`app/src/main/java/${pkgPath}/MainActivity.kt`, mainActivityTemplate(identity.applicationId))
176
181
  write(`app/src/main/java/${pkgPath}/AppViewModel.kt`, appViewModelTemplate(identity.applicationId))
177
182
  write("app/src/main/res/values/themes.xml", themesXmlTemplate())
@@ -184,6 +189,8 @@ export const initAndroid = async (opts: AndroidInitOptions) => {
184
189
  const initArtifact = cmpVersion(sdkVersion, ANDROID_SDK_VARIANTS_MIN) >= 0 ? androidSdkArtifact(initVariant, sdkVersion) : "lecodes-sdk"
185
190
  write("lecodes-runtime/build.gradle.kts", runtimeBuildGradleTemplate(sdkVersion, [], initArtifact))
186
191
  write("lecodes-runtime/src/main/kotlin/io/letary/lecodes/runtime/LeCodesRuntime.kt", runtimeKotlinTemplate([]))
192
+ // The parent of app/'s Theme.LeCodesApp (black until a sync renders app.json "splash" into it).
193
+ write("lecodes-runtime/src/main/res/values/lecodes_splash.xml", runtimeThemeTemplate())
187
194
 
188
195
  log("")
189
196
  log(`${c.green("sdk")} lecodes-android-sdk ${sdkVersion}${sdk === "latest" ? c.dim(" (android.sdk: latest — re-resolved on every sync)") : c.dim(" (pinned in app.json android.sdk — `lecodes app update` moves it)")}`)
@@ -191,6 +198,7 @@ export const initAndroid = async (opts: AndroidInitOptions) => {
191
198
  log(` ${c.bold("lecodes app sync")} embed the compiled bundle (+ plugins) into the shell`)
192
199
  log(` ${c.bold("lecodes app open android")} then run on your device from Android Studio`)
193
200
  log(` App icon: set app.json "icon" to a square ≥1024px image — sync renders every size (or use Android Studio → Image Asset)`)
201
+ log(` Splash: set app.json "splash": {"background": "#RRGGBB", "image": "./splash.png"} — sync renders the splash (the image centred at 160 dp, "size" overrides; Android 12+'s system splash included)`)
194
202
  }
195
203
 
196
204
  /* ---------------------------------------- sync ---------------------------------------- */
@@ -378,7 +386,14 @@ export const syncAndroid = async (root: string, config: AppConfig, prior: SyncAr
378
386
  // LeCodesShell.boot reads it — app.json "update" resolved like the iOS plist key ----
379
387
  const updateUrl = resolveUpdateUrl(config.update, root, sdkVersion)
380
388
  writeFileSync(join(androidDir, "lecodes-runtime", "src", "main", "AndroidManifest.xml"), runtimeManifestTemplate(updateUrl))
381
- if (updateUrl) log(`${c.green("update")} OTA source ${updateUrl} — checked natively at launch (LeCodesShell.boot), new code applies next launch`)
389
+ if (updateUrl) log(`${c.green("update")} OTA source ${updateUrl} — checked natively at launch (LeCodesShell.boot): the first launch of a build waits (≤ 5 s) for the newest bundle, later launches apply new code next launch`)
390
+ // ---- splash: Theme.LeCodesRuntime (the parent of the app's theme) in the runtime module's res —
391
+ // black without app.json "splash", the splash colour / image / Android 12+ system splash with it ----
392
+ await writeAndroidSplash(androidDir, await loadSplashMaster(root, config))
393
+ if (config.splash !== undefined) {
394
+ const themeHint = androidSplashThemeHint(androidDir)
395
+ if (themeHint) warn(`splash: ${themeHint}`)
396
+ }
382
397
 
383
398
  if (pluginSpecs.length > 0 || existsSync(lockPath)) writeJson(lockPath, { plugins: newLock })
384
399
 
@@ -393,38 +408,59 @@ export const syncAndroid = async (root: string, config: AppConfig, prior: SyncAr
393
408
  restampManifestIcon(androidDir)
394
409
  }
395
410
  restampManifestUrlScheme(androidDir, urlSchemeOf(config))
411
+ const appLinks = appLinksOf(config)
412
+ restampManifestAppLinks(androidDir, appLinks)
413
+ if (appLinks.length) {
414
+ log(`${c.green("links")} ${appLinks.map(l => l.url).join(", ")} — verified by the site's proof:`)
415
+ for (const line of appLinksSiteNote(appLinks, { platform: "android", applicationId: config.android?.applicationId })) log(` ${line}`)
416
+ }
396
417
 
397
418
  log("")
398
419
  success(`Android shell synced: app.js + ${runtimePlugins.length} plugin(s), SDK ${sdkVersion}, v${config.version ?? "1.0.0"} (${config.android?.versionCode ?? 1}).`)
399
420
  note("Build & run from Android Studio (`lecodes app open android`) — user files in android/app/ were not touched.")
400
421
  }
401
422
 
402
- /** The `lecodes:urlScheme` block of the USER-owned manifest follows app.json: written into the
403
- * activity when the key appears, rewritten when it changes, removed when it goes. A manifest
423
+ /** A `lecodes:<tag>` block of the USER-owned manifest follows app.json: written into the
424
+ * activity when its key appears, rewritten when it changes, removed when it goes. A manifest
404
425
  * without the tag and without a MainActivity to put it in is left alone, with a warning. */
405
- export const restampManifestUrlScheme = (androidDir: string, urlScheme: string | undefined): void => {
426
+ const restampManifestBlock = (androidDir: string, tag: string, block: string, what: string, missing: string, after: RegExp[] = []): void => {
406
427
  const path = join(androidDir, "app", "src", "main", "AndroidManifest.xml")
407
428
  if (!existsSync(path)) return
408
429
  const content = readFileSync(path, "utf8")
409
- const tagged = /\n[ \t]*<!-- lecodes:urlScheme[\s\S]*?<!-- \/lecodes:urlScheme -->/
410
- const block = urlSchemeFilter(urlScheme)
430
+ const tagged = new RegExp(`\\n[ \\t]*<!-- lecodes:${tag}[\\s\\S]*?<!-- \\/lecodes:${tag} -->`)
411
431
  let next: string
412
- if (tagged.test(content)) next = content.replace(tagged, block)
413
- else if (!urlScheme) return
432
+ if (tagged.test(content)) next = content.replace(tagged, () => block)
433
+ else if (!block) return
414
434
  else {
415
- // Inside the MainActivity element: right after its LAUNCHER intent-filter.
435
+ // Inside the MainActivity element: after the block it follows in the template when that one
436
+ // is there, else right after the LAUNCHER intent-filter — so a restamped manifest reads as a
437
+ // fresh init's.
416
438
  const launcher = /(<category android:name="android\.intent\.category\.LAUNCHER" \/>\s*<\/intent-filter>)/
417
- if (!launcher.test(content)) {
418
- warn(`couldn't find the launcher activity in app/src/main/AndroidManifest.xml — add an intent-filter for the "${urlScheme}" scheme yourself.`)
439
+ const anchor = [...after, launcher].find(re => re.test(content))
440
+ if (!anchor) {
441
+ warn(`couldn't find the launcher activity in app/src/main/AndroidManifest.xml — ${missing}`)
419
442
  return
420
443
  }
421
- next = content.replace(launcher, `$1${block}`)
444
+ next = content.replace(anchor, (m) => `${m}${block}`)
422
445
  }
423
446
  if (next === content) return
424
447
  writeFileSync(path, next)
425
- log(`${c.green("updated")} android/app/src/main/AndroidManifest.xml: urlScheme ${urlScheme ? `→ ${urlScheme}://` : "removed"}`)
448
+ log(`${c.green("updated")} android/app/src/main/AndroidManifest.xml: ${what}`)
426
449
  }
427
450
 
451
+ /** app.json "urlScheme" → the tagged BROWSABLE intent-filter (`urlSchemeFilter`). */
452
+ export const restampManifestUrlScheme = (androidDir: string, urlScheme: string | undefined): void =>
453
+ restampManifestBlock(androidDir, "urlScheme", urlSchemeFilter(urlScheme),
454
+ `urlScheme ${urlScheme ? `→ ${urlScheme}://` : "removed"}`,
455
+ `add an intent-filter for the "${urlScheme}" scheme yourself.`)
456
+
457
+ /** app.json "appLinks" → the tagged autoVerify intent-filters (`appLinksFilter`). */
458
+ export const restampManifestAppLinks = (androidDir: string, links: AppLink[]): void =>
459
+ restampManifestBlock(androidDir, "appLinks", appLinksFilter(links),
460
+ `appLinks ${links.length ? `→ ${links.map(l => l.url).join(", ")}` : "removed"}`,
461
+ `add the autoVerify intent-filters for ${links.map(l => l.url).join(", ")} yourself.`,
462
+ [/<!-- \/lecodes:urlScheme -->/])
463
+
428
464
  /** Values-only restamps + tagged-line management in the USER-owned app/build.gradle.kts —
429
465
  * the Android analog of the pbxproj MARKETING_VERSION restamp + CODE_SIGN_ENTITLEMENTS
430
466
  * injection: warn-not-fail when the user restructured, and the ONLY lines sync ever removes
@@ -1025,9 +1061,22 @@ export const doctorAndroidChecks = async (
1025
1061
  check(existsSync(manifest) && readFileSync(manifest, "utf8").includes("io.letary.lecodes.UPDATE_URL"), "OTA update URL in the runtime manifest", "run `lecodes app sync`", false)
1026
1062
  const appSrc = join(androidDir, "app", "src", "main", "java")
1027
1063
  const kt = existsSync(appSrc) ? readdirSync(appSrc, { recursive: true }).map(String).filter((f) => f.endsWith(".kt")) : []
1028
- const boots = kt.some((f) => readFileSync(join(appSrc, f), "utf8").includes("LeCodesShell.boot"))
1064
+ const sources = kt.map((f) => readFileSync(join(appSrc, f), "utf8"))
1065
+ const boots = sources.some((src) => src.includes("LeCodesShell.boot"))
1029
1066
  check(boots, "App code launches via the updater (LeCodesShell.boot)",
1030
- "no app/src/main/java/**/*.kt calls LeCodesShell.boot(engine, context) — downloaded updates would never run; see \"Over-the-air updates\" in android/README.md for the AppViewModel snippet", false)
1067
+ "no app/src/main/java/**/*.kt calls LeCodesShell.boot(engine, activity) — downloaded updates would never run; see \"Over-the-air updates\" in android/README.md for the AppViewModel snippet", false)
1068
+ // The context form (the pre-wait shape, `boot(engine, getApplication())`) still runs downloads,
1069
+ // but only from the NEXT launch: no view to hold, so the first launch of a build never waits.
1070
+ const waits = sources.some((src) => /LeCodesShell\.boot\(\s*engine\s*,\s*activity\b/.test(src))
1071
+ if (boots) check(waits, "The first launch waits for the newest bundle (LeCodesShell.boot(engine, activity))",
1072
+ "AppViewModel calls the context form of LeCodesShell.boot — pass the activity instead (onActivityCreate's parameter) so a fresh install runs the newest bundle at once; see \"Over-the-air updates\" in android/README.md", false)
1073
+ }
1074
+
1075
+ if (config.splash !== undefined) {
1076
+ // The splash lives in Theme.LeCodesRuntime (the runtime module); the user-owned app theme must
1077
+ // inherit it — a shell generated before the key existed is parented on AppCompat directly.
1078
+ const themeHint = androidSplashThemeHint(androidDir)
1079
+ check(!themeHint, "The app theme inherits the splash (Theme.LeCodesRuntime)", themeHint ?? "", false)
1031
1080
  }
1032
1081
 
1033
1082
  const signing = resolveAndroidSigning(androidDir)
@@ -3,18 +3,20 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statS
3
3
  import { homedir } from "node:os"
4
4
  import { basename, dirname, join, resolve } from "node:path"
5
5
  import { readManifest } from "../../project/manifest"
6
+ import { binaryName } from "../../plugin/manifest"
6
7
  import { compileShell, type BundleResource } from "../compile"
7
8
  import { CliError, UsageError, bool, c, defineCommand, log, note, str, success, warn } from "../../cli"
8
9
  import {
9
10
  ACCENT_COLOR_JSON, APP_DELEGATE, APP_ICON_JSON, ASSETS_ROOT_JSON, IOS_README, LAUNCH_STORYBOARD,
10
11
  SCENE_DELEGATE, SCHEME_XML, VIEW_CONTROLLER, entitlementsTemplate, infoPlistTemplate,
11
- pbxprojTemplate, runtimePackageTemplate, runtimeSwiftTemplate,
12
+ pbxprojTemplate, runtimeBinaryPath, runtimePackageTemplate, runtimeSwiftTemplate,
12
13
  type RuntimePlugin, type SdkVariant, type ShellIdentity,
13
14
  } from "./templates/ios"
14
15
  import {
15
16
  FIRST_PARTY_PLUGINS, SDK_VARIANTS, cmpVersion, ensureShellIgnored,
16
17
  fetchLatestSdkVersion, latestPluginTag, localPlugin, localPluginKey, pluginSpecsFor, projectRoot, readAppConfigAt, readJson, resolvePlugin, resolveSdkVersion, sdkSatisfies,
17
18
  resolveVariant, runTool, slugify, writeJson, VERSION_RE, type AppConfig, type LockEntry, resolveUpdateUrl, urlSchemeOf,
19
+ appLinksOf, appLinksSiteNote, associatedDomainsOf,
18
20
  } from "./shared"
19
21
  import { isLocalPluginSpec, type PluginEntry } from "lecodes-sdk/compile"
20
22
  import {
@@ -23,6 +25,14 @@ import {
23
25
  } from "./android"
24
26
  import { desktopBuild, initDesktop } from "./desktop"
25
27
  import { loadIconMaster, writeIosAppIcon } from "./icon"
28
+ import { loadSplashMaster, writeIosSplash } from "./splash"
29
+
30
+ /** The entitlements of app.json alone (init, before any plugin): the associated domains of
31
+ * "appLinks". Sync merges the plugins' values on top of these. */
32
+ const iosEntitlements = (base: Record<string, unknown>, config: AppConfig): Record<string, unknown> => {
33
+ const domains = associatedDomainsOf(appLinksOf(config))
34
+ return domains.length ? { ...base, "com.apple.developer.associated-domains": domains } : base
35
+ }
26
36
 
27
37
  /*
28
38
  * `lecodes app` — native app shells for a LeCodes project (docs/xcode-app-plan.md). This file is
@@ -68,6 +78,10 @@ const SDK_REPO = "letary/lecodes-ios-sdk"
68
78
  // it); this floor is only the last-resort fallback when the network is unavailable at init. A 1.x
69
79
  // shell is moved here by `lecodes app update` (its CLI-owned files are regenerated; its
70
80
  // App/ViewController.swift keeps compiling: LeCodesViewController and LeCodesUpdater exist in 2.x).
81
+ // TODO(docs/plans/ota-splash-plan.md step 1): raise to the first lecodes-ios-sdk release with the
82
+ // first-launch wait (LeCodesShell.boot's `firstLaunchTimeout` + the launch-screen hold of
83
+ // LeCodesShellViewController) — the owner fills the version in at release time. (An older SDK
84
+ // still builds the generated shell: it just never waits.)
71
85
  const SDK_MIN_VERSION = "2.0.7"
72
86
 
73
87
  // First lecodes-ios-sdk release with `LeCodesEngine.bootProjectUuid` — the shell's world
@@ -167,7 +181,7 @@ const initIos = async (opts: IosInitOptions): Promise<void> => {
167
181
  write("App/SceneDelegate.swift", SCENE_DELEGATE)
168
182
  write("App/ViewController.swift", VIEW_CONTROLLER)
169
183
  write("App/Info.plist", infoPlistTemplate({}, undefined, urlSchemeOf(config)))
170
- write("App/App.entitlements", entitlementsTemplate({}))
184
+ write("App/App.entitlements", entitlementsTemplate(iosEntitlements({}, config)))
171
185
  write("App/Base.lproj/LaunchScreen.storyboard", LAUNCH_STORYBOARD)
172
186
  write("App/Assets.xcassets/Contents.json", ASSETS_ROOT_JSON)
173
187
  write("App/Assets.xcassets/AccentColor.colorset/Contents.json", ACCENT_COLOR_JSON)
@@ -183,6 +197,7 @@ const initIos = async (opts: IosInitOptions): Promise<void> => {
183
197
  log(` ${c.bold("lecodes app sync")} embed the compiled bundle (+ plugins) into the shell`)
184
198
  log(` ${c.bold("open ios/App.xcodeproj")} then run on your device from Xcode`)
185
199
  log(` App icon: set app.json "icon" to a square ≥1024px image — sync renders every size (or drop a PNG into App/Assets.xcassets/AppIcon.appiconset/)`)
200
+ log(` Splash: set app.json "splash": {"background": "#RRGGBB", "image": "./splash.png"} — sync writes the launch screen (the image centred at 160 pt, "size" overrides; or edit App/Base.lproj/LaunchScreen.storyboard yourself)`)
186
201
  }
187
202
 
188
203
  const init = defineCommand({
@@ -256,7 +271,9 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
256
271
  const entitlementValues: Record<string, unknown[]> = {}
257
272
  const newLock: Record<string, LockEntry> = {}
258
273
 
259
- const sourcesDir = join(iosDir, "LeCodesRuntime", "Sources")
274
+ const runtimeDir = join(iosDir, "LeCodesRuntime")
275
+ const sourcesDir = join(runtimeDir, "Sources")
276
+ const binariesDir = join(runtimeDir, "Binaries")
260
277
  for (const [id, spec] of pluginSpecs) {
261
278
  const plugin = resolvePlugin(id, spec, oldLock[id], "ios")
262
279
  const ios = plugin.manifest.ios!
@@ -269,6 +286,11 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
269
286
  const dest = join(sourcesDir, module)
270
287
  rmSync(dest, { recursive: true, force: true })
271
288
  cpSync(src, dest, { recursive: true })
289
+ // Its prebuilt xcframeworks (manifest ios.binaries) beside the sources, replaced the same way:
290
+ // a binary target's path is inside the package (SwiftPM takes none outside it).
291
+ const binaries = (ios.binaries ?? []).map(path => ({ path, name: binaryName(path) }))
292
+ rmSync(join(binariesDir, id), { recursive: true, force: true })
293
+ for (const b of binaries) cpSync(join(plugin.dir, b.path), join(runtimeDir, runtimeBinaryPath(id, b.name)), { recursive: true, verbatimSymlinks: true })
272
294
 
273
295
  // Hard error, not a warning: outside the plugin's `sdk` range the vendored sources reference
274
296
  // an SDK API the linked release does not have (or another contract major), so the shell
@@ -287,9 +309,9 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
287
309
  throw new CliError(`Plugin "${id}": manifest ios.packages entries need { url, exact | from, products: [...] } — got ${JSON.stringify(pkg)}`)
288
310
  }
289
311
  }
290
- runtimePlugins.push({ id, module, register, packages: ios.packages })
312
+ runtimePlugins.push({ id, module, register, packages: ios.packages, binaries: binaries.map(b => b.name) })
291
313
  newLock[id] = plugin.lock
292
- log(`${c.green("plugin")} ${id}@${plugin.lock.version} (${plugin.lock.tag} → Sources/${module})`)
314
+ log(`${c.green("plugin")} ${id}@${plugin.lock.version} (${plugin.lock.tag} → Sources/${module}${binaries.length ? `, Binaries/${id}` : ""})`)
293
315
  }
294
316
 
295
317
  // Remove targets of uninstalled plugins (everything under Sources/ except the runtime itself).
@@ -300,6 +322,15 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
300
322
  log(`${c.yellow("removed")} ios/LeCodesRuntime/Sources/${entry} (plugin uninstalled)`)
301
323
  }
302
324
  }
325
+ // …and their binaries (Binaries/<id>/); the folder goes with the last of them.
326
+ const installed = new Set(runtimePlugins.map(p => p.id))
327
+ for (const entry of existsSync(binariesDir) ? readdirSync(binariesDir) : []) {
328
+ if (!installed.has(entry) && statSync(join(binariesDir, entry)).isDirectory()) {
329
+ rmSync(join(binariesDir, entry), { recursive: true })
330
+ log(`${c.yellow("removed")} ios/LeCodesRuntime/Binaries/${entry} (plugin uninstalled)`)
331
+ }
332
+ }
333
+ if (existsSync(binariesDir) && readdirSync(binariesDir).length === 0) rmSync(binariesDir, { recursive: true })
303
334
 
304
335
  // ---- bundle: compile self-contained into Resources/, then embed the assets it references ----
305
336
  const remotePatterns = config.resources?.remote ?? []
@@ -375,7 +406,7 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
375
406
  for (const [key, values] of Object.entries(infoValues)) mergedKeys[key] = [...new Set(values)].join(" ")
376
407
  const updateUrl = resolveUpdateUrl(config.update, root, sdkVersion)
377
408
  writeFileSync(join(iosDir, "App", "Info.plist"), infoPlistTemplate(mergedKeys, updateUrl, urlSchemeOf(config)))
378
- if (updateUrl) log(`${c.green("update")} OTA source ${updateUrl} — checked natively at launch, new code applies next launch${config.update === undefined ? c.dim(' ("update": false in app.json turns it off)') : ""}`)
409
+ if (updateUrl) log(`${c.green("update")} OTA source ${updateUrl} — checked natively at launch: the first launch of a build waits (≤ 5 s) for the newest bundle, later launches apply new code next launch${config.update === undefined ? c.dim(' ("update": false in app.json turns it off)') : ""}`)
379
410
  else if (config.update === false) log(`${c.green("update")} off (app.json "update": false)`)
380
411
  else note(`no OTA: a local-only project has no bundle on the platform — push it, or set "update": {"url": "https://…/app.js"} for custom hosting`)
381
412
 
@@ -393,6 +424,13 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
393
424
  // get the CODE_SIGN_ENTITLEMENTS reference injected the first time a plugin brings a
394
425
  // capability — the ONE structural pbxproj edit sync ever makes, idempotent and line-shaped.
395
426
  const mergedEntitlements: Record<string, unknown> = {}
427
+ // app.json "appLinks" → associated-domains, merged like a plugin's array value (a plugin may
428
+ // declare the key too, e.g. a web-credentials domain). The key gone = the domains gone: the
429
+ // file is regenerated whole.
430
+ const appLinks = appLinksOf(config)
431
+ if (appLinks.length) {
432
+ (entitlementValues["com.apple.developer.associated-domains"] ??= []).unshift(associatedDomainsOf(appLinks))
433
+ }
396
434
  for (const [key, values] of Object.entries(entitlementValues)) {
397
435
  if (values.every(v => Array.isArray(v))) {
398
436
  const seen = new Set<string>()
@@ -405,6 +443,10 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
405
443
  mergedEntitlements[key] = values[0]
406
444
  }
407
445
  }
446
+ if (appLinks.length) {
447
+ log(`${c.green("links")} ${appLinks.map(l => l.url).join(", ")} — verified by the site's proof:`)
448
+ for (const line of appLinksSiteNote(appLinks, { platform: "ios", teamId: config.ios?.teamId, bundleId: config.ios?.bundleId })) log(` ${line}`)
449
+ }
408
450
  const hasEntitlements = Object.keys(mergedEntitlements).length > 0
409
451
  if (pbx.includes("CODE_SIGN_ENTITLEMENTS") || hasEntitlements) {
410
452
  writeFileSync(join(iosDir, "App", "App.entitlements"), entitlementsTemplate(mergedEntitlements))
@@ -426,6 +468,11 @@ const syncIos = async (root: string, config: AppConfig): Promise<SyncArtifacts>
426
468
  if (config.icon) {
427
469
  await writeIosAppIcon(iosDir, await loadIconMaster(root, config))
428
470
  }
471
+ // ---- splash: the launch storyboard from app.json "splash" when set (it becomes CLI-owned with
472
+ // its colorset / imageset) — absent, the storyboard stays the person's ----
473
+ if (config.splash !== undefined) {
474
+ await writeIosSplash(iosDir, await loadSplashMaster(root, config))
475
+ }
429
476
 
430
477
  log("")
431
478
  success(`Shell synced: app.js + ${runtimePlugins.length} plugin(s), SDK ${sdkVersion}, variant ${variant}, v${config.version ?? "1.0.0"} (${config.ios.buildNumber ?? 1}).`)
@@ -437,7 +484,7 @@ const sync = defineCommand({
437
484
  name: "sync",
438
485
  summary: "Make every existing shell match the project: bundle + assets + SDK variant + plugins + CLI-owned files",
439
486
  usage: "[ios|android]",
440
- description: "Compiles the bundle and embeds the assets it references (ios/App/Resources/ resp. the android assets/; offline by default, also for server projects — app.json \"resources\": {\"remote\": [globs]} keeps heavy assets streaming), picks the SDK variant from the bundle's engine use, vendors the app.json plugins (pinned in plugins.lock.json) and regenerates the CLI-owned shell files. User files (ios/App/*.swift, android/app/) are never touched.\n\nNative OTA JS updates at launch (both shells; the current launch runs the newest LOCAL bundle, a download applies on the next): on by default for a pushed project (its bundle on the platform, the launcher's own URL), app.json \"update\": {\"url\": …} for custom hosting, \"update\": false turns it off. A download runs only when it is of the shell's SDK major and not older than the bundle running. app.json \"icon\" (a square ≥1024px image) renders the app icons every sync (\"iconBackground\": the adaptive / flatten backdrop). app.json \"urlScheme\" (\"myshop\") is the scheme the shells open on: iOS CFBundleURLTypes, Android a BROWSABLE intent-filter — a link arrives as app.launchUrl / the \"url\" event (the return of Browser.open with a returnUrl). No platform = every shell that exists; a dual-shell project compiles once.",
487
+ description: "Compiles the bundle and embeds the assets it references (ios/App/Resources/ resp. the android assets/; offline by default, also for server projects — app.json \"resources\": {\"remote\": [globs]} keeps heavy assets streaming), picks the SDK variant from the bundle's engine use, vendors the app.json plugins (pinned in plugins.lock.json) and regenerates the CLI-owned shell files. User files (ios/App/*.swift, android/app/) are never touched.\n\nNative OTA JS updates at launch (both shells): the first launch of an installed build waits (≤ 5 s, the splash held) for the check and runs the newest bundle; every later launch runs the newest LOCAL bundle and a download applies on the next. On by default for a pushed project (its bundle on the platform, the launcher's own URL), app.json \"update\": {\"url\": …} for custom hosting, \"update\": false turns it off. A download runs only when it is of the shell's SDK major and not older than the bundle running; a store update keeps a downloaded bundle only when it is newer code than the one it ships. app.json \"icon\" (a square ≥1024px image) renders the app icons every sync (\"iconBackground\": the adaptive / flatten backdrop). app.json \"splash\" ({\"background\": \"#RRGGBB\", \"image\": \"./splash.png\", \"size\": 160}, all optional) renders the launch screen of both shells every sync — the colour with the image fitted centred into a size × size pt / dp square, 160 by default (iOS LaunchScreen.storyboard, Android the system splash of Theme.LeCodesRuntime, which the app's theme inherits). app.json \"urlScheme\" (\"myshop\") is the scheme the shells open on: iOS CFBundleURLTypes, Android a BROWSABLE intent-filter — a link arrives as app.launchUrl / the \"url\" event (the return of Browser.open with a returnUrl). app.json \"appLinks\" ([\"https://shop.example/pay/\"]) are the verified https links they open on — iOS universal links (associated-domains in App.entitlements), Android App Links (autoVerify intent-filters in the manifest); sync prints the apple-app-site-association / assetlinks.json each site must serve. No platform = every shell that exists; a dual-shell project compiles once.",
441
488
  examples: ["lecodes app sync", "lecodes app sync android"],
442
489
  run: ({ args }) => runSync(args[0]),
443
490
  })
@@ -766,7 +813,7 @@ const doctorIosChecks = async (root: string, config: AppConfig, check: Check) =>
766
813
  const doctor = defineCommand({
767
814
  name: "doctor",
768
815
  summary: "Preflight checks for building / uploading the shells",
769
- description: "Toolchain (Xcode / JDK + Android SDK), the synced bundle, SDK variant + version vs app.json, plugin lock, signing (team id / release keystore), icons, OTA wiring and the App Store Connect key. Fatal checks fail the command (exit 1); soft ones print a `!` and a hint.",
816
+ description: "Toolchain (Xcode / JDK + Android SDK), the synced bundle, SDK variant + version vs app.json, plugin lock, signing (team id / release keystore), icons, the splash theme (Android), OTA wiring and the App Store Connect key. Fatal checks fail the command (exit 1); soft ones print a `!` and a hint.",
770
817
  examples: ["lecodes app doctor"],
771
818
  run: async () => {
772
819
  const root = projectRoot()
@@ -782,6 +829,9 @@ const doctor = defineCommand({
782
829
  if (config?.icon) {
783
830
  check(existsSync(join(root, config.icon)), `Icon master ${config.icon}`, `app.json "icon" points at a missing file — sync will fail`)
784
831
  }
832
+ if (typeof config?.splash?.image === "string") {
833
+ check(existsSync(join(root, config.splash.image)), `Splash image ${config.splash.image}`, `app.json "splash.image" points at a missing file — sync will fail`)
834
+ }
785
835
  if (hasIos) await doctorIosChecks(root, config!, check)
786
836
  if (hasAndroid) {
787
837
  await doctorAndroidChecks(root, config!, check)
@@ -49,6 +49,21 @@ export interface AppConfig {
49
49
  /** Icon backdrop ("#RGB"/"#RRGGBB", default white): the Android adaptive-icon background
50
50
  * layer, and what a transparent master is flattened onto for the opacity-required iOS icon. */
51
51
  iconBackground?: string
52
+ /** The launch screen of both shells, rendered by every sync (splash.ts): a full-screen colour
53
+ * (`background`, any opaque CSS color, default `iconBackground`, default white) and, optionally,
54
+ * `image` (project-root-relative PNG/JPEG) fitted CENTRED into a square of a fixed logical side
55
+ * on both platforms — `size` pt / dp, a whole number, default 160 — never at its pixel size:
56
+ * sync renders every density from the one master (iOS @1x/@2x/@3x = size × 1/2/3 px, Android
57
+ * mdpi…xxxhdpi = size × 1/1.5/2/3/4 px), so a master under 3 × size px warns (it would upscale)
58
+ * and a non-square one is fitted into the square keeping its aspect. `size` above 192 warns
59
+ * (Android 12+ shows only the inner 192 dp circle of the splash icon, the rest is cut; iOS and
60
+ * Android before 12 show it whole), above 288 (the Android 12+ icon canvas) is refused.
61
+ * Recommend a square mark: Android 12+ crops the splash icon to a circle. No image = the colour
62
+ * alone. With the key, the generated files become CLI-owned (iOS: LaunchScreen.storyboard + the
63
+ * LeCodesSplash imageset / LeCodesSplashBackground colorset; Android: the lecodes-runtime
64
+ * module's res, through `Theme.LeCodesRuntime` — the parent the app's theme must name). Absent
65
+ * = nothing is generated: the storyboard stays the person's, the Android window stays black. */
66
+ splash?: { background?: string, image?: string, size?: number }
52
67
  /** id → a spec for every platform (`"*"`, `"^2.0.0"`, `"github:owner/repo@v1"`, `"./plugins/<id>"`)
53
68
  * or a spec per platform (`{ "web": "./plugins/ar-8thwall" }`; a platform it does not name is
54
69
  * `"*"`). Read in the list form too (readAppConfigAt); a platform's spec is pluginSpecOf's. */
@@ -58,16 +73,28 @@ export interface AppConfig {
58
73
  * / the "url" event — what `Browser.open(url, { returnUrl })` resolves on after an OAuth redirect.
59
74
  * Lowercase letters, digits, `+ - .`, starting with a letter. */
60
75
  urlScheme?: string
76
+ /** The verified https links the shells open on (`"https://shop.example/pay/"`: a URL prefix,
77
+ * several allowed): iOS universal links (`applinks:<host>` in the entitlements), Android App
78
+ * Links (an `autoVerify` intent-filter per host, with the paths). A link reaches the app as
79
+ * `app.launchUrl` / the "url" event — the return of `Browser.open(url, { returnUrl })` when
80
+ * the page (a bank's app, a checkout) sends the person back by https. The site must serve the
81
+ * two proofs (sync prints them): /.well-known/apple-app-site-association and
82
+ * /.well-known/assetlinks.json. One list for both platforms, like `plugins`. */
83
+ appLinks?: string[]
61
84
  /** `remote`: lecodesignore-style globs of resources to STREAM from the server instead of
62
85
  * embedding in the app (server-backed projects only — a streamed asset needs a server URL). */
63
86
  resources?: { remote?: string[] }
64
87
  /** Over-the-air JS updates: where the shell checks for newer compiled code at launch
65
- * (natively, before the JS engine — offline is a no-op, new code applies next launch).
88
+ * (natively, before the JS engine — offline is a no-op). The first launch of an installed
89
+ * build waits for the check (≤ 5 s, the splash held) and runs the newest bundle; every later
90
+ * launch runs the local bundle at once and new code applies next launch.
66
91
  * `true` = this project's live bundle on the platform (server-backed only); or an https
67
92
  * URL to a compiled bundle on any hosting (string or `{ "url": … }`). Absent = no OTA.
68
93
  * Both shells: iOS reads it from Info.plist (LeCodesUpdater), Android from the manifest
69
94
  * meta-data the CLI-owned lecodes-runtime module carries (LeCodesShell.boot). A download runs
70
- * only when it is of the shell's SDK major and not older than the bundle running. */
95
+ * only when it is of the shell's SDK major and not older than the bundle running; a store
96
+ * update keeps a downloaded bundle only when it is newer code (by compile date) than the one
97
+ * the update ships. */
71
98
  update?: boolean | string | { url?: string }
72
99
  /** `variant`: SDK product — "auto" (default: sync picks the smallest one covering the engines
73
100
  * the compiled bundle actually uses) or core|2d|3d|full to force one.
@@ -229,6 +256,62 @@ export const urlSchemeOf = (config: Pick<AppConfig, "urlScheme"> | null | undefi
229
256
  return scheme
230
257
  }
231
258
 
259
+ /** One app.json "appLinks" entry, parsed: the prefix as written, its host, its path ("" for the
260
+ * host's root — every path of the host). */
261
+ export interface AppLink { url: string, host: string, path: string }
262
+
263
+ /** app.json "appLinks", checked: https URL prefixes with a host, no query / fragment (a prefix
264
+ * ends at a path). Empty when the key is absent. */
265
+ export const appLinksOf = (config: Pick<AppConfig, "appLinks"> | null | undefined): AppLink[] => {
266
+ const raw = config?.appLinks
267
+ if (raw === undefined) return []
268
+ if (!Array.isArray(raw)) throw new CliError(`app.json "appLinks" must be a list of https URL prefixes (["https://shop.example/pay/"]) — got ${JSON.stringify(raw)}.`)
269
+ const links: AppLink[] = []
270
+ for (const entry of raw) {
271
+ let url: URL
272
+ try { url = new URL(typeof entry === "string" ? entry : "") } catch { url = null as any }
273
+ if (!url || url.protocol !== "https:" || !url.hostname) {
274
+ throw new CliError(`app.json "appLinks": ${JSON.stringify(entry)} is not an https URL prefix ("https://shop.example/pay/"). A custom scheme goes in "urlScheme".`)
275
+ }
276
+ if (url.search || url.hash || url.username || url.port) {
277
+ throw new CliError(`app.json "appLinks": ${JSON.stringify(entry)} — a prefix is a host and a path, no query, fragment, port or credentials.`)
278
+ }
279
+ const path = url.pathname === "/" ? "" : url.pathname
280
+ if (links.some(l => l.host === url.hostname && l.path === path)) continue
281
+ links.push({ url: `https://${url.hostname}${path}`, host: url.hostname, path })
282
+ }
283
+ return links
284
+ }
285
+
286
+ /** The iOS entitlement "appLinks" means: one `applinks:<host>` per host (the paths live in the
287
+ * site's apple-app-site-association). */
288
+ export const associatedDomainsOf = (links: AppLink[]): string[] => [...new Set(links.map(l => `applinks:${l.host}`))]
289
+
290
+ /** What the sites named by "appLinks" must serve for the OS to trust the links — printed by sync
291
+ * so nobody composes them by hand: the AASA for iOS (`teamId.bundleId` + the paths), assetlinks
292
+ * for Android (the package + the signing certificate's SHA-256, which `lecodes app keystore show`
293
+ * prints). One block per host. */
294
+ export const appLinksSiteNote = (links: AppLink[], ids: { platform: "ios", teamId?: string, bundleId?: string } | { platform: "android", applicationId?: string }): string[] => {
295
+ const lines: string[] = []
296
+ const hosts = [...new Set(links.map(l => l.host))]
297
+ for (const host of hosts) {
298
+ const paths = links.filter(l => l.host === host).map(l => l.path)
299
+ const patterns = paths.includes("") ? ["*"] : paths.map(p => `${p}*`)
300
+ if (ids.platform === "ios") {
301
+ const appId = `${ids.teamId ?? "<TEAM_ID>"}.${ids.bundleId ?? "<BUNDLE_ID>"}`
302
+ lines.push(`https://${host}/.well-known/apple-app-site-association (Content-Type: application/json, no redirect — Apple's CDN fetches it at install):`)
303
+ lines.push(JSON.stringify({ applinks: { details: [{ appIDs: [appId], components: patterns.map(p => ({ "/": p })) }] } }))
304
+ } else {
305
+ lines.push(`https://${host}/.well-known/assetlinks.json (Content-Type: application/json):`)
306
+ lines.push(JSON.stringify([{
307
+ relation: ["delegate_permission/common.handle_all_urls"],
308
+ target: { namespace: "android_app", package_name: ids.applicationId ?? "<APPLICATION_ID>", sha256_cert_fingerprints: ["<SHA-256 of the signing certificate — `lecodes app keystore show`>"] },
309
+ }]))
310
+ }
311
+ }
312
+ return lines
313
+ }
314
+
232
315
  /** app.json wherever a command needs the project-level desktop/window config. Tolerant of a
233
316
  * missing or broken file — standalone projects (no app.json) must keep working everywhere
234
317
  * this is consulted. */