@moku-labs/native 0.3.10 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -793,8 +793,8 @@ function generateCapabilities(input) {
793
793
  //#endregion
794
794
  //#region src/plugins/project/generators/cargo.ts
795
795
  /**
796
- * @file project plugin generator — Cargo.toml with registry-pinned crate dependencies and
797
- * the path dependency of every generated local crate.
796
+ * @file project plugin generator — Cargo.toml with registry-pinned crate dependencies, the
797
+ * path dependency of every generated local crate, and the size profile of a release build.
798
798
  */
799
799
  /**
800
800
  * The `tauri` crate floor. The `back` capability calls `exit()` and grants
@@ -809,6 +809,19 @@ const TAURI_VERSION_FLOOR = "2.12";
809
809
  */
810
810
  const IOS_ONLY_DEPENDENCIES = [`[target.'cfg(target_os = "ios")'.dependencies]`, "objc2 = \"0.6\""];
811
811
  /**
812
+ * The release profile, for every target and both build profiles: the debug build is a
813
+ * release build too, so what a phone measures is what the store ships. It trades compile
814
+ * time for a smaller library, and `panic = "abort"` drops the unwinding tables.
815
+ */
816
+ const RELEASE_PROFILE = [
817
+ "[profile.release]",
818
+ "codegen-units = 1",
819
+ "lto = true",
820
+ "opt-level = \"s\"",
821
+ "panic = \"abort\"",
822
+ "strip = true"
823
+ ];
824
+ /**
812
825
  * Derives a valid Cargo package name from the app's display name — lowercased,
813
826
  * non-alphanumeric runs collapsed to a single hyphen, and guaranteed to start with a
814
827
  * letter (Cargo package names must match `[a-z][a-z0-9_-]*`).
@@ -866,7 +879,8 @@ function dependencyLine(capability) {
866
879
  * the tray API is not compiled in at all), plus one dependency line per resolved
867
880
  * capability that ships a crate: pinned for a published one, by path for the generated
868
881
  * shell crate. Feature-only and permission-only rows contribute no dependency line. The
869
- * iOS-only `objc2` table closes the file on every target.
882
+ * `[profile.release]` table follows, and the iOS-only `objc2` table closes the file on
883
+ * every target.
870
884
  *
871
885
  * @param input - Frozen global config + capabilities resolved for the target.
872
886
  * @returns A single-artifact array for `src-tauri/Cargo.toml`.
@@ -896,6 +910,8 @@ function generateCargo(input) {
896
910
  "serde_json = \"1\"",
897
911
  ...pinnedDeps,
898
912
  "",
913
+ ...RELEASE_PROFILE,
914
+ "",
899
915
  ...IOS_ONLY_DEPENDENCIES,
900
916
  ""
901
917
  ].join("\n")
@@ -1015,7 +1031,7 @@ function generateEntitlements(input) {
1015
1031
  //#region src/plugins/project/generators/rust.ts
1016
1032
  /**
1017
1033
  * @file project plugin generator — main.rs/lib.rs with mobile entry point, plugin init
1018
- * lines and the iOS safe-area setup hook.
1034
+ * lines and the iOS setup hook (the safe area, and the idle timer with `app.keepScreenOn`).
1019
1035
  */
1020
1036
  /**
1021
1037
  * `Manager` brings `get_webview_window` into scope. Only the iOS arm of the setup hook
@@ -1023,11 +1039,12 @@ function generateEntitlements(input) {
1023
1039
  */
1024
1040
  const IOS_MANAGER_IMPORT = ["#[cfg(target_os = \"ios\")]", "use tauri::Manager;"];
1025
1041
  /**
1026
- * The safe-area setup hook, as verified on the iOS 26.3 simulator. UIKit shrinks a
1027
- * WKWebView page by the safe area while its scroll view stays on `.automatic`; `.never`
1028
- * gives the page the whole screen, and CSS `env(safe-area-inset-*)` still reports the
1029
- * notch. The `cfg` makes it a no-op off iOS, so `lib.rs` does not differ per target. The
1030
- * window is tauri's default `main` label: the generated `app.windows` entry carries none.
1042
+ * The safe-area setup hook up to the end of the iOS closure, as verified on the iOS 26.3
1043
+ * simulator. UIKit shrinks a WKWebView page by the safe area while its scroll view stays on
1044
+ * `.automatic`; `.never` gives the page the whole screen, and CSS `env(safe-area-inset-*)`
1045
+ * still reports the notch. The `cfg` makes it a no-op off iOS, so `lib.rs` does not differ
1046
+ * per target. The window is tauri's default `main` label: the generated `app.windows` entry
1047
+ * carries none.
1031
1048
  */
1032
1049
  const SAFE_AREA_SETUP = [
1033
1050
  " .setup(|_app| {",
@@ -1040,7 +1057,19 @@ const SAFE_AREA_SETUP = [
1040
1057
  " let wk = &*(webview.inner() as *mut AnyObject);",
1041
1058
  " let scroll: *mut AnyObject = msg_send![wk, scrollView];",
1042
1059
  " // UIScrollViewContentInsetAdjustmentNever = 2",
1043
- " let _: () = msg_send![&*scroll, setContentInsetAdjustmentBehavior: 2isize];",
1060
+ " let _: () = msg_send![&*scroll, setContentInsetAdjustmentBehavior: 2isize];"
1061
+ ];
1062
+ /**
1063
+ * The `app.keepScreenOn` calls, the tail of the iOS closure: `with_webview` runs on the main
1064
+ * thread, the one UIKit wants them on, and the page cannot do this for itself on iOS.
1065
+ */
1066
+ const IDLE_TIMER_CALLS = [
1067
+ " // iOS refuses navigator.wakeLock until the first tap, so the app does it at launch.",
1068
+ " let application: *mut AnyObject = msg_send![objc2::class!(UIApplication), sharedApplication];",
1069
+ " let _: () = msg_send![&*application, setIdleTimerDisabled: true];"
1070
+ ];
1071
+ /** Closes the iOS closure and the setup hook. */
1072
+ const SETUP_END = [
1044
1073
  " })?;",
1045
1074
  " }",
1046
1075
  " Ok(())",
@@ -1051,13 +1080,15 @@ const SAFE_AREA_SETUP = [
1051
1080
  * `#[cfg_attr(mobile, tauri::mobile_entry_point)]`-annotated `run()` with one
1052
1081
  * `.plugin(...)` init line per resolved capability that has a real Rust init (rows
1053
1082
  * without one, e.g. tray's cargo-feature row, contribute no line), then the iOS
1054
- * safe-area `.setup` hook; `main.rs` is a thin entry point that calls into the lib crate.
1083
+ * safe-area `.setup` hook, which turns the idle timer off too with `app.keepScreenOn`;
1084
+ * `main.rs` is a thin entry point that calls into the lib crate.
1055
1085
  *
1056
1086
  * @param input - Frozen global config + capabilities resolved for the target.
1057
1087
  * @returns Artifacts for `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`.
1058
1088
  * @example
1059
1089
  * ```ts
1060
- * generateRust({ global, target: "android", capabilities: [] });
1090
+ * generateRust({ global, target: "android", capabilities: [], profile: "store" }).map(file => file.path);
1091
+ * // ["src-tauri/src/lib.rs", "src-tauri/src/main.rs"]
1061
1092
  * ```
1062
1093
  */
1063
1094
  function generateRust(input) {
@@ -1071,6 +1102,8 @@ function generateRust(input) {
1071
1102
  " tauri::Builder::default()",
1072
1103
  ...pluginLines,
1073
1104
  ...SAFE_AREA_SETUP,
1105
+ ...input.global.app.keepScreenOn ? IDLE_TIMER_CALLS : [],
1106
+ ...SETUP_END,
1074
1107
  " .run(tauri::generate_context!())",
1075
1108
  " .expect(\"error while running tauri application\");",
1076
1109
  "}",
@@ -1931,7 +1964,7 @@ function shellPageScript(input, profile) {
1931
1964
  * @returns The crate's artifacts, paths relative to `projectDir`; empty without the shell.
1932
1965
  * @example
1933
1966
  * ```ts
1934
- * generateShell({ global, target: "android", capabilities: [resolve("shell")] }, "debug")[0]?.path;
1967
+ * generateShell({ global, target: "android", capabilities: [resolve("shell")], profile: "debug" }, "debug")[0]?.path;
1935
1968
  * // "plugins/moku-shell/Cargo.toml"
1936
1969
  * ```
1937
1970
  */
@@ -2070,32 +2103,72 @@ function escapeXml(text) {
2070
2103
  /**
2071
2104
  * @file project plugin generator — Info.ios.plist sidecar (src-tauri root, outside gen/).
2072
2105
  */
2106
+ /** One indentation step of the generated plist. */
2107
+ const PLIST_INDENT = " ";
2108
+ /**
2109
+ * Tells a plist `<array>` from a `<dict>`: `Array.isArray` alone does not narrow a readonly
2110
+ * array.
2111
+ *
2112
+ * @param value - An array or a dictionary value.
2113
+ * @returns True, narrowing `value`, when it is an array.
2114
+ * @example
2115
+ * ```ts
2116
+ * isPlistArray(["a"]); // true
2117
+ * ```
2118
+ */
2119
+ function isPlistArray(value) {
2120
+ return Array.isArray(value);
2121
+ }
2122
+ /**
2123
+ * Renders one dictionary's entries as `<key>` lines, each followed by its value. Every key is
2124
+ * XML-escaped.
2125
+ *
2126
+ * @param entries - The key/value pairs, in order.
2127
+ * @param indent - The indentation of the `<key>` lines.
2128
+ * @returns The entries' lines.
2129
+ * @example
2130
+ * ```ts
2131
+ * renderPlistEntries([["A&B", true]], " "); // [" <key>A&amp;B</key>", " <true/>"]
2132
+ * ```
2133
+ */
2134
+ function renderPlistEntries(entries, indent) {
2135
+ return [...entries].flatMap(([key, value]) => [`${indent}<key>${escapeXml(key)}</key>`, ...renderPlistValue(value, indent)]);
2136
+ }
2073
2137
  /**
2074
2138
  * Renders one plist value as the lines that follow its `<key>`: a `<string>`, a
2075
- * `<true/>`/`<false/>`, or an `<array>` of strings. Every text is XML-escaped.
2139
+ * `<true/>`/`<false/>`, or an `<array>` or `<dict>` holding more of them, as deep as the
2140
+ * value goes. Every text is XML-escaped.
2076
2141
  *
2077
2142
  * @param value - The entry value.
2078
- * @returns The value's lines, indented for the top-level `<dict>`.
2143
+ * @param indent - The indentation of the value's first line.
2144
+ * @returns The value's lines.
2079
2145
  * @example
2080
2146
  * ```ts
2081
- * renderPlistValue(["UIInterfaceOrientationPortrait"]);
2147
+ * renderPlistValue(["UIInterfaceOrientationPortrait"], " ");
2082
2148
  * // [" <array>", " <string>UIInterfaceOrientationPortrait</string>", " </array>"]
2083
2149
  * ```
2084
2150
  */
2085
- function renderPlistValue(value) {
2086
- if (typeof value === "boolean") return [value ? " <true/>" : " <false/>"];
2087
- if (typeof value === "string") return [` <string>${escapeXml(value)}</string>`];
2151
+ function renderPlistValue(value, indent) {
2152
+ if (typeof value === "boolean") return [`${indent}${value ? "<true/>" : "<false/>"}`];
2153
+ if (typeof value === "string") return [`${indent}<string>${escapeXml(value)}</string>`];
2154
+ const nested = `${indent}${PLIST_INDENT}`;
2155
+ if (isPlistArray(value)) return [
2156
+ `${indent}<array>`,
2157
+ ...value.flatMap((item) => renderPlistValue(item, nested)),
2158
+ `${indent}</array>`
2159
+ ];
2088
2160
  return [
2089
- " <array>",
2090
- ...value.map((item) => ` <string>${escapeXml(item)}</string>`),
2091
- " </array>"
2161
+ `${indent}<dict>`,
2162
+ ...renderPlistEntries(Object.entries(value), nested),
2163
+ `${indent}</dict>`
2092
2164
  ];
2093
2165
  }
2094
2166
  /**
2095
2167
  * Generates the `Info.ios.plist` SIDECAR at the src-tauri root, which Tauri merges into the
2096
2168
  * app's Info.plist on every iOS build. Its entries are every resolved capability's
2097
- * `sidecarPlist`, then the orientation lock (`app.orientation`); on a duplicate key the
2098
- * later entry wins, so orientation beats a capability.
2169
+ * `sidecarPlist`, then `ios.infoPlist`, then the orientation lock (`app.orientation`); on a
2170
+ * duplicate key the later entry wins, so the app's keys beat a capability and orientation
2171
+ * beats both.
2099
2172
  *
2100
2173
  * On iOS the file is ALWAYS written, as an empty `<dict>` when nothing contributes a key:
2101
2174
  * the writer never deletes a file, and a portrait lock left in a stale sidecar would keep
@@ -2107,15 +2180,22 @@ function renderPlistValue(value) {
2107
2180
  * ```ts
2108
2181
  * // `config` is any full native Config
2109
2182
  * const global = { ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } };
2110
- * generateSidecar({ global, target: "ios", capabilities: [] })[0]?.path; // "src-tauri/Info.ios.plist"
2183
+ * generateSidecar({ global, target: "ios", capabilities: [], profile: "store" })[0]?.path; // "src-tauri/Info.ios.plist"
2111
2184
  * // its <dict>: UISupportedInterfaceOrientations, UISupportedInterfaceOrientations~ipad, UIRequiresFullScreen
2112
- * generateSidecar({ global, target: "macos", capabilities: [] }); // []
2185
+ * generateSidecar({ global, target: "macos", capabilities: [], profile: "store" }); // []
2113
2186
  * ```
2114
2187
  */
2115
2188
  function generateSidecar(input) {
2116
2189
  if (input.target !== "ios") return [];
2117
2190
  const entries = /* @__PURE__ */ new Map();
2118
- const contributed = [...input.capabilities.flatMap((capability) => capability.sidecarPlist), ...orientationPlist(input.global.app.orientation)];
2191
+ const contributed = [
2192
+ ...input.capabilities.flatMap((capability) => capability.sidecarPlist),
2193
+ ...Object.entries(input.global.ios?.infoPlist ?? {}).map(([key, value]) => ({
2194
+ key,
2195
+ value
2196
+ })),
2197
+ ...orientationPlist(input.global.app.orientation)
2198
+ ];
2119
2199
  for (const entry of contributed) entries.set(entry.key, entry.value);
2120
2200
  return [{
2121
2201
  path: "src-tauri/Info.ios.plist",
@@ -2124,7 +2204,7 @@ function generateSidecar(input) {
2124
2204
  "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
2125
2205
  "<plist version=\"1.0\">",
2126
2206
  "<dict>",
2127
- ...[...entries].flatMap(([key, value]) => [` <key>${escapeXml(key)}</key>`, ...renderPlistValue(value)]),
2207
+ ...renderPlistEntries(entries, PLIST_INDENT),
2128
2208
  "</dict>",
2129
2209
  "</plist>",
2130
2210
  ""
@@ -2135,7 +2215,7 @@ function generateSidecar(input) {
2135
2215
  //#region src/plugins/project/generators/tauri-conf.ts
2136
2216
  /**
2137
2217
  * @file project plugin generator — tauri.conf.json (identity, build wiring, bundle
2138
- * metadata, Apple signing, plugin blocks).
2218
+ * metadata, Apple signing, the Android versionCode, plugin blocks).
2139
2219
  */
2140
2220
  /**
2141
2221
  * The icon set `tauri icon` writes into `src-tauri/icons`. Tauri reads `bundle.icon` at
@@ -2148,13 +2228,10 @@ const BUNDLE_ICONS = [
2148
2228
  "icons/icon.icns",
2149
2229
  "icons/icon.ico"
2150
2230
  ];
2151
- /**
2152
- * The iOS deployment target used when `signing.apple.iosMinimumSystemVersion` is unset.
2153
- * Tauri's own default is 14.0, which Xcode 27 rejects outright ("the range of supported
2154
- * deployment target versions is 15.0 to 27.0.x", xcodebuild exit 65), so every iOS build
2155
- * on a current Xcode failed until the person found and set this value themselves.
2156
- */
2157
- const DEFAULT_IOS_MINIMUM_SYSTEM_VERSION = "15.0";
2231
+ /** A whole number without leading zeros: the only shape Gradle's `versionCode` takes. */
2232
+ const VERSION_CODE_PATTERN = /^[1-9]\d*$/;
2233
+ /** The highest `versionCode` Google Play accepts. */
2234
+ const MAX_VERSION_CODE = 21e8;
2158
2235
  /**
2159
2236
  * Drops the entries whose value is unset, so an unconfigured store/signing field is
2160
2237
  * ABSENT from the JSON rather than present-and-null (Tauri rejects null there).
@@ -2172,16 +2249,51 @@ function compact(entries) {
2172
2249
  return result;
2173
2250
  }
2174
2251
  /**
2252
+ * Reads the Android `versionCode` from `app.buildNumber`, as the JSON number Tauri asks for.
2253
+ * Checked here and not at composition: `"1.0.3"` stays a legal macOS/iOS bundle version, and
2254
+ * `build.run({ targets })` may name a target outside `config.targets`.
2255
+ *
2256
+ * @param input - Frozen global config + the target being generated for.
2257
+ * @returns The `versionCode` on android with a build number set, undefined otherwise.
2258
+ * @throws {Error} `[native]` on android when the build number is not a whole number from 1
2259
+ * to 2100000000.
2260
+ * @example
2261
+ * ```ts
2262
+ * androidVersionCode({ global: { app: { buildNumber: "42" } }, target: "android" }); // 42
2263
+ * ```
2264
+ */
2265
+ function androidVersionCode(input) {
2266
+ const { buildNumber } = input.global.app;
2267
+ if (input.target !== "android" || buildNumber === void 0) return void 0;
2268
+ const versionCode = Number(buildNumber);
2269
+ if (VERSION_CODE_PATTERN.test(buildNumber) && versionCode <= MAX_VERSION_CODE) return versionCode;
2270
+ throw new Error(`[native] app.buildNumber "${buildNumber}" is not a valid Android versionCode.\n Use a whole number from 1 to ${MAX_VERSION_CODE}, such as "42".`);
2271
+ }
2272
+ /**
2273
+ * Whether a platform block carries anything worth writing.
2274
+ *
2275
+ * @param block - A compacted block.
2276
+ * @returns True when the block has at least one key.
2277
+ * @example
2278
+ * ```ts
2279
+ * hasEntries({}); // false
2280
+ * ```
2281
+ */
2282
+ function hasEntries(block) {
2283
+ return Object.keys(block).length > 0;
2284
+ }
2285
+ /**
2175
2286
  * Builds the `bundle` block — icon set, optional store metadata, and the signing
2176
- * identifiers. `iOS` and `android` always exist (Tauri expects the keys), and `iOS` always
2177
- * carries a deployment target Xcode accepts; `macOS` and `windows` appear only when
2178
- * something is actually configured for them.
2287
+ * identifiers. `iOS` and `android` always exist (Tauri expects the keys), `iOS` always
2288
+ * carries a deployment target Xcode accepts, and `android` carries a `versionCode` on an
2289
+ * android build with a build number; `macOS` and `windows` appear only when something is
2290
+ * actually configured for them.
2179
2291
  *
2180
2292
  * @param input - Frozen global config + capabilities resolved for the target.
2181
2293
  * @returns The `bundle` object for tauri.conf.json.
2182
2294
  * @example
2183
2295
  * ```ts
2184
- * buildBundle({ global: { app: { name: "App" }, signing: {} }, target: "ios", capabilities: [] }).iOS;
2296
+ * buildBundle({ global: { app: { name: "App" }, signing: {} }, target: "ios", capabilities: [], profile: "store" }).iOS;
2185
2297
  * // { minimumSystemVersion: "15.0" }
2186
2298
  * ```
2187
2299
  */
@@ -2189,6 +2301,7 @@ function buildBundle(input) {
2189
2301
  const { app, signing } = input.global;
2190
2302
  const apple = signing.apple ?? {};
2191
2303
  const windows = compact([["certificateThumbprint", signing.windows?.certificateThumbprint]]);
2304
+ const versionCode = androidVersionCode(input);
2192
2305
  const macOS = compact([
2193
2306
  ["signingIdentity", apple.signingIdentity],
2194
2307
  ["providerShortName", apple.providerShortName],
@@ -2203,12 +2316,12 @@ function buildBundle(input) {
2203
2316
  ...compact([["category", app.category]]),
2204
2317
  iOS: compact([
2205
2318
  ["developmentTeam", apple.teamId],
2206
- ["minimumSystemVersion", apple.iosMinimumSystemVersion ?? DEFAULT_IOS_MINIMUM_SYSTEM_VERSION],
2319
+ ["minimumSystemVersion", apple.iosMinimumSystemVersion ?? "15.0"],
2207
2320
  ["bundleVersion", app.buildNumber]
2208
2321
  ]),
2209
- ...Object.keys(macOS).length > 0 ? { macOS } : {},
2210
- ...Object.keys(windows).length > 0 ? { windows } : {},
2211
- android: {}
2322
+ ...hasEntries(macOS) ? { macOS } : {},
2323
+ ...hasEntries(windows) ? { windows } : {},
2324
+ android: versionCode === void 0 ? {} : { versionCode }
2212
2325
  };
2213
2326
  }
2214
2327
  /**
@@ -2236,9 +2349,10 @@ function buildPlugins(capabilities) {
2236
2349
  return plugins;
2237
2350
  }
2238
2351
  /**
2239
- * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, the
2240
- * main window (its title, plus `app.backgroundColor` when set), the bundle/signing
2241
- * metadata, and a `plugins.<name>` block per CONFIGURED capability (see
2352
+ * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, with
2353
+ * `removeUnusedCommands` in the store profile only (a debug page may call what a store
2354
+ * page does not), the main window (its title, plus `app.backgroundColor` when set), the
2355
+ * bundle/signing metadata, and a `plugins.<name>` block per CONFIGURED capability (see
2242
2356
  * {@link buildPlugins}; this is where deep-link's scheme rides — per D-011/D-012 the whole
2243
2357
  * v1 mobile-permission story is conf-only). Both path-shaped fields are rebased onto
2244
2358
  * `src-tauri`, which is where Tauri resolves them from, and the before-commands carry an
@@ -2246,9 +2360,11 @@ function buildPlugins(capabilities) {
2246
2360
  *
2247
2361
  * @param input - Frozen global config + capabilities resolved for the target.
2248
2362
  * @returns A single-artifact array for `src-tauri/tauri.conf.json`.
2363
+ * @throws {Error} `[native]` on android when `app.buildNumber` is not a valid `versionCode`.
2249
2364
  * @example
2250
2365
  * ```ts
2251
- * generateTauriConf({ global, target: "ios", capabilities: [] });
2366
+ * generateTauriConf({ global, target: "ios", capabilities: [], profile: "store" })[0]?.path;
2367
+ * // "src-tauri/tauri.conf.json"
2252
2368
  * ```
2253
2369
  */
2254
2370
  function generateTauriConf(input) {
@@ -2268,7 +2384,8 @@ function generateTauriConf(input) {
2268
2384
  cwd: webRoot
2269
2385
  },
2270
2386
  devUrl: global.web.devUrl,
2271
- frontendDist: relativeToTauriRoot(global.projectDir, path.resolve(webRoot, global.web.dist))
2387
+ frontendDist: relativeToTauriRoot(global.projectDir, path.resolve(webRoot, global.web.dist)),
2388
+ ...input.profile === "store" ? { removeUnusedCommands: true } : {}
2272
2389
  },
2273
2390
  app: { windows: [{
2274
2391
  title: global.app.name,
@@ -2577,12 +2694,13 @@ async function writeIfChanged(filePath, content, projectDirectory) {
2577
2694
  //#region src/plugins/project/mobile/files.ts
2578
2695
  /**
2579
2696
  * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
2580
- * touch". Both iOS patches (the runner-command rewrite and the Xcode build-settings patch)
2581
- * read the same list from here, so neither can drift into a file the other does not know
2582
- * about — and neither ever descends into `gen/apple/build` or `gen/android/build`, which
2583
- * belong to the toolchain. The Android status bar patch finds its MainActivity.kt here too,
2584
- * the profile patches their `strings.xml` and network security config, and the icon inset
2585
- * its adaptive icon directory.
2697
+ * touch". Every iOS patch (the runner-command rewrite, the Xcode build-settings patch and
2698
+ * the iOS project patches) reads the same list from here, so none can drift into a file the
2699
+ * others do not know about — and none ever descends into `gen/apple/build` or
2700
+ * `gen/android/build`, which belong to the toolchain. The privacy manifest's place in the
2701
+ * tree is here too. The Android status bar patch finds its MainActivity.kt here, the profile
2702
+ * patches their `strings.xml` and network security config, and the icon inset its adaptive
2703
+ * icon directory.
2586
2704
  */
2587
2705
  /** Source extensions that can carry the Android runner command. */
2588
2706
  const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -2612,6 +2730,8 @@ const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
2612
2730
  ".gradle",
2613
2731
  ".idea"
2614
2732
  ]);
2733
+ /** The file name Apple reads a privacy manifest from, at the top of the app bundle. */
2734
+ const IOS_PRIVACY_MANIFEST_FILE = "PrivacyInfo.xcprivacy";
2615
2735
  /**
2616
2736
  * Lists the generated iOS files a patch pass may rewrite: `project.yml` plus the
2617
2737
  * `project.pbxproj` of every generated Xcode project. `gen/apple/build` is never listed —
@@ -2636,6 +2756,21 @@ async function iosPatchFiles(genDirectory) {
2636
2756
  return files;
2637
2757
  }
2638
2758
  /**
2759
+ * Returns where the iOS patch pass keeps the privacy manifest: the top of `gen/apple`, the
2760
+ * directory `project.yml` and the pbxproj's root group resolve a relative path from.
2761
+ *
2762
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
2763
+ * @returns The `PrivacyInfo.xcprivacy` path of that tree.
2764
+ * @example
2765
+ * ```ts
2766
+ * iosPrivacyManifestPath("/repo/.moku/tauri/src-tauri/gen/apple");
2767
+ * // "/repo/.moku/tauri/src-tauri/gen/apple/PrivacyInfo.xcprivacy"
2768
+ * ```
2769
+ */
2770
+ function iosPrivacyManifestPath(genDirectory) {
2771
+ return path.join(genDirectory, IOS_PRIVACY_MANIFEST_FILE);
2772
+ }
2773
+ /**
2639
2774
  * Walks a directory tree collecting accepted files, skipping derived build output.
2640
2775
  *
2641
2776
  * @param directory - The directory to walk (a missing directory yields nothing).
@@ -2704,6 +2839,21 @@ async function androidMainActivityFiles(genDirectory) {
2704
2839
  return (await collectFiles(androidJavaDirectory(genDirectory), (name) => name === MAIN_ACTIVITY_FILE)).toSorted();
2705
2840
  }
2706
2841
  /**
2842
+ * Returns the directory `tauri android init` writes the app's resources into, where the
2843
+ * window background patch finds every `values*\/themes.xml`.
2844
+ *
2845
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2846
+ * @returns The `app/src/main/res` directory of that tree.
2847
+ * @example
2848
+ * ```ts
2849
+ * androidResourceDirectory("/repo/.moku/tauri/src-tauri/gen/android");
2850
+ * // "/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res"
2851
+ * ```
2852
+ */
2853
+ function androidResourceDirectory(genDirectory) {
2854
+ return path.join(genDirectory, ...ANDROID_RESOURCE_SEGMENTS);
2855
+ }
2856
+ /**
2707
2857
  * Returns the app's string resources, where the debug profile renames the app.
2708
2858
  *
2709
2859
  * @param genDirectory - The `src-tauri/gen/android` directory.
@@ -2809,154 +2959,936 @@ async function patchAndroidIcon(options) {
2809
2959
  };
2810
2960
  }
2811
2961
  //#endregion
2812
- //#region src/plugins/project/mobile/manifest.ts
2962
+ //#region src/plugins/project/mobile/xcode-settings.ts
2813
2963
  /**
2814
- * @file project plugin — the Android manifest patch. Tauri has no config key for what the
2815
- * main activity carries (`android:screenOrientation` among them), so the mobile patch pass
2816
- * sets those attributes on the `<activity>` of the generated
2817
- * `gen/android/app/src/main/AndroidManifest.xml` itself. The same rules set attributes on
2818
- * the `<application>` start tag (the debug profile's network security config).
2964
+ * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
2819
2965
  *
2820
- * The transform is a pure text function: only the touched attribute changes, every other
2821
- * byte (line endings and indentation included) survives, and a second pass is a no-op.
2966
+ * A capability plugin's build script rewrites the generated `<app>_iOS.entitlements` file
2967
+ * while Xcode is compiling, and Xcode fails the second build on that:
2968
+ * `Entitlements file "<app>_iOS.entitlements" was modified during the build, which is not
2969
+ * supported`. Xcode names the way out itself — `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION`
2970
+ * — so every `buildSettings` block of the generated `project.pbxproj` carries it, and the
2971
+ * `project.yml` target carries it too, so a later xcodegen regeneration keeps it.
2972
+ *
2973
+ * Both transforms are pure text functions over the real generated shapes: line endings,
2974
+ * indentation and every neighbouring line survive byte for byte, and a second pass is a
2975
+ * no-op.
2822
2976
  */
2823
- /** Where `tauri android init` writes the app manifest, below `gen/android`. */
2824
- const MANIFEST_PATH_SEGMENTS = [
2825
- "app",
2826
- "src",
2827
- "main",
2828
- "AndroidManifest.xml"
2829
- ];
2830
- /** The tag name the application start tag opens with. */
2831
- const APPLICATION_OPEN = "<application";
2832
- /** Where an `<application` start tag opens. */
2833
- const APPLICATION_OPEN_PATTERN = /<application(?=[\s/>])/;
2834
- /** The tag name an activity start tag opens with. */
2835
- const ACTIVITY_OPEN = "<activity";
2836
- /** The end tag that closes an activity's body. */
2837
- const ACTIVITY_CLOSE = "</activity>";
2838
- /** The intent action that marks the launcher activity. */
2839
- const MAIN_ACTION = "android.intent.action.MAIN";
2840
- /** Where an `<activity` start tag opens — `<activity-alias` is a different element. */
2841
- const ACTIVITY_OPEN_PATTERN = /<activity(?=[\s/>])/g;
2977
+ /** The Xcode build setting that permits a build script to rewrite the entitlements file. */
2978
+ const ENTITLEMENTS_MODIFICATION_KEY = "CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION";
2979
+ /** The pbxproj value form — Xcode writes booleans as `YES`/`NO`. */
2980
+ const PBXPROJ_ENABLED_VALUE = "YES";
2842
2981
  /**
2843
- * One attribute inside a start tag, from the whitespace character before it:
2844
- * ` (name)="value"`. XML allows spaces around `=`, but no generated manifest writes them.
2982
+ * The project.yml value form. xcodegen renders a YAML boolean as `YES` in the pbxproj it
2983
+ * generates, which is why the target's sibling settings read `true`/`false` there.
2845
2984
  */
2846
- const ATTRIBUTE_PATTERN = /\s([\w:.-]+)=(?:"[^"]*"|'[^']*')/g;
2847
- /** An XML comment — blanked before the scan, so a commented-out activity never counts. */
2848
- const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
2985
+ const YML_ENABLED_VALUE = "true";
2986
+ /** Opens one settings block inside a `XCBuildConfiguration` section. */
2987
+ const BUILD_SETTINGS_OPEN_PATTERN = /^([ \t]*)buildSettings = \{[ \t]*$/;
2988
+ /** The setting, already present as a pbxproj assignment (whatever its value). */
2989
+ const PBXPROJ_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*=`);
2990
+ /** The setting, already present as a YAML key (whatever its value). */
2991
+ const YML_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*:`);
2992
+ /** Opens a target's `settings:` mapping in `project.yml`. */
2993
+ const YML_SETTINGS_PATTERN = /^([ \t]*)settings:[ \t]*$/;
2994
+ /** Opens the `base:` mapping a `settings:` block carries its own build settings in. */
2995
+ const YML_BASE_PATTERN = /^([ \t]*)base:[ \t]*$/;
2996
+ /** The leading whitespace of a line — never matches a line break. */
2997
+ const INDENT_PATTERN$1 = /^[ \t]*/;
2998
+ /** Splits text into lines, keeping each line's own terminator attached to it. */
2999
+ const LINE_SPLIT_PATTERN = /(?<=\n)/;
3000
+ /** A line's terminator (LF or CRLF), stripped to compare the line's text alone. */
3001
+ const LINE_ENDING_PATTERN = /\r?\n$/;
3002
+ /** One indentation step inside a pbxproj — the generated file is tab-indented. */
3003
+ const PBXPROJ_NESTED_INDENT = " ";
3004
+ /** One indentation step inside a project.yml — YAML mappings never indent with tabs. */
3005
+ const YML_NESTED_INDENT = " ";
2849
3006
  /**
2850
- * Builds the `[native]` error for a manifest whose main activity cannot be told apart.
3007
+ * Splits text into lines that each remember their own terminator, so a file mixing (or
3008
+ * using) CRLF comes back out exactly as it went in.
2851
3009
  *
2852
- * @param manifestPath - The manifest that was searched.
2853
- * @returns A formatted `[native] ...` error.
3010
+ * @param text - The file content.
3011
+ * @returns One entry per line, in order.
2854
3012
  * @example
2855
3013
  * ```ts
2856
- * throw mainActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
3014
+ * splitLines("a\r\nb"); // [{ body: "a", ending: "\r\n" }, { body: "b", ending: "" }]
2857
3015
  * ```
2858
3016
  */
2859
- function mainActivityError(manifestPath) {
2860
- return /* @__PURE__ */ new Error(`[native] Could not find the main <activity> in ${manifestPath}.\n Re-run the mobile init pass (tauri android init) or report the manifest Tauri generated.`);
3017
+ function splitLines$1(text) {
3018
+ return text.split(LINE_SPLIT_PATTERN).map((chunk) => {
3019
+ const body = chunk.replace(LINE_ENDING_PATTERN, "");
3020
+ return {
3021
+ body,
3022
+ ending: chunk.slice(body.length)
3023
+ };
3024
+ });
2861
3025
  }
2862
3026
  /**
2863
- * Builds the `[native]` error for a manifest without an `<application>` element.
3027
+ * Joins lines back into file content.
2864
3028
  *
2865
- * @param manifestPath - The manifest that was searched.
2866
- * @returns A formatted `[native] ...` error.
3029
+ * @param lines - The lines to join.
3030
+ * @returns The file content.
2867
3031
  * @example
2868
3032
  * ```ts
2869
- * throw applicationError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
3033
+ * joinLines([{ body: "a", ending: "\n" }]); // "a\n"
2870
3034
  * ```
2871
3035
  */
2872
- function applicationError(manifestPath) {
2873
- return /* @__PURE__ */ new Error(`[native] Could not find the <application> element in ${manifestPath}.\n Re-run the mobile init pass (tauri android init) or report the manifest Tauri generated.`);
3036
+ function joinLines(lines) {
3037
+ return lines.map((line) => line.body + line.ending).join("");
2874
3038
  }
2875
3039
  /**
2876
- * Finds where a start tag ends. A quoted attribute value is skipped whole, so a `>` inside
2877
- * one never ends the tag.
3040
+ * Reads a line's leading whitespace — the indentation a new sibling line has to match.
2878
3041
  *
2879
- * @param text - The manifest content.
2880
- * @param from - Offset just past the tag name.
2881
- * @returns The offset just past the closing `>`, or undefined for a tag that never closes.
3042
+ * @param body - The line's text.
3043
+ * @returns The leading spaces/tabs, possibly empty.
2882
3044
  * @example
2883
3045
  * ```ts
2884
- * startTagEnd('<activity android:label="a > b">', 9); // 32
3046
+ * indentOf("\t\t\tisa = XCBuildConfiguration;"); // "\t\t\t"
2885
3047
  * ```
2886
3048
  */
2887
- function startTagEnd(text, from) {
2888
- let quote;
2889
- for (let index = from; index < text.length; index += 1) {
2890
- const character = text[index];
2891
- if (quote !== void 0) {
2892
- if (character === quote) quote = void 0;
2893
- continue;
2894
- }
2895
- if (character === "\"" || character === "'") {
2896
- quote = character;
2897
- continue;
2898
- }
2899
- if (character === ">") return index + 1;
2900
- }
3049
+ function indentOf(body) {
3050
+ return INDENT_PATTERN$1.exec(body)?.[0] ?? "";
2901
3051
  }
2902
3052
  /**
2903
- * Locates every `<activity>` start tag and records whether its body declares MAIN.
2904
- * Comments are blanked out first (same length, so every offset still points into the real
2905
- * text), which keeps a commented-out activity from being counted or patched. A start tag
2906
- * that never closes is not counted at all.
3053
+ * Returns a block that carries the setting exactly once: an assignment already there is
3054
+ * rewritten in place (a block that turned the setting OFF would still break the rebuild),
3055
+ * and an absent one is inserted as the block's first entry, at its siblings' indentation.
2907
3056
  *
2908
- * @param text - The manifest content.
2909
- * @returns One entry per activity, in file order.
3057
+ * @param block - The lines inside the block, without its opening and closing line.
3058
+ * @param options - How to place the setting.
3059
+ * @param options.present - Matches an assignment of the setting already in the block.
3060
+ * @param options.render - Renders the setting line at a given indentation.
3061
+ * @param options.fallbackIndent - Indentation used when the block carries no line to match.
3062
+ * @param options.fallbackEnding - Terminator used when the block carries no line to match.
3063
+ * @returns The block's lines, with the setting present exactly once.
2910
3064
  * @example
2911
3065
  * ```ts
2912
- * locateActivities('<activity android:name=".A" /><activity android:name=".B"><action android:name="android.intent.action.MAIN" /></activity>');
2913
- * // [{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]
3066
+ * placeSetting(block, { present: PBXPROJ_SETTING_PATTERN, render, fallbackIndent, fallbackEnding });
2914
3067
  * ```
2915
3068
  */
2916
- function locateActivities(text) {
2917
- const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
2918
- const activities = [];
2919
- for (const match of masked.matchAll(ACTIVITY_OPEN_PATTERN)) {
2920
- const start = match.index;
2921
- const end = startTagEnd(masked, start + 9);
2922
- if (end === void 0) continue;
2923
- const body = masked.slice(start, end).endsWith("/>") ? "" : masked.slice(end, masked.indexOf(ACTIVITY_CLOSE, end));
2924
- activities.push({
2925
- start,
2926
- end,
2927
- isMain: body.includes(MAIN_ACTION)
2928
- });
2929
- }
2930
- return activities;
3069
+ function placeSetting(block, options) {
3070
+ const { present, render, fallbackIndent, fallbackEnding } = options;
3071
+ const existingIndex = block.findIndex((line) => present.test(line.body));
3072
+ if (existingIndex !== -1) return block.map((line, index) => index === existingIndex ? {
3073
+ body: render(indentOf(line.body)),
3074
+ ending: line.ending
3075
+ } : line);
3076
+ const sibling = block.find((line) => line.body.trim().length > 0);
3077
+ return [{
3078
+ body: render(sibling ? indentOf(sibling.body) : fallbackIndent),
3079
+ ending: sibling?.ending ?? fallbackEnding
3080
+ }, ...block];
2931
3081
  }
2932
3082
  /**
2933
- * Picks the main activity: the one whose body declares MAIN. A manifest with a single
2934
- * activity and no MAIN still has an obvious one; anything else is ambiguous.
3083
+ * Collects the lines of one block, starting at `start` and stopping at the first line the
3084
+ * block does not own.
2935
3085
  *
2936
- * @param activities - Every activity in the manifest.
2937
- * @returns The main activity, or undefined when none or several qualify.
3086
+ * @param lines - Every line of the file.
3087
+ * @param start - Index of the block's first line.
3088
+ * @param isMember - Whether a line still belongs to the block.
3089
+ * @returns The block's lines, and the index of the first line after it.
2938
3090
  * @example
2939
3091
  * ```ts
2940
- * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]);
2941
- * // { start: 30, end: 58, isMain: true }
2942
- * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: false }]); // undefined
3092
+ * const { block, next } = collectBlock(lines, index, line => line.body !== "\t\t\t};");
2943
3093
  * ```
2944
3094
  */
2945
- function mainActivity(activities) {
2946
- const mains = activities.filter((activity) => activity.isMain);
2947
- if (mains.length === 1) return mains[0];
2948
- if (mains.length === 0 && activities.length === 1) return activities[0];
2949
- }
2950
- /**
2951
- * Locates the first `<application>` start tag outside a comment.
2952
- *
2953
- * @param text - The manifest content.
2954
- * @returns The tag's offsets, or undefined when there is none.
2955
- * @example
2956
- * ```ts
2957
- * locateApplication('<manifest><application android:label="a"></application></manifest>');
2958
- * // { start: 10, end: 40 }
2959
- * ```
3095
+ function collectBlock(lines, start, isMember) {
3096
+ const block = [];
3097
+ let index = start;
3098
+ while (index < lines.length) {
3099
+ const line = lines[index];
3100
+ if (!line || !isMember(line)) break;
3101
+ block.push(line);
3102
+ index += 1;
3103
+ }
3104
+ return {
3105
+ block,
3106
+ next: index
3107
+ };
3108
+ }
3109
+ /**
3110
+ * Renders the setting as a pbxproj assignment.
3111
+ *
3112
+ * @param indent - The indentation its sibling settings use.
3113
+ * @returns The assignment line.
3114
+ * @example
3115
+ * ```ts
3116
+ * renderPbxprojSetting("\t\t\t\t"); // "\t\t\t\tCODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;"
3117
+ * ```
3118
+ */
3119
+ function renderPbxprojSetting(indent) {
3120
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY} = ${PBXPROJ_ENABLED_VALUE};`;
3121
+ }
3122
+ /**
3123
+ * Renders the setting as a YAML mapping entry.
3124
+ *
3125
+ * @param indent - The indentation its sibling entries use.
3126
+ * @returns The entry line.
3127
+ * @example
3128
+ * ```ts
3129
+ * renderYmlSetting(" "); // " CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: true"
3130
+ * ```
3131
+ */
3132
+ function renderYmlSetting(indent) {
3133
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY}: ${YML_ENABLED_VALUE}`;
3134
+ }
3135
+ /**
3136
+ * Reads the `base:` mapping a target's `settings:` line opens — the one block in
3137
+ * `project.yml` that holds build settings.
3138
+ *
3139
+ * The block is walked, not peeked at: `base:` is a direct child of `settings:`, but not
3140
+ * necessarily the FIRST one — xcodegen is equally happy with `settings:` followed by
3141
+ * `groups: [app]` and `base:` below it. So every line indented deeper than `settings:` is
3142
+ * scanned until the block dedents, and the first `base:` sitting at the direct-child level
3143
+ * wins; a nested `base:` deeper inside somebody else's sub-mapping does not. A `settings:`
3144
+ * block carrying no `base:` at all owns no such block and is left alone.
3145
+ *
3146
+ * @param lines - Every line of the file.
3147
+ * @param settingsIndex - Index of the candidate `settings:` line.
3148
+ * @returns The `base:` line, its index and its indentation, or undefined when there is none.
3149
+ * @example
3150
+ * ```ts
3151
+ * baseMappingAt(splitLines(" settings:\n groups: [app]\n base:\n"), 0);
3152
+ * ```
3153
+ */
3154
+ function baseMappingAt(lines, settingsIndex) {
3155
+ const settingsLine = lines[settingsIndex];
3156
+ const settings = settingsLine && YML_SETTINGS_PATTERN.exec(settingsLine.body);
3157
+ if (!settings) return void 0;
3158
+ const settingsIndent = (settings[1] ?? "").length;
3159
+ let childIndent;
3160
+ for (let index = settingsIndex + 1; index < lines.length; index += 1) {
3161
+ const line = lines[index];
3162
+ if (!line) break;
3163
+ if (line.body.trim().length === 0) continue;
3164
+ const indent = indentOf(line.body);
3165
+ if (indent.length <= settingsIndent) break;
3166
+ childIndent ??= indent.length;
3167
+ if (indent.length !== childIndent) continue;
3168
+ if (YML_BASE_PATTERN.test(line.body)) return {
3169
+ line,
3170
+ index,
3171
+ indent
3172
+ };
3173
+ }
3174
+ }
3175
+ /**
3176
+ * Adds `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;` to every `buildSettings` block of
3177
+ * a generated `project.pbxproj`, exactly once per block and at the indentation its sibling
3178
+ * settings use. Content outside those blocks — the shell-script build phase included — is
3179
+ * returned byte for byte, and a file that already carries the setting comes back unchanged.
3180
+ *
3181
+ * @param existing - The current `project.pbxproj` content.
3182
+ * @returns The content with the setting in every settings block.
3183
+ * @example
3184
+ * ```ts
3185
+ * applyPbxprojEntitlementsSetting(await readFile(pbxprojPath, "utf8"));
3186
+ * ```
3187
+ */
3188
+ function applyPbxprojEntitlementsSetting(existing) {
3189
+ const lines = splitLines$1(existing);
3190
+ const patched = [];
3191
+ let index = 0;
3192
+ while (index < lines.length) {
3193
+ const line = lines[index];
3194
+ if (!line) break;
3195
+ patched.push(line);
3196
+ index += 1;
3197
+ const opening = BUILD_SETTINGS_OPEN_PATTERN.exec(line.body);
3198
+ if (!opening) continue;
3199
+ const blockIndent = opening[1] ?? "";
3200
+ const closing = `${blockIndent}};`;
3201
+ const { block, next } = collectBlock(lines, index, (inner) => inner.body !== closing);
3202
+ index = next;
3203
+ patched.push(...placeSetting(block, {
3204
+ present: PBXPROJ_SETTING_PATTERN,
3205
+ render: renderPbxprojSetting,
3206
+ fallbackIndent: `${blockIndent}${PBXPROJ_NESTED_INDENT}`,
3207
+ fallbackEnding: line.ending
3208
+ }));
3209
+ }
3210
+ return joinLines(patched);
3211
+ }
3212
+ /**
3213
+ * Adds the setting to every target's `settings.base` block in a generated `project.yml`, so
3214
+ * an xcodegen regeneration writes it back into the pbxproj. Only a `base:` mapping that is a
3215
+ * direct child of a `settings:` mapping is touched — a `settingGroups:` block is somebody
3216
+ * else's. A blank line inside the block does not end it: YAML mappings end at a dedent, so
3217
+ * an entry printed below an empty line is still seen and never duplicated.
3218
+ *
3219
+ * @param existing - The current `project.yml` content.
3220
+ * @returns The content with the setting under each target's `settings.base`.
3221
+ * @example
3222
+ * ```ts
3223
+ * applyProjectYmlEntitlementsSetting(await readFile(projectYmlPath, "utf8"));
3224
+ * ```
3225
+ */
3226
+ function applyProjectYmlEntitlementsSetting(existing) {
3227
+ const lines = splitLines$1(existing);
3228
+ const patched = [];
3229
+ let index = 0;
3230
+ while (index < lines.length) {
3231
+ const line = lines[index];
3232
+ if (!line) break;
3233
+ const base = baseMappingAt(lines, index);
3234
+ patched.push(line);
3235
+ index += 1;
3236
+ if (!base) continue;
3237
+ patched.push(...lines.slice(index, base.index + 1));
3238
+ index = base.index + 1;
3239
+ const { block, next } = collectBlock(lines, index, (entry) => entry.body.trim().length === 0 || indentOf(entry.body).length > base.indent.length);
3240
+ index = next;
3241
+ patched.push(...placeSetting(block, {
3242
+ present: YML_SETTING_PATTERN,
3243
+ render: renderYmlSetting,
3244
+ fallbackIndent: `${base.indent}${YML_NESTED_INDENT}`,
3245
+ fallbackEnding: base.line.ending
3246
+ }));
3247
+ }
3248
+ return joinLines(patched);
3249
+ }
3250
+ /**
3251
+ * Applies the entitlements-modification setting to every generated iOS project file —
3252
+ * `project.yml` and each `*.xcodeproj/project.pbxproj`. Idempotent: a second pass reports
3253
+ * every file unchanged. Nothing under `gen/apple/build` is ever read or written.
3254
+ *
3255
+ * @param projectDirectory - The Tauri project root.
3256
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
3257
+ * @returns The paths patched vs. left unchanged.
3258
+ * @example
3259
+ * ```ts
3260
+ * await patchXcodeSettings(projectDir, path.join(projectDir, "src-tauri/gen/apple"));
3261
+ * ```
3262
+ */
3263
+ async function patchXcodeSettings(projectDirectory, genDirectory) {
3264
+ const patched = [];
3265
+ const unchanged = [];
3266
+ for (const file of await iosPatchFiles(genDirectory)) {
3267
+ const existing = await readFile(file, "utf8");
3268
+ (await writeIfChanged(file, file.endsWith(".yml") ? applyProjectYmlEntitlementsSetting(existing) : applyPbxprojEntitlementsSetting(existing), projectDirectory) === "written" ? patched : unchanged).push(file);
3269
+ }
3270
+ return {
3271
+ patched,
3272
+ unchanged
3273
+ };
3274
+ }
3275
+ //#endregion
3276
+ //#region src/plugins/project/mobile/ios-project.ts
3277
+ /**
3278
+ * @file project plugin — the iOS project patches: the deployment target and the privacy
3279
+ * manifest.
3280
+ *
3281
+ * `tauri ios build` never runs xcodegen on a kept tree, and init runs before this pass, so a
3282
+ * change to `project.yml` alone reaches no build. Every change here lands in `project.yml`
3283
+ * (a later xcodegen keeps it) AND in each `project.pbxproj` (the file Xcode reads today).
3284
+ *
3285
+ * The transforms are pure text functions over the real generated shapes: line endings and
3286
+ * every neighbouring line survive byte for byte, and a second pass is a no-op. A file
3287
+ * without the line a transform needs is a `[native]` error, never a silent skip: the app
3288
+ * would ship the old minimum, or no manifest, with nothing in the log.
3289
+ */
3290
+ /** The name a pbxproj error reports. */
3291
+ const PBXPROJ_FILE = "project.pbxproj";
3292
+ /** The name a project.yml error reports. */
3293
+ const PROJECT_YML_FILE = "project.yml";
3294
+ /** Every deployment target of a pbxproj. Group 1 is the line up to the value. */
3295
+ const PBXPROJ_DEPLOYMENT_PATTERN = /^([ \t]*IPHONEOS_DEPLOYMENT_TARGET = )[^;\r\n]*;/gm;
3296
+ /** Opens the `deploymentTarget:` mapping of `project.yml`. */
3297
+ const YML_DEPLOYMENT_PATTERN = /^[ \t]*deploymentTarget:[ \t]*$/;
3298
+ /** The iOS entry of that mapping. Group 1 is the line up to the value. */
3299
+ const YML_IOS_ENTRY_PATTERN = /^([ \t]+iOS:[ \t]*)\S.*$/;
3300
+ /** The object id `mainGroup` names, with or without a name comment after it. */
3301
+ const MAIN_GROUP_PATTERN = /^[ \t]*mainGroup = (\w+)/;
3302
+ /** Opens the `children` list of a group. */
3303
+ const CHILDREN_LINE = "children = (";
3304
+ /** Opens the `files` list of a build phase. */
3305
+ const FILES_LINE = "files = (";
3306
+ /** The `PBXBuildFile` id of the manifest: `MOKU` in ASCII, then a counter. Never xcodegen's. */
3307
+ const PRIVACY_BUILD_FILE_ID = "4D4F4B5500000000000000A1";
3308
+ /** The `PBXFileReference` id of the manifest. */
3309
+ const PRIVACY_FILE_REFERENCE_ID = "4D4F4B5500000000000000A2";
3310
+ /** The manifest's `PBXBuildFile` line. */
3311
+ const BUILD_FILE_LINE = `\t\t${PRIVACY_BUILD_FILE_ID} /* ${IOS_PRIVACY_MANIFEST_FILE} in Resources */ = {isa = PBXBuildFile; fileRef = ${PRIVACY_FILE_REFERENCE_ID} /* ${IOS_PRIVACY_MANIFEST_FILE} */; };`;
3312
+ /** The manifest's `PBXFileReference` line; the root group resolves it from `gen/apple`. */
3313
+ const FILE_REFERENCE_LINE = `\t\t${PRIVACY_FILE_REFERENCE_ID} /* ${IOS_PRIVACY_MANIFEST_FILE} */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = ${IOS_PRIVACY_MANIFEST_FILE}; sourceTree = "<group>"; };`;
3314
+ /** The manifest's entry in the root group's `children`. */
3315
+ const GROUP_CHILD_LINE = `\t\t\t\t${PRIVACY_FILE_REFERENCE_ID} /* ${IOS_PRIVACY_MANIFEST_FILE} */,`;
3316
+ /** The manifest's entry in the Resources phase's `files`. */
3317
+ const RESOURCES_FILE_LINE = `\t\t\t\t${PRIVACY_BUILD_FILE_ID} /* ${IOS_PRIVACY_MANIFEST_FILE} in Resources */,`;
3318
+ /** The `project.yml` key of the targets, top level. */
3319
+ const YML_TARGETS_LINE = "targets:";
3320
+ /** Opens a `sources:` list in `project.yml`. */
3321
+ const YML_SOURCES_PATTERN = /^[ \t]+sources:[ \t]*$/;
3322
+ /** The first line of a YAML list entry. */
3323
+ const YML_LIST_ITEM_PATTERN = /^[ \t]*- /;
3324
+ /** The manifest's entry in the sources list. */
3325
+ const YML_PRIVACY_PATH_LINE = `- path: ${IOS_PRIVACY_MANIFEST_FILE}`;
3326
+ /** The second line of that entry. The `assets` entry carries the same one: it stays. */
3327
+ const YML_RESOURCES_PHASE_LINE = "buildPhase: resources";
3328
+ /** How deep a list entry's second line sits below its `- `. */
3329
+ const YML_ENTRY_INDENT = " ";
3330
+ /**
3331
+ * Builds the `[native]` refusal for a generated file that lacks what a patch needs.
3332
+ *
3333
+ * @param anchor - What is missing.
3334
+ * @param file - The file's name.
3335
+ * @returns A formatted `[native] ...` error.
3336
+ * @example
3337
+ * ```ts
3338
+ * missingAnchorError("mainGroup", "project.pbxproj").message;
3339
+ * // "[native] Could not find mainGroup in project.pbxproj.\n Run clean for ios and build again, or report the project.pbxproj Tauri generated."
3340
+ * ```
3341
+ */
3342
+ function missingAnchorError(anchor, file) {
3343
+ return /* @__PURE__ */ new Error(`[native] Could not find ${anchor} in ${file}.\n Run clean for ios and build again, or report the ${file} Tauri generated.`);
3344
+ }
3345
+ /**
3346
+ * Finds a line by its text inside a range of lines.
3347
+ *
3348
+ * @param lines - Every line of the file.
3349
+ * @param matches - Whether a line's text is the one looked for.
3350
+ * @param from - Index of the first line to look at.
3351
+ * @param to - Index after the last line to look at.
3352
+ * @returns The line's index in `lines`, or -1.
3353
+ * @example
3354
+ * ```ts
3355
+ * findLine(splitLines("a\nb\nb\n"), body => body === "b", 2, 3); // 2
3356
+ * ```
3357
+ */
3358
+ function findLine(lines, matches, from, to) {
3359
+ const index = lines.slice(from, to).findIndex((line) => matches(line.body));
3360
+ return index === -1 ? -1 : from + index;
3361
+ }
3362
+ /**
3363
+ * Finds the `Begin` and `End` comments of a pbxproj section.
3364
+ *
3365
+ * @param lines - Every line of the file.
3366
+ * @param section - The section's name, an `isa` value.
3367
+ * @returns The indices of both comments.
3368
+ * @throws {Error} `[native]` when the section is not there.
3369
+ * @example
3370
+ * ```ts
3371
+ * sectionBounds(splitLines("/* Begin A section *\/\n/* End A section *\/\n"), "A"); // { begin: 0, end: 1 }
3372
+ * ```
3373
+ */
3374
+ function sectionBounds(lines, section) {
3375
+ const begin = lines.findIndex((line) => line.body === `/* Begin ${section} section */`);
3376
+ const end = lines.findIndex((line) => line.body === `/* End ${section} section */`);
3377
+ if (begin === -1 || end === -1) throw missingAnchorError(`the ${section} section`, PBXPROJ_FILE);
3378
+ return {
3379
+ begin,
3380
+ end
3381
+ };
3382
+ }
3383
+ /**
3384
+ * Whether a line opens the object of one group id.
3385
+ *
3386
+ * @param body - The line's text.
3387
+ * @param id - The group's object id.
3388
+ * @returns True for the group's opening line.
3389
+ * @example
3390
+ * ```ts
3391
+ * opensGroup("\t\tAA = {", "AA"); // true
3392
+ * ```
3393
+ */
3394
+ function opensGroup(body, id) {
3395
+ return body.trimStart().startsWith(`${id} `) && body.trimEnd().endsWith("= {");
3396
+ }
3397
+ /**
3398
+ * Finds the `children = (` line of the root group: the group the `PBXProject` object's
3399
+ * `mainGroup` names, which has no name of its own to look for.
3400
+ *
3401
+ * @param lines - Every line of the file.
3402
+ * @returns The line's index.
3403
+ * @throws {Error} `[native]` when the `mainGroup` line, the group or its list is not there.
3404
+ * @example
3405
+ * ```ts
3406
+ * const text = [
3407
+ * "/* Begin PBXGroup section *\/",
3408
+ * "\t\tAA = {",
3409
+ * "\t\t\tisa = PBXGroup;",
3410
+ * "\t\t\tchildren = (",
3411
+ * "\t\t\t);",
3412
+ * "\t\t};",
3413
+ * "/* End PBXGroup section *\/",
3414
+ * "/* Begin PBXProject section *\/",
3415
+ * "\t\t\tmainGroup = AA;",
3416
+ * "/* End PBXProject section *\/"
3417
+ * ].join("\n");
3418
+ * rootGroupChildren(splitLines(text)); // 3
3419
+ * ```
3420
+ */
3421
+ function rootGroupChildren(lines) {
3422
+ const project = sectionBounds(lines, "PBXProject");
3423
+ const mainGroup = lines.slice(project.begin, project.end).map((line) => MAIN_GROUP_PATTERN.exec(line.body)?.[1]).find((id) => id !== void 0);
3424
+ if (mainGroup === void 0) throw missingAnchorError("mainGroup", PBXPROJ_FILE);
3425
+ const groups = sectionBounds(lines, "PBXGroup");
3426
+ const open = findLine(lines, (body) => opensGroup(body, mainGroup), groups.begin, groups.end);
3427
+ const opening = lines[open];
3428
+ if (!opening) throw missingAnchorError(`the main group ${mainGroup}`, PBXPROJ_FILE);
3429
+ const closing = `${indentOf(opening.body)}};`;
3430
+ const { block } = collectBlock(lines, open, (line) => line.body !== closing);
3431
+ const children = block.findIndex((line) => line.body.trim() === CHILDREN_LINE);
3432
+ if (children === -1) throw missingAnchorError(`the children of the main group ${mainGroup}`, PBXPROJ_FILE);
3433
+ return open + children;
3434
+ }
3435
+ /**
3436
+ * Finds the `files = (` line of the Resources phase. A generated project has one target,
3437
+ * so one such phase.
3438
+ *
3439
+ * @param lines - Every line of the file.
3440
+ * @returns The line's index.
3441
+ * @throws {Error} `[native]` when the section or its list is not there.
3442
+ * @example
3443
+ * ```ts
3444
+ * const text = [
3445
+ * "/* Begin PBXResourcesBuildPhase section *\/",
3446
+ * "\t\t\tisa = PBXResourcesBuildPhase;",
3447
+ * "\t\t\tfiles = (",
3448
+ * "/* End PBXResourcesBuildPhase section *\/"
3449
+ * ].join("\n");
3450
+ * resourcesFiles(splitLines(text)); // 2
3451
+ * ```
3452
+ */
3453
+ function resourcesFiles(lines) {
3454
+ const phases = sectionBounds(lines, "PBXResourcesBuildPhase");
3455
+ const files = findLine(lines, (body) => body.trim() === FILES_LINE, phases.begin, phases.end);
3456
+ if (files === -1) throw missingAnchorError("the PBXResourcesBuildPhase files", PBXPROJ_FILE);
3457
+ return files;
3458
+ }
3459
+ /**
3460
+ * Finds the `iOS:` entry of the `deploymentTarget:` mapping. The mapping is walked to its
3461
+ * dedent, so an entry below a sibling or a blank line counts, and an `iOS:` key outside it
3462
+ * does not.
3463
+ *
3464
+ * @param lines - Every line of the file.
3465
+ * @returns The entry's index, or -1.
3466
+ * @example
3467
+ * ```ts
3468
+ * ymlDeploymentEntry(splitLines(" deploymentTarget:\n iOS: 16.0\n")); // 1
3469
+ * ```
3470
+ */
3471
+ function ymlDeploymentEntry(lines) {
3472
+ const open = lines.findIndex((line) => YML_DEPLOYMENT_PATTERN.test(line.body));
3473
+ const opening = lines[open];
3474
+ if (!opening) return -1;
3475
+ const depth = indentOf(opening.body).length;
3476
+ const { block } = collectBlock(lines, open + 1, (line) => line.body.trim().length === 0 || indentOf(line.body).length > depth);
3477
+ const entry = block.findIndex((line) => YML_IOS_ENTRY_PATTERN.test(line.body));
3478
+ return entry === -1 ? -1 : open + 1 + entry;
3479
+ }
3480
+ /**
3481
+ * Rewrites every `IPHONEOS_DEPLOYMENT_TARGET` of a generated `project.pbxproj`, the setting
3482
+ * `MinimumOSVersion` comes from.
3483
+ *
3484
+ * @param existing - The current `project.pbxproj` content.
3485
+ * @param version - The deployment target to write.
3486
+ * @returns The content with every setting on `version`.
3487
+ * @throws {Error} `[native]` when the file has no such line.
3488
+ * @example
3489
+ * ```ts
3490
+ * applyPbxprojDeploymentTarget("\tIPHONEOS_DEPLOYMENT_TARGET = 16.0;\n", "26.0");
3491
+ * // "\tIPHONEOS_DEPLOYMENT_TARGET = 26.0;\n"
3492
+ * ```
3493
+ */
3494
+ function applyPbxprojDeploymentTarget(existing, version) {
3495
+ if (existing.search(PBXPROJ_DEPLOYMENT_PATTERN) === -1) throw missingAnchorError("IPHONEOS_DEPLOYMENT_TARGET", PBXPROJ_FILE);
3496
+ return existing.replaceAll(PBXPROJ_DEPLOYMENT_PATTERN, (_match, assignment) => `${assignment}${version};`);
3497
+ }
3498
+ /**
3499
+ * Rewrites `deploymentTarget.iOS` in a generated `project.yml`.
3500
+ *
3501
+ * @param existing - The current `project.yml` content.
3502
+ * @param version - The deployment target to write.
3503
+ * @returns The content with the entry on `version`.
3504
+ * @throws {Error} `[native]` when the file has no such entry.
3505
+ * @example
3506
+ * ```ts
3507
+ * applyProjectYmlDeploymentTarget(" deploymentTarget:\n iOS: 16.0\n", "26.0");
3508
+ * // " deploymentTarget:\n iOS: 26.0\n"
3509
+ * ```
3510
+ */
3511
+ function applyProjectYmlDeploymentTarget(existing, version) {
3512
+ const lines = splitLines$1(existing);
3513
+ const index = ymlDeploymentEntry(lines);
3514
+ const entry = lines[index];
3515
+ if (!entry) throw missingAnchorError("deploymentTarget.iOS", PROJECT_YML_FILE);
3516
+ const body = entry.body.replace(YML_IOS_ENTRY_PATTERN, (_match, key) => `${key}${version}`);
3517
+ return joinLines(lines.with(index, {
3518
+ body,
3519
+ ending: entry.ending
3520
+ }));
3521
+ }
3522
+ /**
3523
+ * Keeps the privacy manifest in a generated `project.pbxproj`: a `PBXBuildFile`, a
3524
+ * `PBXFileReference`, a child of the root group and an entry in the Resources phase. Every
3525
+ * line carrying one of the two fixed ids is dropped first, so a second pass is a no-op and
3526
+ * `enabled: false` gives back the file as it was, needing no anchor.
3527
+ *
3528
+ * @param existing - The current `project.pbxproj` content.
3529
+ * @param enabled - Whether the app carries a manifest.
3530
+ * @returns The content with the four lines, or without them.
3531
+ * @throws {Error} `[native]` when `enabled` and the file lacks an anchor.
3532
+ * @example
3533
+ * ```ts
3534
+ * applyPbxprojPrivacyManifest("// !$*UTF8*$!\n", false); // "// !$*UTF8*$!\n"
3535
+ * ```
3536
+ */
3537
+ function applyPbxprojPrivacyManifest(existing, enabled) {
3538
+ const lines = splitLines$1(existing).filter((line) => !line.body.includes(PRIVACY_BUILD_FILE_ID) && !line.body.includes(PRIVACY_FILE_REFERENCE_ID));
3539
+ if (!enabled) return joinLines(lines);
3540
+ const inserted = /* @__PURE__ */ new Map([
3541
+ [sectionBounds(lines, "PBXBuildFile").end, BUILD_FILE_LINE],
3542
+ [sectionBounds(lines, "PBXFileReference").end, FILE_REFERENCE_LINE],
3543
+ [rootGroupChildren(lines) + 1, GROUP_CHILD_LINE],
3544
+ [resourcesFiles(lines) + 1, RESOURCES_FILE_LINE]
3545
+ ]);
3546
+ return joinLines(lines.flatMap((line, index) => {
3547
+ const body = inserted.get(index);
3548
+ return body === void 0 ? [line] : [{
3549
+ body,
3550
+ ending: line.ending
3551
+ }, line];
3552
+ }));
3553
+ }
3554
+ /**
3555
+ * Tests whether a `project.yml` line is the first line of the manifest's list entry.
3556
+ *
3557
+ * @param line - The line, or undefined past either end of the file.
3558
+ * @returns Whether it is that line.
3559
+ * @example
3560
+ * ```ts
3561
+ * isYmlPrivacyPath({ body: " - path: PrivacyInfo.xcprivacy", ending: "\n" }); // true
3562
+ * ```
3563
+ */
3564
+ function isYmlPrivacyPath(line) {
3565
+ return line?.body.trim() === YML_PRIVACY_PATH_LINE;
3566
+ }
3567
+ /**
3568
+ * Drops the manifest's list entry from `project.yml`: the path line, and the `buildPhase`
3569
+ * line right after it, never the same line of another entry.
3570
+ *
3571
+ * @param lines - Every line of the file.
3572
+ * @returns The lines without the entry.
3573
+ * @example
3574
+ * ```ts
3575
+ * dropYmlPrivacyEntry(splitLines("- path: PrivacyInfo.xcprivacy\n buildPhase: resources\n")); // []
3576
+ * ```
3577
+ */
3578
+ function dropYmlPrivacyEntry(lines) {
3579
+ return lines.filter((line, index) => {
3580
+ if (isYmlPrivacyPath(line)) return false;
3581
+ return !(isYmlPrivacyPath(lines[index - 1]) && line.body.trim() === YML_RESOURCES_PHASE_LINE);
3582
+ });
3583
+ }
3584
+ /**
3585
+ * Finds the first entry of the app target's `sources:` list: the first `sources:` after the
3586
+ * top-level `targets:` line. A `targetTemplates` block carries its own one above that line.
3587
+ *
3588
+ * @param lines - Every line of the file.
3589
+ * @returns The first entry's index and line.
3590
+ * @throws {Error} `[native]` when there is no such list.
3591
+ * @example
3592
+ * ```ts
3593
+ * firstTargetSource(splitLines("targets:\n app:\n sources:\n - path: Sources\n")).index; // 3
3594
+ * ```
3595
+ */
3596
+ function firstTargetSource(lines) {
3597
+ const targets = lines.findIndex((line) => line.body.trimEnd() === YML_TARGETS_LINE);
3598
+ const sources = findLine(lines, (body) => YML_SOURCES_PATTERN.test(body), targets + 1, lines.length);
3599
+ const index = sources + 1;
3600
+ const line = lines[index];
3601
+ const hasSourcesList = targets !== -1 && sources !== -1 && YML_LIST_ITEM_PATTERN.test(line?.body ?? "");
3602
+ if (!line || !hasSourcesList) throw missingAnchorError("the target's sources list", PROJECT_YML_FILE);
3603
+ return {
3604
+ index,
3605
+ line
3606
+ };
3607
+ }
3608
+ /**
3609
+ * Keeps the privacy manifest in a generated `project.yml`, as the first entry of the app
3610
+ * target's sources, so a later xcodegen writes it back into the pbxproj. The entry is
3611
+ * dropped first, so a second pass is a no-op and `enabled: false` gives back the file as it
3612
+ * was, needing no anchor.
3613
+ *
3614
+ * @param existing - The current `project.yml` content.
3615
+ * @param enabled - Whether the app carries a manifest.
3616
+ * @returns The content with the entry, or without it.
3617
+ * @throws {Error} `[native]` when `enabled` and the file has no target sources list.
3618
+ * @example
3619
+ * ```ts
3620
+ * applyProjectYmlPrivacyManifest("name: app\n", false); // "name: app\n"
3621
+ * ```
3622
+ */
3623
+ function applyProjectYmlPrivacyManifest(existing, enabled) {
3624
+ const lines = dropYmlPrivacyEntry(splitLines$1(existing));
3625
+ if (!enabled) return joinLines(lines);
3626
+ const { index, line } = firstTargetSource(lines);
3627
+ const indent = indentOf(line.body);
3628
+ return joinLines(lines.toSpliced(index, 0, {
3629
+ body: `${indent}${YML_PRIVACY_PATH_LINE}`,
3630
+ ending: line.ending
3631
+ }, {
3632
+ body: `${indent}${YML_ENTRY_INDENT}${YML_RESOURCES_PHASE_LINE}`,
3633
+ ending: line.ending
3634
+ }));
3635
+ }
3636
+ /**
3637
+ * Reads the privacy manifest `ios.privacyManifest` names, as bytes: a binary plist is legal.
3638
+ * The patch pass calls it first, so a missing source is refused before anything is written.
3639
+ *
3640
+ * @param source - `ios.privacyManifest`, or undefined when unset.
3641
+ * @returns The manifest's bytes, or undefined when the option is unset.
3642
+ * @throws {Error} `[native] ios.privacyManifest "<path>" was not found.`
3643
+ * @example
3644
+ * ```ts
3645
+ * await readPrivacyManifest(undefined); // undefined
3646
+ * ```
3647
+ */
3648
+ async function readPrivacyManifest(source) {
3649
+ if (source === void 0) return void 0;
3650
+ if (!existsSync(source)) throw new Error(`[native] ios.privacyManifest "${source}" was not found.\n Point config.ios.privacyManifest at the manifest file, or unset it.`);
3651
+ return readFile(source);
3652
+ }
3653
+ /**
3654
+ * Rewrites every generated iOS project file. All of them are transformed before the first
3655
+ * write, so a file that refuses leaves the tree as it was.
3656
+ *
3657
+ * @param projectDirectory - The Tauri project root.
3658
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
3659
+ * @param transform - Rewrites one file's content; its second argument says whether the file
3660
+ * is `project.yml`.
3661
+ * @returns The paths patched vs. left unchanged.
3662
+ * @throws {Error} What the transform throws.
3663
+ */
3664
+ async function rewriteProjectFiles(projectDirectory, genDirectory, transform) {
3665
+ const rewrites = [];
3666
+ for (const file of await iosPatchFiles(genDirectory)) {
3667
+ const existing = await readFile(file, "utf8");
3668
+ rewrites.push({
3669
+ file,
3670
+ content: transform(existing, file.endsWith(".yml"))
3671
+ });
3672
+ }
3673
+ const patched = [];
3674
+ const unchanged = [];
3675
+ for (const { file, content } of rewrites) (await writeIfChanged(file, content, projectDirectory) === "written" ? patched : unchanged).push(file);
3676
+ return {
3677
+ patched,
3678
+ unchanged
3679
+ };
3680
+ }
3681
+ /**
3682
+ * Moves a kept iOS tree to the configured deployment target, in `project.yml` and each
3683
+ * `project.pbxproj`. Idempotent: a second pass reports every file unchanged.
3684
+ *
3685
+ * @param projectDirectory - The Tauri project root.
3686
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
3687
+ * @param version - The deployment target to write.
3688
+ * @returns The paths patched vs. left unchanged.
3689
+ * @throws {Error} `[native]` when a file has no deployment target line.
3690
+ * @example
3691
+ * ```ts
3692
+ * await patchDeploymentTarget(projectDir, path.join(projectDir, "src-tauri/gen/apple"), "26.0");
3693
+ * // { patched: [".../gen/apple/project.yml", ".../gen/apple/app.xcodeproj/project.pbxproj"], unchanged: [] }
3694
+ * ```
3695
+ */
3696
+ async function patchDeploymentTarget(projectDirectory, genDirectory, version) {
3697
+ return rewriteProjectFiles(projectDirectory, genDirectory, (text, isProjectYml) => isProjectYml ? applyProjectYmlDeploymentTarget(text, version) : applyPbxprojDeploymentTarget(text, version));
3698
+ }
3699
+ /**
3700
+ * Keeps the privacy manifest of a kept iOS tree: with bytes, `gen/apple/PrivacyInfo.xcprivacy`
3701
+ * holds them and `project.yml` and each `project.pbxproj` name it; without, the entries go
3702
+ * and so does the file, so the option can be dropped. A tree with no project file gets
3703
+ * nothing: no file would name the manifest. Idempotent: a second pass changes nothing.
3704
+ *
3705
+ * @param projectDirectory - The Tauri project root.
3706
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
3707
+ * @param manifest - The bytes from {@link readPrivacyManifest}, undefined when unset.
3708
+ * @returns The paths patched vs. left unchanged; a removed manifest counts as patched.
3709
+ * @throws {Error} `[native]` when a manifest meets a project file that lacks an anchor.
3710
+ * @example
3711
+ * ```ts
3712
+ * await patchPrivacyManifest(projectDir, genDir, await readPrivacyManifest("/repo/PrivacyInfo.xcprivacy"));
3713
+ * ```
3714
+ */
3715
+ async function patchPrivacyManifest(projectDirectory, genDirectory, manifest) {
3716
+ const enabled = manifest !== void 0;
3717
+ const { patched, unchanged } = await rewriteProjectFiles(projectDirectory, genDirectory, (text, isProjectYml) => isProjectYml ? applyProjectYmlPrivacyManifest(text, enabled) : applyPbxprojPrivacyManifest(text, enabled));
3718
+ if (patched.length + unchanged.length === 0) return {
3719
+ patched,
3720
+ unchanged
3721
+ };
3722
+ const manifestPath = iosPrivacyManifestPath(genDirectory);
3723
+ if (manifest !== void 0) {
3724
+ if (await writeIfChanged(manifestPath, manifest, projectDirectory) === "written") return {
3725
+ patched: [...patched, manifestPath],
3726
+ unchanged
3727
+ };
3728
+ return {
3729
+ patched,
3730
+ unchanged: [...unchanged, manifestPath]
3731
+ };
3732
+ }
3733
+ if (!existsSync(manifestPath)) return {
3734
+ patched,
3735
+ unchanged
3736
+ };
3737
+ await rm(manifestPath, { force: true });
3738
+ return {
3739
+ patched: [...patched, manifestPath],
3740
+ unchanged
3741
+ };
3742
+ }
3743
+ //#endregion
3744
+ //#region src/plugins/project/mobile/manifest.ts
3745
+ /**
3746
+ * @file project plugin — the Android manifest patch. Tauri has no config key for what the
3747
+ * main activity carries (`android:screenOrientation` among them), so the mobile patch pass
3748
+ * sets those attributes on the `<activity>` of the generated
3749
+ * `gen/android/app/src/main/AndroidManifest.xml` itself. The same rules set attributes on
3750
+ * the `<application>` start tag (the debug profile's network security config).
3751
+ *
3752
+ * The transform is a pure text function: only the touched attribute changes, every other
3753
+ * byte (line endings and indentation included) survives, and a second pass is a no-op.
3754
+ */
3755
+ /** Where `tauri android init` writes the app manifest, below `gen/android`. */
3756
+ const MANIFEST_PATH_SEGMENTS = [
3757
+ "app",
3758
+ "src",
3759
+ "main",
3760
+ "AndroidManifest.xml"
3761
+ ];
3762
+ /** The tag name the application start tag opens with. */
3763
+ const APPLICATION_OPEN = "<application";
3764
+ /** Where an `<application` start tag opens. */
3765
+ const APPLICATION_OPEN_PATTERN = /<application(?=[\s/>])/;
3766
+ /** The tag name an activity start tag opens with. */
3767
+ const ACTIVITY_OPEN = "<activity";
3768
+ /** The end tag that closes an activity's body. */
3769
+ const ACTIVITY_CLOSE = "</activity>";
3770
+ /** The intent action that marks the launcher activity. */
3771
+ const MAIN_ACTION = "android.intent.action.MAIN";
3772
+ /** Where an `<activity` start tag opens — `<activity-alias` is a different element. */
3773
+ const ACTIVITY_OPEN_PATTERN = /<activity(?=[\s/>])/g;
3774
+ /**
3775
+ * One attribute inside a start tag, from the whitespace character before it:
3776
+ * ` (name)="value"`. XML allows spaces around `=`, but no generated manifest writes them.
3777
+ */
3778
+ const ATTRIBUTE_PATTERN = /\s([\w:.-]+)=(?:"[^"]*"|'[^']*')/g;
3779
+ /** An XML comment — blanked before the scan, so a commented-out activity never counts. */
3780
+ const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
3781
+ /**
3782
+ * Builds the `[native]` error for a manifest whose main activity cannot be told apart.
3783
+ *
3784
+ * @param manifestPath - The manifest that was searched.
3785
+ * @returns A formatted `[native] ...` error.
3786
+ * @example
3787
+ * ```ts
3788
+ * throw mainActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
3789
+ * ```
3790
+ */
3791
+ function mainActivityError(manifestPath) {
3792
+ return /* @__PURE__ */ new Error(`[native] Could not find the main <activity> in ${manifestPath}.\n Re-run the mobile init pass (tauri android init) or report the manifest Tauri generated.`);
3793
+ }
3794
+ /**
3795
+ * Builds the `[native]` error for a manifest without an `<application>` element.
3796
+ *
3797
+ * @param manifestPath - The manifest that was searched.
3798
+ * @returns A formatted `[native] ...` error.
3799
+ * @example
3800
+ * ```ts
3801
+ * throw applicationError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
3802
+ * ```
3803
+ */
3804
+ function applicationError(manifestPath) {
3805
+ return /* @__PURE__ */ new Error(`[native] Could not find the <application> element in ${manifestPath}.\n Re-run the mobile init pass (tauri android init) or report the manifest Tauri generated.`);
3806
+ }
3807
+ /**
3808
+ * Finds where a start tag ends. A quoted attribute value is skipped whole, so a `>` inside
3809
+ * one never ends the tag.
3810
+ *
3811
+ * @param text - The manifest content.
3812
+ * @param from - Offset just past the tag name.
3813
+ * @returns The offset just past the closing `>`, or undefined for a tag that never closes.
3814
+ * @example
3815
+ * ```ts
3816
+ * startTagEnd('<activity android:label="a > b">', 9); // 32
3817
+ * ```
3818
+ */
3819
+ function startTagEnd(text, from) {
3820
+ let quote;
3821
+ for (let index = from; index < text.length; index += 1) {
3822
+ const character = text[index];
3823
+ if (quote !== void 0) {
3824
+ if (character === quote) quote = void 0;
3825
+ continue;
3826
+ }
3827
+ if (character === "\"" || character === "'") {
3828
+ quote = character;
3829
+ continue;
3830
+ }
3831
+ if (character === ">") return index + 1;
3832
+ }
3833
+ }
3834
+ /**
3835
+ * Locates every `<activity>` start tag and records whether its body declares MAIN.
3836
+ * Comments are blanked out first (same length, so every offset still points into the real
3837
+ * text), which keeps a commented-out activity from being counted or patched. A start tag
3838
+ * that never closes is not counted at all.
3839
+ *
3840
+ * @param text - The manifest content.
3841
+ * @returns One entry per activity, in file order.
3842
+ * @example
3843
+ * ```ts
3844
+ * locateActivities('<activity android:name=".A" /><activity android:name=".B"><action android:name="android.intent.action.MAIN" /></activity>');
3845
+ * // [{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]
3846
+ * ```
3847
+ */
3848
+ function locateActivities(text) {
3849
+ const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
3850
+ const activities = [];
3851
+ for (const match of masked.matchAll(ACTIVITY_OPEN_PATTERN)) {
3852
+ const start = match.index;
3853
+ const end = startTagEnd(masked, start + 9);
3854
+ if (end === void 0) continue;
3855
+ const body = masked.slice(start, end).endsWith("/>") ? "" : masked.slice(end, masked.indexOf(ACTIVITY_CLOSE, end));
3856
+ activities.push({
3857
+ start,
3858
+ end,
3859
+ isMain: body.includes(MAIN_ACTION)
3860
+ });
3861
+ }
3862
+ return activities;
3863
+ }
3864
+ /**
3865
+ * Picks the main activity: the one whose body declares MAIN. A manifest with a single
3866
+ * activity and no MAIN still has an obvious one; anything else is ambiguous.
3867
+ *
3868
+ * @param activities - Every activity in the manifest.
3869
+ * @returns The main activity, or undefined when none or several qualify.
3870
+ * @example
3871
+ * ```ts
3872
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]);
3873
+ * // { start: 30, end: 58, isMain: true }
3874
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: false }]); // undefined
3875
+ * ```
3876
+ */
3877
+ function mainActivity(activities) {
3878
+ const mains = activities.filter((activity) => activity.isMain);
3879
+ if (mains.length === 1) return mains[0];
3880
+ if (mains.length === 0 && activities.length === 1) return activities[0];
3881
+ }
3882
+ /**
3883
+ * Locates the first `<application>` start tag outside a comment.
3884
+ *
3885
+ * @param text - The manifest content.
3886
+ * @returns The tag's offsets, or undefined when there is none.
3887
+ * @example
3888
+ * ```ts
3889
+ * locateApplication('<manifest><application android:label="a"></application></manifest>');
3890
+ * // { start: 10, end: 40 }
3891
+ * ```
2960
3892
  */
2961
3893
  function locateApplication(text) {
2962
3894
  const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
@@ -4455,322 +5387,206 @@ async function patchAndroidSystemBars(projectDirectory, genDirectory, background
4455
5387
  unchanged: []
4456
5388
  } : {
4457
5389
  patched: [],
4458
- unchanged: [activity.path]
4459
- };
4460
- }
4461
- //#endregion
4462
- //#region src/plugins/project/mobile/xcode-settings.ts
4463
- /**
4464
- * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
4465
- *
4466
- * A capability plugin's build script rewrites the generated `<app>_iOS.entitlements` file
4467
- * while Xcode is compiling, and Xcode fails the second build on that:
4468
- * `Entitlements file "<app>_iOS.entitlements" was modified during the build, which is not
4469
- * supported`. Xcode names the way out itself — `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION`
4470
- * — so every `buildSettings` block of the generated `project.pbxproj` carries it, and the
4471
- * `project.yml` target carries it too, so a later xcodegen regeneration keeps it.
4472
- *
4473
- * Both transforms are pure text functions over the real generated shapes: line endings,
4474
- * indentation and every neighbouring line survive byte for byte, and a second pass is a
4475
- * no-op.
4476
- */
4477
- /** The Xcode build setting that permits a build script to rewrite the entitlements file. */
4478
- const ENTITLEMENTS_MODIFICATION_KEY = "CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION";
4479
- /** The pbxproj value form — Xcode writes booleans as `YES`/`NO`. */
4480
- const PBXPROJ_ENABLED_VALUE = "YES";
4481
- /**
4482
- * The project.yml value form. xcodegen renders a YAML boolean as `YES` in the pbxproj it
4483
- * generates, which is why the target's sibling settings read `true`/`false` there.
4484
- */
4485
- const YML_ENABLED_VALUE = "true";
4486
- /** Opens one settings block inside a `XCBuildConfiguration` section. */
4487
- const BUILD_SETTINGS_OPEN_PATTERN = /^([ \t]*)buildSettings = \{[ \t]*$/;
4488
- /** The setting, already present as a pbxproj assignment (whatever its value). */
4489
- const PBXPROJ_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*=`);
4490
- /** The setting, already present as a YAML key (whatever its value). */
4491
- const YML_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*:`);
4492
- /** Opens a target's `settings:` mapping in `project.yml`. */
4493
- const YML_SETTINGS_PATTERN = /^([ \t]*)settings:[ \t]*$/;
4494
- /** Opens the `base:` mapping a `settings:` block carries its own build settings in. */
4495
- const YML_BASE_PATTERN = /^([ \t]*)base:[ \t]*$/;
4496
- /** The leading whitespace of a line — never matches a line break. */
4497
- const INDENT_PATTERN = /^[ \t]*/;
4498
- /** Splits text into lines, keeping each line's own terminator attached to it. */
4499
- const LINE_SPLIT_PATTERN = /(?<=\n)/;
4500
- /** A line's terminator (LF or CRLF), stripped to compare the line's text alone. */
4501
- const LINE_ENDING_PATTERN = /\r?\n$/;
4502
- /** One indentation step inside a pbxproj — the generated file is tab-indented. */
4503
- const PBXPROJ_NESTED_INDENT = " ";
4504
- /** One indentation step inside a project.yml — YAML mappings never indent with tabs. */
4505
- const YML_NESTED_INDENT = " ";
4506
- /**
4507
- * Splits text into lines that each remember their own terminator, so a file mixing (or
4508
- * using) CRLF comes back out exactly as it went in.
4509
- *
4510
- * @param text - The file content.
4511
- * @returns One entry per line, in order.
4512
- * @example
4513
- * ```ts
4514
- * splitLines("a\r\nb"); // [{ body: "a", ending: "\r\n" }, { body: "b", ending: "" }]
4515
- * ```
4516
- */
4517
- function splitLines$1(text) {
4518
- return text.split(LINE_SPLIT_PATTERN).map((chunk) => {
4519
- const body = chunk.replace(LINE_ENDING_PATTERN, "");
4520
- return {
4521
- body,
4522
- ending: chunk.slice(body.length)
4523
- };
4524
- });
4525
- }
4526
- /**
4527
- * Joins lines back into file content.
4528
- *
4529
- * @param lines - The lines to join.
4530
- * @returns The file content.
4531
- * @example
4532
- * ```ts
4533
- * joinLines([{ body: "a", ending: "\n" }]); // "a\n"
4534
- * ```
4535
- */
4536
- function joinLines(lines) {
4537
- return lines.map((line) => line.body + line.ending).join("");
4538
- }
4539
- /**
4540
- * Reads a line's leading whitespace — the indentation a new sibling line has to match.
4541
- *
4542
- * @param body - The line's text.
4543
- * @returns The leading spaces/tabs, possibly empty.
4544
- * @example
4545
- * ```ts
4546
- * indentOf("\t\t\tisa = XCBuildConfiguration;"); // "\t\t\t"
4547
- * ```
4548
- */
4549
- function indentOf(body) {
4550
- return INDENT_PATTERN.exec(body)?.[0] ?? "";
5390
+ unchanged: [activity.path]
5391
+ };
4551
5392
  }
4552
- /**
4553
- * Returns a block that carries the setting exactly once: an assignment already there is
4554
- * rewritten in place (a block that turned the setting OFF would still break the rebuild),
4555
- * and an absent one is inserted as the block's first entry, at its siblings' indentation.
4556
- *
4557
- * @param block - The lines inside the block, without its opening and closing line.
4558
- * @param options - How to place the setting.
4559
- * @param options.present - Matches an assignment of the setting already in the block.
4560
- * @param options.render - Renders the setting line at a given indentation.
4561
- * @param options.fallbackIndent - Indentation used when the block carries no line to match.
4562
- * @param options.fallbackEnding - Terminator used when the block carries no line to match.
4563
- * @returns The block's lines, with the setting present exactly once.
5393
+ //#endregion
5394
+ //#region src/plugins/project/mobile/window-background.ts
5395
+ /**
5396
+ * @file project plugin — the Android window background patch. The generated app theme
5397
+ * (`Theme.Material3.DayNight.NoActionBar`) sets no window background, so between the
5398
+ * system's icon splash and the WebView's first paint the activity window shows the theme's
5399
+ * default, dark in night mode: a dark flash at every launch. When `app.backgroundColor` is
5400
+ * set, this patch writes that colour as a moku-owned colour resource and points the app
5401
+ * theme's `android:windowBackground` and `android:windowSplashScreenBackground` (the
5402
+ * Android 12+ icon splash) at it, in every `res/values*\/themes.xml` that holds the theme.
5403
+ *
5404
+ * Every line and file this patch writes carries {@link MARKER}, so a pass first strips its
5405
+ * own lines and then writes them again: a second pass is a no-op, other bytes (line endings
5406
+ * included) survive, and unsetting the colour restores the generated files.
5407
+ */
5408
+ /** Marks every line and file this patch owns. */
5409
+ const MARKER = "<!-- moku:native window background -->";
5410
+ /** The colour resource the theme items point at. */
5411
+ const COLOUR_NAME = "moku_window_background";
5412
+ /** The unqualified resource directory: the day theme and the colour resource live there. */
5413
+ const VALUES_DIRECTORY = "values";
5414
+ /** The theme file `tauri android init` writes per resource qualifier. */
5415
+ const THEMES_FILE = "themes.xml";
5416
+ /** `#rrggbb` or `#rrggbbaa`: the colour and the optional alpha, captured apart. */
5417
+ const HEX_COLOUR_PATTERN$1 = /^#([\da-f]{6})([\da-f]{2})?$/i;
5418
+ /** The prefix `android:theme` names the app theme with. */
5419
+ const STYLE_REFERENCE_PREFIX = "@style/";
5420
+ /** The theme items, in the order they are written: window first, then the icon splash. */
5421
+ const THEME_ITEMS = [`<item name="android:windowBackground">@color/${COLOUR_NAME}</item>`, `<item name="android:windowSplashScreenBackground" tools:targetApi="31">@color/${COLOUR_NAME}</item>`];
5422
+ /** One level of indentation, for a style with no child line to copy it from. */
5423
+ const INDENT_STEP = " ";
5424
+ /** The leading spaces and tabs of a line. */
5425
+ const INDENT_PATTERN = /^[\t ]*/;
5426
+ /**
5427
+ * Builds the `[native]` error for a generated file this patch needs and cannot use.
5428
+ *
5429
+ * @param problem - What is wrong, starting with the file path.
5430
+ * @returns A formatted `[native] ...` error.
4564
5431
  * @example
4565
5432
  * ```ts
4566
- * placeSetting(block, { present: PBXPROJ_SETTING_PATTERN, render, fallbackIndent, fallbackEnding });
5433
+ * throw initError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res/values/themes.xml not found");
4567
5434
  * ```
4568
5435
  */
4569
- function placeSetting(block, options) {
4570
- const { present, render, fallbackIndent, fallbackEnding } = options;
4571
- const existingIndex = block.findIndex((line) => present.test(line.body));
4572
- if (existingIndex !== -1) return block.map((line, index) => index === existingIndex ? {
4573
- body: render(indentOf(line.body)),
4574
- ending: line.ending
4575
- } : line);
4576
- const sibling = block.find((line) => line.body.trim().length > 0);
4577
- return [{
4578
- body: render(sibling ? indentOf(sibling.body) : fallbackIndent),
4579
- ending: sibling?.ending ?? fallbackEnding
4580
- }, ...block];
5436
+ function initError(problem) {
5437
+ return /* @__PURE__ */ new Error(`[native] ${problem}.\n Re-run the mobile init pass (tauri android init), or unset app.backgroundColor.`);
4581
5438
  }
4582
5439
  /**
4583
- * Collects the lines of one block, starting at `start` and stopping at the first line the
4584
- * block does not own.
5440
+ * Converts `app.backgroundColor` to Android's colour notation, which puts the alpha first.
4585
5441
  *
4586
- * @param lines - Every line of the file.
4587
- * @param start - Index of the block's first line.
4588
- * @param isMember - Whether a line still belongs to the block.
4589
- * @returns The block's lines, and the index of the first line after it.
5442
+ * @param colour - `#rrggbb` or `#rrggbbaa`.
5443
+ * @returns `#rrggbb` unchanged, or `#aarrggbb`.
5444
+ * @throws {Error} `[native]` when the value is not a hex colour.
4590
5445
  * @example
4591
5446
  * ```ts
4592
- * const { block, next } = collectBlock(lines, index, line => line.body !== "\t\t\t};");
5447
+ * androidColour("#10161d"); // "#10161d"
5448
+ * androidColour("#10161d80"); // "#8010161d"
4593
5449
  * ```
4594
5450
  */
4595
- function collectBlock(lines, start, isMember) {
4596
- const block = [];
4597
- let index = start;
4598
- while (index < lines.length) {
4599
- const line = lines[index];
4600
- if (!line || !isMember(line)) break;
4601
- block.push(line);
4602
- index += 1;
4603
- }
4604
- return {
4605
- block,
4606
- next: index
4607
- };
5451
+ function androidColour(colour) {
5452
+ const match = HEX_COLOUR_PATTERN$1.exec(colour);
5453
+ if (!match) throw new Error(`[native] app.backgroundColor "${colour}" is not a valid colour.\n Use a hex colour such as "#10161d".`);
5454
+ const [, rgb = "", alpha = ""] = match;
5455
+ return `#${alpha}${rgb}`;
4608
5456
  }
4609
5457
  /**
4610
- * Renders the setting as a pbxproj assignment.
5458
+ * Sets or clears the window background items of one `themes.xml`. The patch's own lines are
5459
+ * removed first; when enabled, the items go right after the start tag of the named style,
5460
+ * at the indentation of the line that follows it.
4611
5461
  *
4612
- * @param indent - The indentation its sibling settings use.
4613
- * @returns The assignment line.
5462
+ * @param source - The `themes.xml` content.
5463
+ * @param styleName - The app theme, as `android:theme` names it without `@style/`.
5464
+ * @param enabled - Whether `app.backgroundColor` is set.
5465
+ * @param filePath - The `themes.xml` path, named in the error.
5466
+ * @returns The content with the items applied.
5467
+ * @throws {Error} `[native]` when enabled and the file holds no such style.
4614
5468
  * @example
4615
5469
  * ```ts
4616
- * renderPbxprojSetting("\t\t\t\t"); // "\t\t\t\tCODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;"
5470
+ * applyWindowBackground('<resources>\n <style name="Theme.app" parent="P">\n </style>\n</resources>\n', "Theme.app", true, "themes.xml");
5471
+ * // the same file with the window and splash items as the style's first two lines
4617
5472
  * ```
4618
5473
  */
4619
- function renderPbxprojSetting(indent) {
4620
- return `${indent}${ENTITLEMENTS_MODIFICATION_KEY} = ${PBXPROJ_ENABLED_VALUE};`;
5474
+ function applyWindowBackground(source, styleName, enabled, filePath) {
5475
+ const lines = source.split("\n").filter((line) => !line.includes(MARKER));
5476
+ if (!enabled) return lines.join("\n");
5477
+ const index = lines.findIndex((line) => line.includes(`<style name="${styleName}"`));
5478
+ if (index === -1) throw initError(`${filePath} has no <style name="${styleName}"> to set the window background in`);
5479
+ const styleIndent = INDENT_PATTERN.exec(lines[index] ?? "")?.[0] ?? "";
5480
+ const nextIndent = INDENT_PATTERN.exec(lines[index + 1] ?? "")?.[0] ?? "";
5481
+ const indent = nextIndent.length > styleIndent.length ? nextIndent : styleIndent + INDENT_STEP;
5482
+ const carriageReturn = source.includes("\r\n") ? "\r" : "";
5483
+ const items = THEME_ITEMS.map((item) => `${indent}${item} ${MARKER}${carriageReturn}`);
5484
+ return [
5485
+ ...lines.slice(0, index + 1),
5486
+ ...items,
5487
+ ...lines.slice(index + 1)
5488
+ ].join("\n");
4621
5489
  }
4622
5490
  /**
4623
- * Renders the setting as a YAML mapping entry.
5491
+ * Builds the moku-owned colour resource file.
4624
5492
  *
4625
- * @param indent - The indentation its sibling entries use.
4626
- * @returns The entry line.
5493
+ * @param colour - The colour in Android notation.
5494
+ * @returns The `moku_window_background.xml` content.
4627
5495
  * @example
4628
5496
  * ```ts
4629
- * renderYmlSetting(" "); // " CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: true"
5497
+ * colourResource("#10161d"); // a <resources> file with <color name="moku_window_background">#10161d</color>
4630
5498
  * ```
4631
5499
  */
4632
- function renderYmlSetting(indent) {
4633
- return `${indent}${ENTITLEMENTS_MODIFICATION_KEY}: ${YML_ENABLED_VALUE}`;
5500
+ function colourResource(colour) {
5501
+ return [
5502
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
5503
+ MARKER,
5504
+ "<resources>",
5505
+ ` <color name="${COLOUR_NAME}">${colour}</color>`,
5506
+ "</resources>",
5507
+ ""
5508
+ ].join("\n");
4634
5509
  }
4635
5510
  /**
4636
- * Reads the `base:` mapping a target's `settings:` line opens — the one block in
4637
- * `project.yml` that holds build settings.
4638
- *
4639
- * The block is walked, not peeked at: `base:` is a direct child of `settings:`, but not
4640
- * necessarily the FIRST one — xcodegen is equally happy with `settings:` followed by
4641
- * `groups: [app]` and `base:` below it. So every line indented deeper than `settings:` is
4642
- * scanned until the block dedents, and the first `base:` sitting at the direct-child level
4643
- * wins; a nested `base:` deeper inside somebody else's sub-mapping does not. A `settings:`
4644
- * block carrying no `base:` at all owns no such block and is left alone.
5511
+ * Lists every `res/values*\/themes.xml` of the tree, sorted, so `values` comes first.
4645
5512
  *
4646
- * @param lines - Every line of the file.
4647
- * @param settingsIndex - Index of the candidate `settings:` line.
4648
- * @returns The `base:` line, its index and its indentation, or undefined when there is none.
4649
- * @example
4650
- * ```ts
4651
- * baseMappingAt(splitLines(" settings:\n groups: [app]\n base:\n"), 0);
4652
- * ```
5513
+ * @param resourceDirectory - The `app/src/main/res` directory.
5514
+ * @returns The theme files found, possibly none.
4653
5515
  */
4654
- function baseMappingAt(lines, settingsIndex) {
4655
- const settingsLine = lines[settingsIndex];
4656
- const settings = settingsLine && YML_SETTINGS_PATTERN.exec(settingsLine.body);
4657
- if (!settings) return void 0;
4658
- const settingsIndent = (settings[1] ?? "").length;
4659
- let childIndent;
4660
- for (let index = settingsIndex + 1; index < lines.length; index += 1) {
4661
- const line = lines[index];
4662
- if (!line) break;
4663
- if (line.body.trim().length === 0) continue;
4664
- const indent = indentOf(line.body);
4665
- if (indent.length <= settingsIndent) break;
4666
- childIndent ??= indent.length;
4667
- if (indent.length !== childIndent) continue;
4668
- if (YML_BASE_PATTERN.test(line.body)) return {
4669
- line,
4670
- index,
4671
- indent
4672
- };
4673
- }
5516
+ async function themeFiles(resourceDirectory) {
5517
+ if (!existsSync(resourceDirectory)) return [];
5518
+ return (await readdir(resourceDirectory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name.startsWith(VALUES_DIRECTORY)).map((entry) => entry.name).toSorted().map((name) => path.join(resourceDirectory, name, THEMES_FILE)).filter((file) => existsSync(file));
4674
5519
  }
4675
5520
  /**
4676
- * Adds `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;` to every `buildSettings` block of
4677
- * a generated `project.pbxproj`, exactly once per block and at the indentation its sibling
4678
- * settings use. Content outside those blocks — the shell-script build phase included — is
4679
- * returned byte for byte, and a file that already carries the setting comes back unchanged.
5521
+ * Reads the app theme's style name from the manifest's `<application android:theme>`.
4680
5522
  *
4681
- * @param existing - The current `project.pbxproj` content.
4682
- * @returns The content with the setting in every settings block.
4683
- * @example
4684
- * ```ts
4685
- * applyPbxprojEntitlementsSetting(await readFile(pbxprojPath, "utf8"));
4686
- * ```
5523
+ * @param genDirectory - The `src-tauri/gen/android` directory.
5524
+ * @returns The style name without `@style/`.
5525
+ * @throws {Error} `[native]` when the manifest is missing or names no style.
4687
5526
  */
4688
- function applyPbxprojEntitlementsSetting(existing) {
4689
- const lines = splitLines$1(existing);
4690
- const patched = [];
4691
- let index = 0;
4692
- while (index < lines.length) {
4693
- const line = lines[index];
4694
- if (!line) break;
4695
- patched.push(line);
4696
- index += 1;
4697
- const opening = BUILD_SETTINGS_OPEN_PATTERN.exec(line.body);
4698
- if (!opening) continue;
4699
- const blockIndent = opening[1] ?? "";
4700
- const closing = `${blockIndent}};`;
4701
- const { block, next } = collectBlock(lines, index, (inner) => inner.body !== closing);
4702
- index = next;
4703
- patched.push(...placeSetting(block, {
4704
- present: PBXPROJ_SETTING_PATTERN,
4705
- render: renderPbxprojSetting,
4706
- fallbackIndent: `${blockIndent}${PBXPROJ_NESTED_INDENT}`,
4707
- fallbackEnding: line.ending
4708
- }));
4709
- }
4710
- return joinLines(patched);
5527
+ async function appThemeName(genDirectory) {
5528
+ const manifestPath = androidManifestPath(genDirectory);
5529
+ if (!existsSync(manifestPath)) throw initError(`${manifestPath} not found`);
5530
+ const theme = applicationAttribute(await readFile(manifestPath, "utf8"), "android:theme");
5531
+ if (!theme?.startsWith(STYLE_REFERENCE_PREFIX)) throw initError(`${manifestPath} names no android:theme on <application> to set the window background in`);
5532
+ return theme.slice(7);
4711
5533
  }
4712
5534
  /**
4713
- * Adds the setting to every target's `settings.base` block in a generated `project.yml`, so
4714
- * an xcodegen regeneration writes it back into the pbxproj. Only a `base:` mapping that is a
4715
- * direct child of a `settings:` mapping is touched — a `settingGroups:` block is somebody
4716
- * else's. A blank line inside the block does not end it: YAML mappings end at a dedent, so
4717
- * an entry printed below an empty line is still seen and never duplicated.
5535
+ * Writes or removes the moku-owned colour resource. A file without the marker is someone
5536
+ * else's and is never touched.
4718
5537
  *
4719
- * @param existing - The current `project.yml` content.
4720
- * @returns The content with the setting under each target's `settings.base`.
4721
- * @example
4722
- * ```ts
4723
- * applyProjectYmlEntitlementsSetting(await readFile(projectYmlPath, "utf8"));
4724
- * ```
4725
- */
4726
- function applyProjectYmlEntitlementsSetting(existing) {
4727
- const lines = splitLines$1(existing);
4728
- const patched = [];
4729
- let index = 0;
4730
- while (index < lines.length) {
4731
- const line = lines[index];
4732
- if (!line) break;
4733
- const base = baseMappingAt(lines, index);
4734
- patched.push(line);
4735
- index += 1;
4736
- if (!base) continue;
4737
- patched.push(...lines.slice(index, base.index + 1));
4738
- index = base.index + 1;
4739
- const { block, next } = collectBlock(lines, index, (entry) => entry.body.trim().length === 0 || indentOf(entry.body).length > base.indent.length);
4740
- index = next;
4741
- patched.push(...placeSetting(block, {
4742
- present: YML_SETTING_PATTERN,
4743
- render: renderYmlSetting,
4744
- fallbackIndent: `${base.indent}${YML_NESTED_INDENT}`,
4745
- fallbackEnding: base.line.ending
4746
- }));
5538
+ * @param projectDirectory - The Tauri project root.
5539
+ * @param colourPath - The `res/values/moku_window_background.xml` path.
5540
+ * @param colour - The colour in Android notation, or undefined to remove the file.
5541
+ * @param result - The lists the path is recorded in.
5542
+ * @returns Resolves once the file is in place or gone.
5543
+ */
5544
+ async function syncColourFile(projectDirectory, colourPath, colour, result) {
5545
+ if (colour !== void 0) {
5546
+ (await writeIfChanged(colourPath, colourResource(colour), projectDirectory) === "written" ? result.patched : result.unchanged).push(colourPath);
5547
+ return;
4747
5548
  }
4748
- return joinLines(patched);
5549
+ if (!existsSync(colourPath)) return;
5550
+ if (!(await readFile(colourPath, "utf8")).includes(MARKER)) return;
5551
+ await rm(colourPath, { force: true });
5552
+ result.patched.push(colourPath);
4749
5553
  }
4750
5554
  /**
4751
- * Applies the entitlements-modification setting to every generated iOS project file —
4752
- * `project.yml` and each `*.xcodeproj/project.pbxproj`. Idempotent: a second pass reports
4753
- * every file unchanged. Nothing under `gen/apple/build` is ever read or written.
5555
+ * Sets the Android window and icon-splash background from `app.backgroundColor`, through
5556
+ * the write-if-changed writer: the colour resource, then every `themes.xml` in sorted order.
5557
+ * Without a colour the patch's own lines and file are removed, and a tree it never touched
5558
+ * is left as it is.
4754
5559
  *
4755
5560
  * @param projectDirectory - The Tauri project root.
4756
- * @param genDirectory - The `src-tauri/gen/apple` directory.
4757
- * @returns The paths patched vs. left unchanged.
5561
+ * @param genDirectory - The `src-tauri/gen/android` directory.
5562
+ * @param backgroundColor - `app.backgroundColor`, or undefined when unset.
5563
+ * @returns The colour file and theme files, patched or unchanged.
5564
+ * @throws {Error} `[native]` when a colour is set and the manifest names no app theme, the
5565
+ * `res/values/themes.xml` is missing, or it lacks the app theme.
4758
5566
  * @example
4759
5567
  * ```ts
4760
- * await patchXcodeSettings(projectDir, path.join(projectDir, "src-tauri/gen/apple"));
5568
+ * // First pass on the generated tree; a second pass lists every file under `unchanged`.
5569
+ * await patchAndroidWindowBackground(".moku/tauri", ".moku/tauri/src-tauri/gen/android", "#10161d");
5570
+ * // { patched: [".../values/moku_window_background.xml", ".../values/themes.xml", ".../values-night/themes.xml"], unchanged: [] }
4761
5571
  * ```
4762
5572
  */
4763
- async function patchXcodeSettings(projectDirectory, genDirectory) {
4764
- const patched = [];
4765
- const unchanged = [];
4766
- for (const file of await iosPatchFiles(genDirectory)) {
4767
- const existing = await readFile(file, "utf8");
4768
- (await writeIfChanged(file, file.endsWith(".yml") ? applyProjectYmlEntitlementsSetting(existing) : applyPbxprojEntitlementsSetting(existing), projectDirectory) === "written" ? patched : unchanged).push(file);
4769
- }
4770
- return {
4771
- patched,
4772
- unchanged
5573
+ async function patchAndroidWindowBackground(projectDirectory, genDirectory, backgroundColor) {
5574
+ const colour = backgroundColor === void 0 ? void 0 : androidColour(backgroundColor);
5575
+ const resourceDirectory = androidResourceDirectory(genDirectory);
5576
+ const dayThemes = path.join(resourceDirectory, VALUES_DIRECTORY, THEMES_FILE);
5577
+ const styleName = colour === void 0 ? "" : await appThemeName(genDirectory);
5578
+ if (colour !== void 0 && !existsSync(dayThemes)) throw initError(`${dayThemes} not found`);
5579
+ const result = {
5580
+ patched: [],
5581
+ unchanged: []
4773
5582
  };
5583
+ await syncColourFile(projectDirectory, path.join(resourceDirectory, VALUES_DIRECTORY, `${COLOUR_NAME}.xml`), colour, result);
5584
+ for (const file of await themeFiles(resourceDirectory)) {
5585
+ const source = await readFile(file, "utf8");
5586
+ const holdsTheme = file === dayThemes || source.includes(`<style name="${styleName}"`);
5587
+ (await writeIfChanged(file, applyWindowBackground(source, styleName, colour !== void 0 && holdsTheme, file), projectDirectory) === "written" ? result.patched : result.unchanged).push(file);
5588
+ }
5589
+ return result;
4774
5590
  }
4775
5591
  //#endregion
4776
5592
  //#region src/plugins/project/mobile/patch.ts
@@ -4780,8 +5596,10 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
4780
5596
  * `profile.ts` (the Android build-profile patches), `signing.ts` (the Android
4781
5597
  * release-signing block), `manifest.ts` (the Android main activity's attributes, such as
4782
5598
  * the orientation lock), `system-bars.ts` (the Android status bar icon style from
4783
- * `app.backgroundColor`), `runner.ts` (the Xcode / Android-Studio runner command) and
4784
- * `xcode-settings.ts` (the iOS entitlements-modification setting that makes a REBUILD work).
5599
+ * `app.backgroundColor`), `window-background.ts` (the Android window and icon-splash
5600
+ * background from the same colour), `runner.ts` (the Xcode / Android-Studio runner command),
5601
+ * `xcode-settings.ts` (the iOS entitlements-modification setting that makes a REBUILD work)
5602
+ * and `ios-project.ts` (the iOS deployment target and privacy manifest).
4785
5603
  */
4786
5604
  /** The profile of a pass whose caller names none: the store profile, warnings dropped. */
4787
5605
  const STORE_PROFILE = { profile: "store" };
@@ -4805,31 +5623,44 @@ function mergePatchResults(...results) {
4805
5623
  };
4806
5624
  }
4807
5625
  /**
4808
- * The iOS half of {@link patchMobile}: the Xcode entitlements-modification setting, then the
4809
- * runner command when the caller supplies a runner. A tree that was never initialised is
4810
- * left alone and reports nothing.
5626
+ * The iOS half of {@link patchMobile}: the Xcode entitlements-modification setting, the
5627
+ * deployment target, the privacy manifest, then the runner command when the caller supplies
5628
+ * a runner. A tree that was never initialised is left alone and reports nothing.
4811
5629
  *
4812
- * @param projectDirectory - The Tauri project root.
4813
- * @param genDirectory - The `src-tauri/gen/apple` directory.
4814
- * @param runner - The absolute Node/tauri.js runner pair, or undefined to keep the runner.
4815
- * @returns The paths patched vs. left unchanged, merged over both patches.
5630
+ * @param options - What to patch.
5631
+ * @param options.projectDirectory - The Tauri project root.
5632
+ * @param options.genDirectory - The `src-tauri/gen/apple` directory.
5633
+ * @param options.runner - The absolute Node/tauri.js runner pair, or undefined to keep it.
5634
+ * @param options.minimumVersion - The iOS deployment target to write.
5635
+ * @param options.privacyManifest - `ios.privacyManifest`; unset removes one a previous pass
5636
+ * added.
5637
+ * @returns The paths patched vs. left unchanged, merged over every patch.
5638
+ * @throws {Error} When the privacy manifest source is missing (before anything is written),
5639
+ * or a project file lacks a line a patch needs.
4816
5640
  */
4817
- async function patchIos(projectDirectory, genDirectory, runner) {
5641
+ async function patchIos(options) {
5642
+ const { projectDirectory, genDirectory, runner } = options;
4818
5643
  if (!existsSync(genDirectory)) return {
4819
5644
  patched: [],
4820
5645
  unchanged: []
4821
5646
  };
4822
- const settingsResult = await patchXcodeSettings(projectDirectory, genDirectory);
4823
- if (!runner) return settingsResult;
4824
- return mergePatchResults(settingsResult, await patchRunner(projectDirectory, genDirectory, {
5647
+ const manifest = await readPrivacyManifest(options.privacyManifest);
5648
+ const iosResults = [
5649
+ await patchXcodeSettings(projectDirectory, genDirectory),
5650
+ await patchDeploymentTarget(projectDirectory, genDirectory, options.minimumVersion),
5651
+ await patchPrivacyManifest(projectDirectory, genDirectory, manifest)
5652
+ ];
5653
+ if (!runner) return mergePatchResults(...iosResults);
5654
+ const runnerResult = await patchRunner(projectDirectory, genDirectory, {
4825
5655
  target: "ios",
4826
5656
  runner
4827
- }));
5657
+ });
5658
+ return mergePatchResults(...iosResults, runnerResult);
4828
5659
  }
4829
5660
  /**
4830
5661
  * The Android half of {@link patchMobile}: the build-profile patches, the release signing
4831
- * block, the main activity's manifest attributes, the status bar style, then the runner
4832
- * command when the caller supplies a runner.
5662
+ * block, the main activity's manifest attributes, the status bar style, the window
5663
+ * background, then the runner command when the caller supplies a runner.
4833
5664
  *
4834
5665
  * @param options - What to patch.
4835
5666
  * @param options.projectDirectory - The Tauri project root.
@@ -4837,7 +5668,8 @@ async function patchIos(projectDirectory, genDirectory, runner) {
4837
5668
  * @param options.runner - The absolute Node/tauri.js runner pair, or undefined to keep it.
4838
5669
  * @param options.signing - The full signing config (only `.android` is consulted).
4839
5670
  * @param options.manifest - Android manifest entries for the main activity.
4840
- * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons follow.
5671
+ * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons and the
5672
+ * window background follow.
4841
5673
  * @param options.profile - The Android build profile.
4842
5674
  * @returns The paths patched vs. left unchanged, merged over every patch.
4843
5675
  * @throws {Error} When the `gen/android` tree (or its `app/build.gradle.kts`) is missing, the
@@ -4857,7 +5689,8 @@ async function patchAndroid(options) {
4857
5689
  }),
4858
5690
  await patchAndroidSigning(projectDirectory, genDirectory, options.signing.android ?? {}, debugKeystore),
4859
5691
  await patchAndroidManifest(projectDirectory, genDirectory, options.manifest),
4860
- await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor)
5692
+ await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor),
5693
+ await patchAndroidWindowBackground(projectDirectory, genDirectory, options.backgroundColor)
4861
5694
  ];
4862
5695
  if (!runner) return mergePatchResults(...androidResults);
4863
5696
  const runnerResult = await patchRunner(projectDirectory, genDirectory, {
@@ -4869,31 +5702,46 @@ async function patchAndroid(options) {
4869
5702
  /**
4870
5703
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
4871
5704
  * Android gets, in this order, its build-profile patches, its release signing block, the
4872
- * main activity's manifest attributes, the system bar style in MainActivity.kt, then the
4873
- * runner command. The profile patches run before signing so that the store profile cuts
4874
- * its Gradle block out byte for byte, wherever the signing block sits. iOS gets the Xcode
5705
+ * main activity's manifest attributes, the system bar style in MainActivity.kt, the window
5706
+ * and icon-splash background in the app theme, then the runner command. The profile
5707
+ * patches run before signing so that the store profile cuts its Gradle block out byte for
5708
+ * byte, wherever the signing block sits. iOS gets the Xcode
4875
5709
  * entitlements-modification setting (without it the SECOND build of the same tree fails),
4876
- * then the runner command. The runner rewrite runs only when the caller supplies a
4877
- * `runner`. iOS takes no manifest entries, no background colour and no profile: its
4878
- * orientation lock and signing travel through the generated `Info.ios.plist` sidecar and
4879
- * tauri.conf.json, and its status bar adapts to the page on its own.
5710
+ * the deployment target and the privacy manifest (a kept tree never runs xcodegen again, so
5711
+ * both land in `project.yml` AND `project.pbxproj`), then the runner command. The runner
5712
+ * rewrite runs only when the caller supplies a `runner`. iOS takes no manifest entries, no
5713
+ * background colour and no profile: its orientation lock and signing travel through the
5714
+ * generated `Info.ios.plist` sidecar and tauri.conf.json, and its status bar adapts to the
5715
+ * page on its own.
4880
5716
  *
4881
5717
  * @param projectDirectory - The Tauri project root.
4882
5718
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
4883
- * @param signing - The full signing config (only `.android` is consulted).
5719
+ * @param signing - The full signing config (`.android` on Android, the iOS minimum in
5720
+ * `.apple` on iOS).
4884
5721
  * @param manifest - Android manifest entries for the main activity (ignored on iOS).
4885
- * @param backgroundColor - `app.backgroundColor`; the Android status bar icons follow it
4886
- * (ignored on iOS).
5722
+ * @param backgroundColor - `app.backgroundColor`; the Android status bar icons, window
5723
+ * background and icon-splash background follow it (ignored on iOS).
4887
5724
  * @param profile - The Android build profile; the store profile when omitted.
5725
+ * @param privacyManifest - `ios.privacyManifest`, an absolute path; unset removes one a
5726
+ * previous pass added (ignored on Android).
4888
5727
  * @returns The paths patched vs. left unchanged, one merged report over every patch.
4889
5728
  * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
4890
5729
  * missing, the debug keystore is missing in the debug profile (before anything is
4891
- * written), manifest entries meet a missing manifest or an unclear main activity, or a
4892
- * background colour meets a tree without exactly one MainActivity.kt to style.
5730
+ * written), manifest entries meet a missing manifest or an unclear main activity, a
5731
+ * background colour meets a tree without exactly one MainActivity.kt to style or without
5732
+ * the app theme to set the window background in; or when the iOS privacy manifest source
5733
+ * is missing (before anything is written), or `project.yml` or `project.pbxproj` lacks a
5734
+ * line a patch needs.
4893
5735
  */
4894
- async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor, profile = STORE_PROFILE) {
5736
+ async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor, profile = STORE_PROFILE, privacyManifest) {
4895
5737
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
4896
- if (opts.target === "ios") return patchIos(projectDirectory, genDirectory, opts.runner);
5738
+ if (opts.target === "ios") return patchIos({
5739
+ projectDirectory,
5740
+ genDirectory,
5741
+ runner: opts.runner,
5742
+ minimumVersion: signing.apple?.iosMinimumSystemVersion ?? "15.0",
5743
+ privacyManifest
5744
+ });
4897
5745
  return patchAndroid({
4898
5746
  projectDirectory,
4899
5747
  genDirectory,
@@ -5442,7 +6290,8 @@ function createProjectApi(ctx) {
5442
6290
  const input = {
5443
6291
  global: ctx.global,
5444
6292
  target: opts.target,
5445
- capabilities
6293
+ capabilities,
6294
+ profile
5446
6295
  };
5447
6296
  const artifacts = [
5448
6297
  ...generateTauriConf(input),
@@ -5506,7 +6355,8 @@ function createProjectApi(ctx) {
5506
6355
  };
5507
6356
  /**
5508
6357
  * Implements {@link Api.patchMobile}: hands Android its build profile, its manifest
5509
- * entries and `app.backgroundColor` (the status bar icons follow it), then logs.
6358
+ * entries and `app.backgroundColor` (the status bar icons and the window background
6359
+ * follow it), hands iOS `ios.privacyManifest`, then logs.
5510
6360
  *
5511
6361
  * @param opts - See {@link Api.patchMobile}.
5512
6362
  * @returns See {@link Api.patchMobile}.
@@ -5514,7 +6364,7 @@ function createProjectApi(ctx) {
5514
6364
  const runPatchMobile = async (opts) => {
5515
6365
  const manifest = opts.target === "android" ? androidManifestEntries(ctx.global) : [];
5516
6366
  const profile = androidProfile(opts);
5517
- const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing, manifest, ctx.global.app.backgroundColor, profile);
6367
+ const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing, manifest, ctx.global.app.backgroundColor, profile, ctx.global.ios?.privacyManifest);
5518
6368
  ctx.log.info("project:patchMobile", {
5519
6369
  target: opts.target,
5520
6370
  profile: profile.profile,
@@ -5646,6 +6496,12 @@ function createProjectApi(ctx) {
5646
6496
  }
5647
6497
  //#endregion
5648
6498
  //#region src/plugins/project/validate.ts
6499
+ /**
6500
+ * @file project plugin — composition-time validation of the global config. Runs in the
6501
+ * plugin's `onInit`, so a misconfigured app fails at `createApp` with a `[native]` fix-it
6502
+ * instead of deep inside `tauri build`.
6503
+ */
6504
+ /** Reverse-DNS app identifier: at least two dot-separated labels. */
5649
6505
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/i;
5650
6506
  /** `MAJOR.MINOR.PATCH` with an optional pre-release/build suffix — lands raw in Cargo TOML. */
5651
6507
  const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:[-+][\w.]+)?$/;
@@ -5659,6 +6515,8 @@ const ENV_VAR_NAME_PATTERN = /^[a-z_][a-z\d_]*$/i;
5659
6515
  const HEX_COLOUR_PATTERN = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
5660
6516
  /** The three `Orientation` values — plain-JS config can carry anything else. */
5661
6517
  const ORIENTATION_PATTERN = /^(?:portrait|landscape|any)$/;
6518
+ /** `MAJOR.MINOR[.PATCH]` — lands raw in `project.yml` and `project.pbxproj`. */
6519
+ const IOS_VERSION_PATTERN = /^\d+\.\d+(?:\.\d+)?$/;
5662
6520
  /**
5663
6521
  * Validates one free-text config value that is interpolated verbatim into a generated
5664
6522
  * file. Every generated format (TOML, Kotlin, plist, XML) has its own escape rules, so a
@@ -5737,6 +6595,56 @@ function assertIconInset(inset) {
5737
6595
  throw new Error(`[native] app.adaptiveIconInset must be a number above 0 and at most ${MAX_ICON_INSET}, got ${String(inset)}.\n Use the percent per side the art needs, such as 19.44, or unset it to leave the icon untouched.`);
5738
6596
  }
5739
6597
  /**
6598
+ * Tells a plain object from everything else `typeof` calls an object: `null`, a `Date`, a
6599
+ * class instance. Only a plain object renders as a `<dict>` with its entries in it.
6600
+ *
6601
+ * @param value - The configured value.
6602
+ * @returns True, narrowing `value`, when it is a plain object.
6603
+ * @example
6604
+ * ```ts
6605
+ * isPlainObject({ a: 1 }); // true
6606
+ * isPlainObject(new Date(0)); // false
6607
+ * ```
6608
+ */
6609
+ function isPlainObject(value) {
6610
+ return value instanceof Object && Object.getPrototypeOf(value) === Object.prototype;
6611
+ }
6612
+ /**
6613
+ * Validates one `ios.infoPlist` value and everything below it. Config arrives as plain JS
6614
+ * too, and anything but a string, a boolean, an array or a plain object would render as an
6615
+ * empty `<dict>`, so the `PlistValue` type is not trusted.
6616
+ *
6617
+ * @param field - The dotted config path of the value, used verbatim in the error.
6618
+ * @param value - The configured value.
6619
+ * @throws {Error} When the value, or one nested in it, is not a plist value.
6620
+ * @example
6621
+ * ```ts
6622
+ * assertPlistValue("ios.infoPlist.Build", 7); // throws: [native] ios.infoPlist.Build is not a plist value.
6623
+ * ```
6624
+ */
6625
+ function assertPlistValue(field, value) {
6626
+ if (typeof value === "string" || typeof value === "boolean") return;
6627
+ if (!Array.isArray(value) && !isPlainObject(value)) throw new Error(`[native] ${field} is not a plist value.\n Use a string, a boolean, an array or a plain object.`);
6628
+ for (const [key, child] of Object.entries(value)) assertPlistValue(`${field}.${key}`, child);
6629
+ }
6630
+ /**
6631
+ * Validates `ios`: the privacy manifest must be an absolute path, because the patch pass
6632
+ * runs from whichever cwd started the build, and every `infoPlist` value must be a plist
6633
+ * value.
6634
+ *
6635
+ * @param ios - The configured `ios` block, or undefined when unset.
6636
+ * @throws {Error} When the manifest path is relative or a plist value is invalid.
6637
+ * @example
6638
+ * ```ts
6639
+ * assertIosConfig({ privacyManifest: "PrivacyInfo.xcprivacy" }); // throws: [native] ios.privacyManifest "PrivacyInfo.xcprivacy" must be an absolute path.
6640
+ * ```
6641
+ */
6642
+ function assertIosConfig(ios) {
6643
+ const privacyManifest = ios?.privacyManifest;
6644
+ if (privacyManifest !== void 0 && !path.isAbsolute(privacyManifest)) throw new Error(`[native] ios.privacyManifest "${privacyManifest}" must be an absolute path.\n Resolve it first, such as with path.resolve("PrivacyInfo.xcprivacy").`);
6645
+ for (const [key, value] of Object.entries(ios?.infoPlist ?? {})) assertPlistValue(`ios.infoPlist.${key}`, value);
6646
+ }
6647
+ /**
5740
6648
  * Validates the app identity and web wiring: `app.name`, a reverse-DNS `app.identifier`,
5741
6649
  * and every `web.*` field. Each lands verbatim in tauri.conf.json, where a missing value
5742
6650
  * fails deep inside `tauri build` instead of at `createApp`.
@@ -5770,13 +6678,13 @@ function assertDeepLinkScheme(global) {
5770
6678
  * Validates the global config at composition time — throws `[native]`-formatted errors
5771
6679
  * for missing app identity, missing web wiring, values that would break out of the
5772
6680
  * generated file they are written into, a window colour, orientation or adaptive icon
5773
- * inset outside its allowed shape, a `projectDir` outside the project, an `outDir` this app must not
5774
- * deliver into, unknown `config.system` names, or a `deep-link` composition missing its
5775
- * scheme.
6681
+ * inset outside its allowed shape, an `ios` block a build could not use, a `projectDir`
6682
+ * outside the project, an `outDir` this app must not deliver into, unknown `config.system`
6683
+ * names, or a `deep-link` composition missing its scheme.
5776
6684
  *
5777
6685
  * @param global - Frozen global framework config.
5778
- * @throws {Error} When identity, web wiring, interpolated values, presentation fields,
5779
- * derived directories, system names, or deep-link config are invalid.
6686
+ * @throws {Error} When identity, web wiring, interpolated values, presentation fields, the
6687
+ * `ios` block, derived directories, system names, or deep-link config are invalid.
5780
6688
  */
5781
6689
  function validateProjectConfig(global) {
5782
6690
  assertIdentity(global);
@@ -5787,6 +6695,8 @@ function validateProjectConfig(global) {
5787
6695
  assertIconInset(global.app.adaptiveIconInset);
5788
6696
  assertShape("signing.android.keystorePasswordEnv", global.signing.android?.keystorePasswordEnv, ENV_VAR_NAME_PATTERN, "environment variable name", "Reference the password by variable NAME, such as \"ANDROID_KEYSTORE_PASSWORD\" — never the password itself.");
5789
6697
  assertShape("signing.android.keyPasswordEnv", global.signing.android?.keyPasswordEnv, ENV_VAR_NAME_PATTERN, "environment variable name", "Reference the password by variable NAME, such as \"ANDROID_KEY_PASSWORD\" — never the password itself.");
6698
+ assertShape("signing.apple.iosMinimumSystemVersion", global.signing.apple?.iosMinimumSystemVersion, IOS_VERSION_PATTERN, "iOS version", "Use a version such as \"16.0\".");
6699
+ assertIosConfig(global.ios);
5790
6700
  assertDerivedDirectory(global.projectDir);
5791
6701
  assertDeliveryDirectory(global.outDir);
5792
6702
  assertKnownCapabilities(global.system);
@@ -5798,8 +6708,9 @@ function validateProjectConfig(global) {
5798
6708
  * Complex tier — capability registry + generators/ (the `tauri-plugin-moku-shell` crate
5799
6709
  * among them) + write-if-changed writer + the mobile/ sub-domain (completeness gate, build
5800
6710
  * profile patches, Android signing block, Android manifest attributes, adaptive icon inset,
5801
- * shell link check, Xcode settings, runner-command rewrite) + the build-time orientation
5802
- * lock + the page agent scan + the guarded clean.
6711
+ * shell link check, Xcode settings, iOS deployment target and privacy manifest,
6712
+ * runner-command rewrite) + the build-time orientation lock + the page agent scan + the
6713
+ * guarded clean.
5803
6714
  *
5804
6715
  * @see README.md
5805
6716
  * @example
@@ -8807,6 +9718,12 @@ const rustupCheck = {
8807
9718
  //#endregion
8808
9719
  //#region src/plugins/doctor/checks/signing.ts
8809
9720
  /**
9721
+ * @file doctor plugin check — signing readiness for ios/macos/android: env-var PRESENCE only
9722
+ * (never values) plus, for Apple, a count-only keychain identity probe and, for Android,
9723
+ * whether the keystore file exists. Warn-only posture: unsigned and simulator builds are
9724
+ * legal, so this check never fails.
9725
+ */
9726
+ /**
8810
9727
  * The two Apple credential sets Tauri accepts — either one, complete, is enough.
8811
9728
  * Presence only: a value is never read, so nothing here can reach a message.
8812
9729
  */
@@ -8825,9 +9742,21 @@ const APPLE_CREDENTIAL_SETS = [{
8825
9742
  "APPLE_API_KEY_PATH"
8826
9743
  ]
8827
9744
  }];
9745
+ /** The scopes that carry a signing identifier or env ref. */
9746
+ const SIGNING_TARGETS = /* @__PURE__ */ new Set([
9747
+ "ios",
9748
+ "macos",
9749
+ "android",
9750
+ "windows"
9751
+ ]);
8828
9752
  /** Every signing message repeats this — doctor never fails a build over signing. */
8829
9753
  const LEGAL_NOTE = "unsigned and simulator builds are legal";
8830
9754
  /**
9755
+ * The Gradle module that holds the signing config, relative to `projectDir`. Gradle's
9756
+ * `file()` in `app/build.gradle.kts` resolves a relative `storeFile` from this directory.
9757
+ */
9758
+ const GRADLE_APP_DIRECTORY = "src-tauri/gen/android/app";
9759
+ /**
8831
9760
  * Whether the local keychain is worth probing: only when a concrete `signingIdentity` is
8832
9761
  * configured (not the ad-hoc `"-"`) and CI has not brought its own certificate.
8833
9762
  *
@@ -8907,12 +9836,27 @@ async function checkAppleSigning(input) {
8907
9836
  };
8908
9837
  }
8909
9838
  /**
8910
- * Checks the android signing env var (`signing.android.keystorePasswordEnv`) for presence.
9839
+ * Looks up the configured `signing.android.keystorePath` where Gradle will read it: an
9840
+ * absolute path as it stands, a relative one under {@link GRADLE_APP_DIRECTORY}.
9841
+ *
9842
+ * @param input - The check input (looks through its fs facade).
9843
+ * @returns The path that is missing, or `undefined` when none is configured or the file exists.
9844
+ */
9845
+ async function missingKeystore(input) {
9846
+ const configured = input.global.signing.android?.keystorePath;
9847
+ if (!configured) return void 0;
9848
+ const keystore = path.isAbsolute(configured) ? configured : path.join(input.global.projectDir, GRADLE_APP_DIRECTORY, configured);
9849
+ return await input.fs.exists(keystore) ? void 0 : keystore;
9850
+ }
9851
+ /**
9852
+ * Checks android signing: the `signing.android.keystorePasswordEnv` var, then the
9853
+ * `signing.android.keyPasswordEnv` var when one is configured (presence only), then the
9854
+ * `signing.android.keystorePath` file when one is configured. The first gap is the result.
8911
9855
  *
8912
9856
  * @param input - The check input, scoped to "android".
8913
9857
  * @returns The check result — "pass" or "warn", never "fail".
8914
9858
  */
8915
- function checkAndroidSigning(input) {
9859
+ async function checkAndroidSigning(input) {
8916
9860
  const envName = input.global.signing.android?.keystorePasswordEnv;
8917
9861
  if (!envName) return {
8918
9862
  id: "signing-android",
@@ -8928,6 +9872,22 @@ function checkAndroidSigning(input) {
8928
9872
  message: `[native] android signing env var "${envName}" is not set.`,
8929
9873
  fixIt: `export ${envName} before building a signed android release`
8930
9874
  };
9875
+ const keyPasswordVariable = input.global.signing.android?.keyPasswordEnv;
9876
+ if (keyPasswordVariable && !input.env.has(keyPasswordVariable)) return {
9877
+ id: "signing-android",
9878
+ target: "android",
9879
+ status: "warn",
9880
+ message: `[native] android key password env var "${keyPasswordVariable}" is not set.`,
9881
+ fixIt: `export ${keyPasswordVariable} before building a signed android release`
9882
+ };
9883
+ const keystore = await missingKeystore(input);
9884
+ if (keystore !== void 0) return {
9885
+ id: "signing-android",
9886
+ target: "android",
9887
+ status: "warn",
9888
+ message: `[native] android keystore not found at ${keystore}.`,
9889
+ fixIt: `put the keystore at ${keystore}, or correct signing.android.keystorePath (a relative path resolves from ${GRADLE_APP_DIRECTORY})`
9890
+ };
8931
9891
  return {
8932
9892
  id: "signing-android",
8933
9893
  target: "android",
@@ -8997,7 +9957,7 @@ const signingCheck = {
8997
9957
  * signingCheck.appliesTo("android", global); // true
8998
9958
  * ```
8999
9959
  */
9000
- appliesTo: (target) => target === "ios" || target === "macos" || target === "android" || target === "windows",
9960
+ appliesTo: (target) => SIGNING_TARGETS.has(target),
9001
9961
  run: run$4
9002
9962
  };
9003
9963
  //#endregion
@@ -10226,7 +11186,7 @@ const cliPlugin = createPlugin$1("cli", {
10226
11186
  *
10227
11187
  * | Field | Type | Default |
10228
11188
  * |---|---|---|
10229
- * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber?; orientation?; backgroundColor?; adaptiveIconInset? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition; `orientation` (`"portrait" \| "landscape" \| "any"`) is a build-time mobile lock, `backgroundColor` a hex window colour, `adaptiveIconInset` the Android adaptive icon inset (percent per side, `0 < n ≤ 30`) |
11189
+ * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber?; orientation?; backgroundColor?; adaptiveIconInset?; keepScreenOn? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition; `buildNumber` is also the Android `versionCode` (a whole number from 1 to 2100000000, checked at generate, android only); `orientation` (`"portrait" \| "landscape" \| "any"`) is a build-time mobile lock, `backgroundColor` a hex window colour, `adaptiveIconInset` the Android adaptive icon inset (percent per side, `0 < n ≤ 30`), `keepScreenOn` turns the iOS idle timer off |
10230
11190
  * | `web` | `{ build; devCommand; devUrl; dist; cwd? }` | `"bun run build"`, `"bun run dev"`, `"http://localhost:5173"`, `"dist"` |
10231
11191
  * | `system` | `ReadonlyArray<{ name: string }>` | `[]` — the composed `@moku-labs/system` plugins |
10232
11192
  * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` — keys: `store`, `notification`, `clipboard-manager`, `tray`, `deep-link`, `back`, `haptics`, `shell` |
@@ -10234,6 +11194,12 @@ const cliPlugin = createPlugin$1("cli", {
10234
11194
  * | `projectDir` | `string` | `".moku/tauri"` — generated Tauri project (gitignored build output) |
10235
11195
  * | `outDir` | `string` | `"dist-native"` — installer delivery root |
10236
11196
  * | `signing` | `SigningConfig` | `{}` — identifiers and env-var NAMES only, never secrets; the generated iOS minimum falls back to `"15.0"` |
11197
+ * | `ios` | `{ infoPlist?; privacyManifest? }` | unset — `infoPlist` merges into `Info.plist` (`app.orientation` wins a shared key); `privacyManifest` is the absolute path of the bundle's `PrivacyInfo.xcprivacy`, and unset removes one an earlier build left |
11198
+ *
11199
+ * Every generated `Cargo.toml` carries a size `[profile.release]`, and a store build sets
11200
+ * `build.removeUnusedCommands` in `tauri.conf.json`. Each iOS patch pass keeps the deployment
11201
+ * target and the privacy manifest in both `project.yml` and `project.pbxproj`, because a kept
11202
+ * tree never runs xcodegen again.
10237
11203
  *
10238
11204
  * Per-plugin config (`pluginConfigs`) — each plugin's own defaults, all seams `undefined`
10239
11205
  * so the real implementation runs unless a test injects one: