@moku-labs/native 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -771,6 +771,18 @@ function generateCapabilities(input) {
771
771
  //#endregion
772
772
  //#region src/plugins/project/generators/cargo.ts
773
773
  /**
774
+ * The `tauri` crate floor. The `back` capability calls `exit()` and grants
775
+ * `core:app:allow-exit`, and both exist only since tauri 2.12.0. `tauri-build` versions
776
+ * on its own 2.x line, so its floor stays `"2"`.
777
+ */
778
+ const TAURI_VERSION_FLOOR = "2.12";
779
+ /**
780
+ * The dependencies only an iOS build compiles: the safe-area hook in the generated
781
+ * `lib.rs` reaches WKWebView through `objc2`. A target table, written for every target,
782
+ * so no other target ever builds the crate and the table adds no per-target difference.
783
+ */
784
+ const IOS_ONLY_DEPENDENCIES = [`[target.'cfg(target_os = "ios")'.dependencies]`, "objc2 = \"0.6\""];
785
+ /**
774
786
  * Derives a valid Cargo package name from the app's display name — lowercased,
775
787
  * non-alphanumeric runs collapsed to a single hyphen, and guaranteed to start with a
776
788
  * letter (Cargo package names must match `[a-z][a-z0-9_-]*`).
@@ -806,7 +818,8 @@ function crateIdent(packageName) {
806
818
  * Generates `src-tauri/Cargo.toml` — the package manifest, the `tauri` dependency with
807
819
  * every cargo feature the composed capabilities ask for (tray's `tray-icon`; without it
808
820
  * the tray API is not compiled in at all), plus one pinned dependency line per resolved
809
- * capability that ships a real crate. Feature-only rows contribute no dependency line.
821
+ * capability that ships a real crate. Feature-only and permission-only rows contribute
822
+ * no dependency line. The iOS-only `objc2` table closes the file on every target.
810
823
  *
811
824
  * @param input - Frozen global config + capabilities resolved for the target.
812
825
  * @returns A single-artifact array for `src-tauri/Cargo.toml`.
@@ -835,10 +848,12 @@ function generateCargo(input) {
835
848
  "tauri-build = { version = \"2\", features = [] }",
836
849
  "",
837
850
  "[dependencies]",
838
- `tauri = { version = "2", features = [${features}] }`,
851
+ `tauri = { version = "${TAURI_VERSION_FLOOR}", features = [${features}] }`,
839
852
  "serde = { version = \"1\", features = [\"derive\"] }",
840
853
  "serde_json = \"1\"",
841
854
  ...pinnedDeps,
855
+ "",
856
+ ...IOS_ONLY_DEPENDENCIES,
842
857
  ""
843
858
  ].join("\n")
844
859
  }];
@@ -956,14 +971,44 @@ function generateEntitlements(input) {
956
971
  //#endregion
957
972
  //#region src/plugins/project/generators/rust.ts
958
973
  /**
959
- * @file project plugin generator — main.rs/lib.rs with mobile entry point + plugin init lines.
960
- */
974
+ * @file project plugin generator — main.rs/lib.rs with mobile entry point, plugin init
975
+ * lines and the iOS safe-area setup hook.
976
+ */
977
+ /**
978
+ * `Manager` brings `get_webview_window` into scope. Only the iOS arm of the setup hook
979
+ * calls it, so the import is iOS-only too: anywhere else it would be an unused import.
980
+ */
981
+ const IOS_MANAGER_IMPORT = ["#[cfg(target_os = \"ios\")]", "use tauri::Manager;"];
982
+ /**
983
+ * The safe-area setup hook, as verified on the iOS 26.3 simulator. UIKit shrinks a
984
+ * WKWebView page by the safe area while its scroll view stays on `.automatic`; `.never`
985
+ * gives the page the whole screen, and CSS `env(safe-area-inset-*)` still reports the
986
+ * notch. The `cfg` makes it a no-op off iOS, so `lib.rs` does not differ per target. The
987
+ * window is tauri's default `main` label: the generated `app.windows` entry carries none.
988
+ */
989
+ const SAFE_AREA_SETUP = [
990
+ " .setup(|_app| {",
991
+ " // wry leaves WKWebView's scroll view on .automatic, which shrinks the page by the",
992
+ " // safe area (tauri-apps/tauri#8166). .never gives the page the full screen.",
993
+ " #[cfg(target_os = \"ios\")]",
994
+ " if let Some(window) = _app.get_webview_window(\"main\") {",
995
+ " window.with_webview(|webview| unsafe {",
996
+ " use objc2::{msg_send, runtime::AnyObject};",
997
+ " let wk = &*(webview.inner() as *mut AnyObject);",
998
+ " let scroll: *mut AnyObject = msg_send![wk, scrollView];",
999
+ " // UIScrollViewContentInsetAdjustmentNever = 2",
1000
+ " let _: () = msg_send![&*scroll, setContentInsetAdjustmentBehavior: 2isize];",
1001
+ " })?;",
1002
+ " }",
1003
+ " Ok(())",
1004
+ " })"
1005
+ ];
961
1006
  /**
962
1007
  * Generates `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`. `lib.rs` carries the
963
1008
  * `#[cfg_attr(mobile, tauri::mobile_entry_point)]`-annotated `run()` with one
964
1009
  * `.plugin(...)` init line per resolved capability that has a real Rust init (rows
965
- * without one, e.g. tray's cargo-feature row, contribute no line); `main.rs` is a thin
966
- * entry point that calls into the lib crate.
1010
+ * without one, e.g. tray's cargo-feature row, contribute no line), then the iOS
1011
+ * safe-area `.setup` hook; `main.rs` is a thin entry point that calls into the lib crate.
967
1012
  *
968
1013
  * @param input - Frozen global config + capabilities resolved for the target.
969
1014
  * @returns Artifacts for `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`.
@@ -974,11 +1019,15 @@ function generateEntitlements(input) {
974
1019
  */
975
1020
  function generateRust(input) {
976
1021
  const packageIdent = crateIdent(sanitizePackageName(input.global.app.name));
1022
+ const pluginLines = input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted();
977
1023
  const library = [
1024
+ ...IOS_MANAGER_IMPORT,
1025
+ "",
978
1026
  "#[cfg_attr(mobile, tauri::mobile_entry_point)]",
979
1027
  "pub fn run() {",
980
1028
  " tauri::Builder::default()",
981
- ...input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted(),
1029
+ ...pluginLines,
1030
+ ...SAFE_AREA_SETUP,
982
1031
  " .run(tauri::generate_context!())",
983
1032
  " .expect(\"error while running tauri application\");",
984
1033
  "}",
@@ -1001,25 +1050,172 @@ function generateRust(input) {
1001
1050
  }];
1002
1051
  }
1003
1052
  //#endregion
1053
+ //#region src/plugins/project/orientation.ts
1054
+ const PORTRAIT = "UIInterfaceOrientationPortrait";
1055
+ const PORTRAIT_UPSIDE_DOWN = "UIInterfaceOrientationPortraitUpsideDown";
1056
+ const LANDSCAPE_SIDES = ["UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"];
1057
+ /**
1058
+ * The iOS orientation lists per lock: the iPhone key, then the `~ipad` override. An iPhone
1059
+ * held portrait never turns upside down; an iPad does, so its portrait list keeps both.
1060
+ */
1061
+ const IOS_ORIENTATIONS = {
1062
+ portrait: {
1063
+ iphone: [PORTRAIT],
1064
+ ipad: [PORTRAIT, PORTRAIT_UPSIDE_DOWN]
1065
+ },
1066
+ landscape: {
1067
+ iphone: LANDSCAPE_SIDES,
1068
+ ipad: LANDSCAPE_SIDES
1069
+ }
1070
+ };
1071
+ /**
1072
+ * The Android `screenOrientation` per lock, matching the iOS lists: `portrait` has no
1073
+ * upside-down side, `sensorLandscape` turns between both landscape sides. `any` maps to no
1074
+ * attribute at all, the template's default.
1075
+ */
1076
+ const ANDROID_SCREEN_ORIENTATION = {
1077
+ portrait: "portrait",
1078
+ landscape: "sensorLandscape",
1079
+ any: void 0
1080
+ };
1081
+ /**
1082
+ * Builds the `Info.ios.plist` entries that lock the iOS orientation. A locked app also
1083
+ * asks for `UIRequiresFullScreen`: App Store review refuses an iPad app that restricts its
1084
+ * orientations without it. `any` and unset add nothing, so the template's default list
1085
+ * (every orientation) stays.
1086
+ *
1087
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1088
+ * @returns The plist entries, empty when the orientation is not locked.
1089
+ * @example
1090
+ * ```ts
1091
+ * orientationPlist("portrait")[0];
1092
+ * // { key: "UISupportedInterfaceOrientations", value: ["UIInterfaceOrientationPortrait"] }
1093
+ * ```
1094
+ */
1095
+ function orientationPlist(orientation) {
1096
+ if (orientation === void 0 || orientation === "any") return [];
1097
+ const { iphone, ipad } = IOS_ORIENTATIONS[orientation];
1098
+ return [
1099
+ {
1100
+ key: "UISupportedInterfaceOrientations",
1101
+ value: iphone
1102
+ },
1103
+ {
1104
+ key: "UISupportedInterfaceOrientations~ipad",
1105
+ value: ipad
1106
+ },
1107
+ {
1108
+ key: "UIRequiresFullScreen",
1109
+ value: true
1110
+ }
1111
+ ];
1112
+ }
1113
+ /**
1114
+ * Builds the Android manifest entry for the orientation lock: `android:screenOrientation`
1115
+ * on the main activity. `any` and unset ask for the attribute to be ABSENT rather than
1116
+ * adding nothing, so a lock a previous build wrote into the gen/ tree is removed again.
1117
+ *
1118
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1119
+ * @returns Exactly one `activity-attribute` entry.
1120
+ * @example
1121
+ * ```ts
1122
+ * orientationManifest("landscape");
1123
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "sensorLandscape" }]
1124
+ * ```
1125
+ */
1126
+ function orientationManifest(orientation) {
1127
+ return [{
1128
+ kind: "activity-attribute",
1129
+ name: "android:screenOrientation",
1130
+ value: ANDROID_SCREEN_ORIENTATION[orientation ?? "any"]
1131
+ }];
1132
+ }
1133
+ //#endregion
1134
+ //#region src/plugins/project/xml.ts
1135
+ /**
1136
+ * @file project plugin — XML text escaping, shared by the two XML files this plugin writes
1137
+ * into: the `Info.ios.plist` sidecar and the Android manifest.
1138
+ */
1139
+ /**
1140
+ * XML's five predefined entities. `&` goes first, so the ampersand of an entity written
1141
+ * by a later step is never escaped a second time.
1142
+ */
1143
+ const XML_ESCAPES = [
1144
+ [/&/g, "&"],
1145
+ [/</g, "&lt;"],
1146
+ [/>/g, "&gt;"],
1147
+ [/"/g, "&quot;"],
1148
+ [/'/g, "&apos;"]
1149
+ ];
1150
+ /**
1151
+ * Escapes text for an XML element body or a quoted attribute value. A value lands
1152
+ * verbatim in a generated file, where an unescaped `<` or `"` would end the element or
1153
+ * the attribute around it.
1154
+ *
1155
+ * @param text - The raw value.
1156
+ * @returns The value with `& < > " '` written as entities.
1157
+ * @example
1158
+ * ```ts
1159
+ * escapeXml(`Tom & "Jerry"`); // "Tom &amp; &quot;Jerry&quot;"
1160
+ * ```
1161
+ */
1162
+ function escapeXml(text) {
1163
+ let escaped = text;
1164
+ for (const [pattern, entity] of XML_ESCAPES) escaped = escaped.replace(pattern, entity);
1165
+ return escaped;
1166
+ }
1167
+ //#endregion
1004
1168
  //#region src/plugins/project/generators/sidecar.ts
1005
1169
  /**
1006
- * Generates the `Info.ios.plist` SIDECAR at the src-tauri root — a future-mechanism
1007
- * seam for iOS mobile-permission plist keys (D-012). Every v1 registry row carries an
1008
- * empty `sidecarPlist`, so this emits no artifact today; it stays pure and
1009
- * generator-shaped so a future row carrying `sidecarPlist` entries activates it with
1010
- * zero pipeline changes.
1170
+ * @file project plugin generator — Info.ios.plist sidecar (src-tauri root, outside gen/).
1171
+ */
1172
+ /**
1173
+ * Renders one plist value as the lines that follow its `<key>`: a `<string>`, a
1174
+ * `<true/>`/`<false/>`, or an `<array>` of strings. Every text is XML-escaped.
1175
+ *
1176
+ * @param value - The entry value.
1177
+ * @returns The value's lines, indented for the top-level `<dict>`.
1178
+ * @example
1179
+ * ```ts
1180
+ * renderPlistValue(["UIInterfaceOrientationPortrait"]);
1181
+ * // [" <array>", " <string>UIInterfaceOrientationPortrait</string>", " </array>"]
1182
+ * ```
1183
+ */
1184
+ function renderPlistValue(value) {
1185
+ if (typeof value === "boolean") return [value ? " <true/>" : " <false/>"];
1186
+ if (typeof value === "string") return [` <string>${escapeXml(value)}</string>`];
1187
+ return [
1188
+ " <array>",
1189
+ ...value.map((item) => ` <string>${escapeXml(item)}</string>`),
1190
+ " </array>"
1191
+ ];
1192
+ }
1193
+ /**
1194
+ * Generates the `Info.ios.plist` SIDECAR at the src-tauri root, which Tauri merges into the
1195
+ * app's Info.plist on every iOS build. Its entries are every resolved capability's
1196
+ * `sidecarPlist`, then the orientation lock (`app.orientation`); on a duplicate key the
1197
+ * later entry wins, so orientation beats a capability.
1198
+ *
1199
+ * On iOS the file is ALWAYS written, as an empty `<dict>` when nothing contributes a key:
1200
+ * the writer never deletes a file, and a portrait lock left in a stale sidecar would keep
1201
+ * being merged after the app went back to `any`. Every other target gets no artifact.
1011
1202
  *
1012
1203
  * @param input - Frozen global config + capabilities resolved for the target.
1013
- * @returns An artifact for `src-tauri/Info.ios.plist` when any resolved capability
1014
- * carries sidecar entries, otherwise an empty array.
1204
+ * @returns An artifact for `src-tauri/Info.ios.plist` on iOS, otherwise an empty array.
1015
1205
  * @example
1016
1206
  * ```ts
1017
- * generateSidecar({ global, target: "ios", capabilities: [] }); // []
1207
+ * // `config` is any full native Config
1208
+ * const global = { ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } };
1209
+ * generateSidecar({ global, target: "ios", capabilities: [] })[0]?.path; // "src-tauri/Info.ios.plist"
1210
+ * // its <dict>: UISupportedInterfaceOrientations, UISupportedInterfaceOrientations~ipad, UIRequiresFullScreen
1211
+ * generateSidecar({ global, target: "macos", capabilities: [] }); // []
1018
1212
  * ```
1019
1213
  */
1020
1214
  function generateSidecar(input) {
1021
- const entries = input.capabilities.flatMap((capability) => capability.sidecarPlist);
1022
- if (entries.length === 0) return [];
1215
+ if (input.target !== "ios") return [];
1216
+ const entries = /* @__PURE__ */ new Map();
1217
+ const contributed = [...input.capabilities.flatMap((capability) => capability.sidecarPlist), ...orientationPlist(input.global.app.orientation)];
1218
+ for (const entry of contributed) entries.set(entry.key, entry.value);
1023
1219
  return [{
1024
1220
  path: "src-tauri/Info.ios.plist",
1025
1221
  content: [
@@ -1027,7 +1223,7 @@ function generateSidecar(input) {
1027
1223
  "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
1028
1224
  "<plist version=\"1.0\">",
1029
1225
  "<dict>",
1030
- entries.map((entry) => ` <key>${entry.key}</key>\n <string>${entry.value}</string>`).join("\n"),
1226
+ ...[...entries].flatMap(([key, value]) => [` <key>${escapeXml(key)}</key>`, ...renderPlistValue(value)]),
1031
1227
  "</dict>",
1032
1228
  "</plist>",
1033
1229
  ""
@@ -1131,7 +1327,8 @@ function buildPlugins(capabilities) {
1131
1327
  }
1132
1328
  /**
1133
1329
  * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, the
1134
- * bundle/signing metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1330
+ * main window (its title, plus `app.backgroundColor` when set), the bundle/signing
1331
+ * metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1135
1332
  * {@link buildPlugins}; this is where deep-link's scheme rides — per D-011/D-012 the whole
1136
1333
  * v1 mobile-permission story is conf-only). Both path-shaped fields are rebased onto
1137
1334
  * `src-tauri`, which is where Tauri resolves them from, and the before-commands carry an
@@ -1163,7 +1360,10 @@ function generateTauriConf(input) {
1163
1360
  devUrl: global.web.devUrl,
1164
1361
  frontendDist: relativeToTauriRoot(global.projectDir, path.resolve(webRoot, global.web.dist))
1165
1362
  },
1166
- app: { windows: [{ title: global.app.name }] },
1363
+ app: { windows: [{
1364
+ title: global.app.name,
1365
+ ...compact([["backgroundColor", global.app.backgroundColor]])
1366
+ }] },
1167
1367
  bundle: buildBundle(input),
1168
1368
  plugins: buildPlugins(capabilities)
1169
1369
  };
@@ -1462,6 +1662,222 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1462
1662
  return "written";
1463
1663
  }
1464
1664
  //#endregion
1665
+ //#region src/plugins/project/mobile/manifest.ts
1666
+ /**
1667
+ * @file project plugin — the Android manifest patch. Tauri has no config key for what the
1668
+ * main activity carries (`android:screenOrientation` among them), so the mobile patch pass
1669
+ * sets those attributes on the `<activity>` of the generated
1670
+ * `gen/android/app/src/main/AndroidManifest.xml` itself.
1671
+ *
1672
+ * The transform is a pure text function: only the touched attribute changes, every other
1673
+ * byte (line endings and indentation included) survives, and a second pass is a no-op.
1674
+ */
1675
+ /** Where `tauri android init` writes the app manifest, below `gen/android`. */
1676
+ const MANIFEST_PATH_SEGMENTS = [
1677
+ "app",
1678
+ "src",
1679
+ "main",
1680
+ "AndroidManifest.xml"
1681
+ ];
1682
+ /** The tag name an activity start tag opens with. */
1683
+ const ACTIVITY_OPEN = "<activity";
1684
+ /** The end tag that closes an activity's body. */
1685
+ const ACTIVITY_CLOSE = "</activity>";
1686
+ /** The intent action that marks the launcher activity. */
1687
+ const MAIN_ACTION = "android.intent.action.MAIN";
1688
+ /** Where an `<activity` start tag opens — `<activity-alias` is a different element. */
1689
+ const ACTIVITY_OPEN_PATTERN = /<activity(?=[\s/>])/g;
1690
+ /**
1691
+ * One attribute inside a start tag, from the whitespace character before it:
1692
+ * ` (name)="value"`. XML allows spaces around `=`, but no generated manifest writes them.
1693
+ */
1694
+ const ATTRIBUTE_PATTERN = /\s([\w:.-]+)=(?:"[^"]*"|'[^']*')/g;
1695
+ /** An XML comment — blanked before the scan, so a commented-out activity never counts. */
1696
+ const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
1697
+ /**
1698
+ * Builds the `[native]` error for a manifest whose main activity cannot be told apart.
1699
+ *
1700
+ * @param manifestPath - The manifest that was searched.
1701
+ * @returns A formatted `[native] ...` error.
1702
+ * @example
1703
+ * ```ts
1704
+ * throw mainActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
1705
+ * ```
1706
+ */
1707
+ function mainActivityError(manifestPath) {
1708
+ 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.`);
1709
+ }
1710
+ /**
1711
+ * Finds where a start tag ends. A quoted attribute value is skipped whole, so a `>` inside
1712
+ * one never ends the tag.
1713
+ *
1714
+ * @param text - The manifest content.
1715
+ * @param from - Offset just past the tag name.
1716
+ * @returns The offset just past the closing `>`, or undefined for a tag that never closes.
1717
+ * @example
1718
+ * ```ts
1719
+ * startTagEnd('<activity android:label="a > b">', 9); // 32
1720
+ * ```
1721
+ */
1722
+ function startTagEnd(text, from) {
1723
+ let quote;
1724
+ for (let index = from; index < text.length; index += 1) {
1725
+ const character = text[index];
1726
+ if (quote !== void 0) {
1727
+ if (character === quote) quote = void 0;
1728
+ continue;
1729
+ }
1730
+ if (character === "\"" || character === "'") {
1731
+ quote = character;
1732
+ continue;
1733
+ }
1734
+ if (character === ">") return index + 1;
1735
+ }
1736
+ }
1737
+ /**
1738
+ * Locates every `<activity>` start tag and records whether its body declares MAIN.
1739
+ * Comments are blanked out first (same length, so every offset still points into the real
1740
+ * text), which keeps a commented-out activity from being counted or patched. A start tag
1741
+ * that never closes is not counted at all.
1742
+ *
1743
+ * @param text - The manifest content.
1744
+ * @returns One entry per activity, in file order.
1745
+ * @example
1746
+ * ```ts
1747
+ * locateActivities('<activity android:name=".A" /><activity android:name=".B"><action android:name="android.intent.action.MAIN" /></activity>');
1748
+ * // [{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]
1749
+ * ```
1750
+ */
1751
+ function locateActivities(text) {
1752
+ const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
1753
+ const activities = [];
1754
+ for (const match of masked.matchAll(ACTIVITY_OPEN_PATTERN)) {
1755
+ const start = match.index;
1756
+ const end = startTagEnd(masked, start + 9);
1757
+ if (end === void 0) continue;
1758
+ const body = masked.slice(start, end).endsWith("/>") ? "" : masked.slice(end, masked.indexOf(ACTIVITY_CLOSE, end));
1759
+ activities.push({
1760
+ start,
1761
+ end,
1762
+ isMain: body.includes(MAIN_ACTION)
1763
+ });
1764
+ }
1765
+ return activities;
1766
+ }
1767
+ /**
1768
+ * Picks the main activity: the one whose body declares MAIN. A manifest with a single
1769
+ * activity and no MAIN still has an obvious one; anything else is ambiguous.
1770
+ *
1771
+ * @param activities - Every activity in the manifest.
1772
+ * @returns The main activity, or undefined when none or several qualify.
1773
+ * @example
1774
+ * ```ts
1775
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]);
1776
+ * // { start: 30, end: 58, isMain: true }
1777
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: false }]); // undefined
1778
+ * ```
1779
+ */
1780
+ function mainActivity(activities) {
1781
+ const mains = activities.filter((activity) => activity.isMain);
1782
+ if (mains.length === 1) return mains[0];
1783
+ if (mains.length === 0 && activities.length === 1) return activities[0];
1784
+ }
1785
+ /**
1786
+ * Applies one attribute entry to a start tag. A value replaces the attribute in place, or
1787
+ * is inserted right after `<activity` with the whitespace that already follows it — on the
1788
+ * template's one-attribute-per-line layout that is the line break plus the next
1789
+ * attribute's indentation, CRLF included. An `undefined` value removes the attribute
1790
+ * together with the whitespace before it, which on that layout is its whole line.
1791
+ *
1792
+ * @param tag - The activity start tag.
1793
+ * @param entry - The attribute to set or remove.
1794
+ * @returns The start tag with the entry applied.
1795
+ * @example
1796
+ * ```ts
1797
+ * applyAttribute('<activity android:name=".MainActivity">', portraitEntry);
1798
+ * // '<activity android:screenOrientation="portrait" android:name=".MainActivity">'
1799
+ * ```
1800
+ */
1801
+ function applyAttribute(tag, entry) {
1802
+ const rendered = entry.value === void 0 ? void 0 : `${entry.name}="${escapeXml(entry.value)}"`;
1803
+ const existing = [...tag.matchAll(ATTRIBUTE_PATTERN)].find((match) => match[1] === entry.name);
1804
+ if (existing) {
1805
+ const before = tag.slice(0, existing.index).trimEnd();
1806
+ const separator = tag.slice(before.length, existing.index + 1);
1807
+ const after = tag.slice(existing.index + existing[0].length);
1808
+ if (rendered === void 0) return `${before}${after}`;
1809
+ return `${before}${separator}${rendered}${after}`;
1810
+ }
1811
+ if (rendered === void 0) return tag;
1812
+ const rest = tag.slice(9);
1813
+ const separator = rest.slice(0, rest.length - rest.trimStart().length) || " ";
1814
+ return `${ACTIVITY_OPEN}${separator}${rendered}${rest}`;
1815
+ }
1816
+ /**
1817
+ * Applies the `activity-attribute` entries to the main activity of a manifest. `child`
1818
+ * entries are not applied: no registry row carries one, and the official plugins merge
1819
+ * their own manifest needs through build.rs. A pass that only removes attributes leaves a
1820
+ * manifest without a clear main activity as it is.
1821
+ *
1822
+ * @param existing - The current manifest content.
1823
+ * @param entries - The manifest entries to apply, in order (a later one wins).
1824
+ * @param manifestPath - The manifest's path, named in the error.
1825
+ * @returns The manifest with every attribute entry applied.
1826
+ * @throws {Error} `[native]` when an attribute is to be set and the main activity cannot
1827
+ * be told apart.
1828
+ * @example
1829
+ * ```ts
1830
+ * applyManifestEntries('<activity android:name=".Main">\n</activity>', orientationManifest("portrait"), "AndroidManifest.xml");
1831
+ * // '<activity android:screenOrientation="portrait" android:name=".Main">\n</activity>'
1832
+ * ```
1833
+ */
1834
+ function applyManifestEntries(existing, entries, manifestPath) {
1835
+ const attributes = entries.filter((entry) => entry.kind === "activity-attribute");
1836
+ if (attributes.length === 0) return existing;
1837
+ const activity = mainActivity(locateActivities(existing));
1838
+ if (!activity) {
1839
+ if (attributes.every((attribute) => attribute.value === void 0)) return existing;
1840
+ throw mainActivityError(manifestPath);
1841
+ }
1842
+ let tag = existing.slice(activity.start, activity.end);
1843
+ for (const attribute of attributes) tag = applyAttribute(tag, attribute);
1844
+ return `${existing.slice(0, activity.start)}${tag}${existing.slice(activity.end)}`;
1845
+ }
1846
+ /**
1847
+ * Patches the main activity of `gen/android/app/src/main/AndroidManifest.xml` with the
1848
+ * `activity-attribute` entries, through the write-if-changed writer. Idempotent: a second
1849
+ * pass reports the manifest unchanged. With no attribute entry there is nothing to apply,
1850
+ * and the manifest is not even read.
1851
+ *
1852
+ * @param projectDirectory - The Tauri project root.
1853
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1854
+ * @param entries - The manifest entries to apply.
1855
+ * @returns The manifest path, patched or unchanged.
1856
+ * @throws {Error} `[native]` when the manifest is missing, or an attribute is to be set and
1857
+ * the manifest has no clear main activity.
1858
+ * @example
1859
+ * ```ts
1860
+ * // First pass on a manifest without the lock; a second pass lists it under `unchanged`.
1861
+ * await patchAndroidManifest(".moku/tauri", ".moku/tauri/src-tauri/gen/android", orientationManifest("portrait"));
1862
+ * // { patched: [".moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml"], unchanged: [] }
1863
+ * ```
1864
+ */
1865
+ async function patchAndroidManifest(projectDirectory, genDirectory, entries) {
1866
+ if (!entries.some((entry) => entry.kind === "activity-attribute")) return {
1867
+ patched: [],
1868
+ unchanged: []
1869
+ };
1870
+ const manifestPath = path.join(genDirectory, ...MANIFEST_PATH_SEGMENTS);
1871
+ if (!existsSync(manifestPath)) throw new Error(`[native] AndroidManifest.xml not found at ${manifestPath}.\n Re-run the mobile init pass (tauri android init) before patching the manifest.`);
1872
+ return await writeIfChanged(manifestPath, applyManifestEntries(await readFile(manifestPath, "utf8"), entries, manifestPath), projectDirectory) === "written" ? {
1873
+ patched: [manifestPath],
1874
+ unchanged: []
1875
+ } : {
1876
+ patched: [],
1877
+ unchanged: [manifestPath]
1878
+ };
1879
+ }
1880
+ //#endregion
1465
1881
  //#region src/plugins/project/mobile/files.ts
1466
1882
  /**
1467
1883
  * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
@@ -1572,12 +1988,25 @@ const WORD_SEPARATOR = String.raw`[ \t]+`;
1572
1988
  const WORD_BOUNDARY = String.raw`\b`;
1573
1989
  /** The already-patched form: the `<node> <tauri.js>` pair, each word quoted. */
1574
1990
  const ABSOLUTE_RUNNER_PAIR = `${QUOTED_RUNNER_WORD}${WORD_SEPARATOR}${QUOTED_RUNNER_WORD}`;
1991
+ /** Binaries Tauri may have detected the CLI behind, optionally through an absolute path. */
1992
+ const RUNNER_BINARIES = "node|bunx|bun|npx|yarn|pnpm|cargo";
1993
+ /**
1994
+ * The optional directory a detected runner is path-qualified with (`/opt/homebrew/bin/`).
1995
+ * It never contains a quote or a backslash: those belong to the string literal around the
1996
+ * command (`shellScript = "…`, a Kotlin `"…"`), and eating the opening quote leaves a
1997
+ * pbxproj Xcode refuses to open.
1998
+ */
1999
+ const RUNNER_PATH_PREFIX = String.raw`(?:[^\s"\\]*/)?`;
1575
2000
  /**
1576
2001
  * Every runner shape `tauri ios|android init` bakes in: `<binary> tauri`, npm's
1577
2002
  * `npm run tauri --` form, or a bare `tauri` — each optionally path-qualified. Longest
1578
2003
  * alternative first, so `npm run tauri --` is never truncated to its trailing `tauri`.
1579
2004
  */
1580
- const PACKAGE_RUNNER = String.raw`(?:\S*/)?npm run tauri --|(?:\S*/)?(?:${"node|bunx|bun|npx|yarn|pnpm|cargo"}) tauri|(?:\S*/)?tauri`;
2005
+ const PACKAGE_RUNNER = [
2006
+ `${RUNNER_PATH_PREFIX}npm run tauri --`,
2007
+ `${RUNNER_PATH_PREFIX}(?:${RUNNER_BINARIES}) tauri`,
2008
+ `${RUNNER_PATH_PREFIX}tauri`
2009
+ ].join("|");
1581
2010
  /** Characters that would break out of the double-quoted shell word a runner path lands in. */
1582
2011
  const SHELL_METACHARACTER_PATTERN = /[\\"$`]/g;
1583
2012
  /** A line break inside a runner path would split the generated build phase into two commands. */
@@ -2226,7 +2655,8 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
2226
2655
  /**
2227
2656
  * @file project plugin — the post-init mobile patch pass: it decides WHICH patches a
2228
2657
  * platform needs and in which order. The patches themselves live next door, in
2229
- * `signing.ts` (the Android release-signing block), `runner.ts` (the Xcode /
2658
+ * `signing.ts` (the Android release-signing block), `manifest.ts` (the Android main
2659
+ * activity's attributes, such as the orientation lock), `runner.ts` (the Xcode /
2230
2660
  * Android-Studio runner command) and `xcode-settings.ts` (the iOS
2231
2661
  * entitlements-modification setting that makes a REBUILD work).
2232
2662
  */
@@ -2251,23 +2681,26 @@ function mergePatchResults(...results) {
2251
2681
  }
2252
2682
  /**
2253
2683
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
2254
- * Android gets its release signing block; iOS gets the Xcode entitlements-modification
2255
- * setting (without it the SECOND build of the same tree fails); both platforms get the
2256
- * runner-command rewrite when the caller supplies a `runner` (omit it and the rewrite is
2257
- * skipped). iOS carries no mobile-permission plist mechanism in v1 (D-012), so signing is
2258
- * conf-only there.
2684
+ * Android gets, in this order, its release signing block, the main activity's manifest
2685
+ * attributes, then the runner command. iOS gets the Xcode entitlements-modification
2686
+ * setting (without it the SECOND build of the same tree fails), then the runner command.
2687
+ * The runner rewrite runs only when the caller supplies a `runner`. iOS takes no manifest
2688
+ * entries: its orientation lock and signing travel through the generated `Info.ios.plist`
2689
+ * sidecar and tauri.conf.json, never through the gen/ tree.
2259
2690
  *
2260
2691
  * @param projectDirectory - The Tauri project root.
2261
2692
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
2262
2693
  * @param signing - The full signing config (only `.android` is consulted).
2263
- * @returns The paths patched vs. left unchanged.
2264
- * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is missing.
2694
+ * @param manifest - Android manifest entries for the main activity (ignored on iOS).
2695
+ * @returns The paths patched vs. left unchanged, one merged report over every patch.
2696
+ * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
2697
+ * missing, or manifest entries meet a missing manifest or an unclear main activity.
2265
2698
  * @example
2266
2699
  * ```ts
2267
- * await patchMobile("/repo/.moku/tauri", { target: "ios", runner }, {});
2700
+ * await patchMobile("/repo/.moku/tauri", { target: "android", runner }, {}, orientationManifest("portrait"));
2268
2701
  * ```
2269
2702
  */
2270
- async function patchMobile(projectDirectory, opts, signing) {
2703
+ async function patchMobile(projectDirectory, opts, signing, manifest = []) {
2271
2704
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
2272
2705
  if (opts.target === "ios") {
2273
2706
  if (!existsSync(genDirectory)) return {
@@ -2283,9 +2716,10 @@ async function patchMobile(projectDirectory, opts, signing) {
2283
2716
  }
2284
2717
  const buildGradlePath = path.join(genDirectory, "app", "build.gradle.kts");
2285
2718
  if (!existsSync(genDirectory) || !existsSync(buildGradlePath)) throw new Error(`[native] Android gen/ tree not found or incomplete at ${genDirectory}.\n Run the mobile init pass (tauri android init) before patching signing state.`);
2286
- const result = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
2287
- if (!opts.runner) return result;
2288
- return mergePatchResults(result, await patchRunner(projectDirectory, genDirectory, {
2719
+ const signingResult = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
2720
+ const manifestResult = await patchAndroidManifest(projectDirectory, genDirectory, manifest);
2721
+ if (!opts.runner) return mergePatchResults(signingResult, manifestResult);
2722
+ return mergePatchResults(signingResult, manifestResult, await patchRunner(projectDirectory, genDirectory, {
2289
2723
  target: opts.target,
2290
2724
  runner: opts.runner
2291
2725
  }));
@@ -2293,11 +2727,12 @@ async function patchMobile(projectDirectory, opts, signing) {
2293
2727
  //#endregion
2294
2728
  //#region src/plugins/project/registry.ts
2295
2729
  /**
2296
- * The five v1 capability registry rows (spike (a), Tauri 2.9.x source-verified 2026-07-03).
2297
- * Four rows are backed by a real official Tauri plugin (crate + npm package + Rust init);
2298
- * `tray` is a core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust
2299
- * init, only `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that
2300
- * divergence from the other four.
2730
+ * The seven capability registry rows (the first five spike (a), Tauri 2.9.x
2731
+ * source-verified 2026-07-03; `back` and `haptics` against Tauri 2.12.1). Five rows are
2732
+ * backed by a real official Tauri plugin (crate + npm package + Rust init). `tray` is a
2733
+ * core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust init, only
2734
+ * `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that divergence.
2735
+ * `back` is core permissions alone: its whole API ships in `@tauri-apps/api/app`.
2301
2736
  */
2302
2737
  const REGISTRY = [
2303
2738
  {
@@ -2388,6 +2823,30 @@ const REGISTRY = [
2388
2823
  "android"
2389
2824
  ],
2390
2825
  confidence: "high"
2826
+ },
2827
+ {
2828
+ name: "back",
2829
+ cargoFeatures: [],
2830
+ permissions: ["core:app:allow-exit"],
2831
+ platforms: ["android"],
2832
+ confidence: "high"
2833
+ },
2834
+ {
2835
+ name: "haptics",
2836
+ npmPackage: "@tauri-apps/plugin-haptics",
2837
+ crate: "tauri-plugin-haptics",
2838
+ crateRange: "^2",
2839
+ npmRange: "^2",
2840
+ rustInit: "tauri_plugin_haptics::init()",
2841
+ cargoFeatures: [],
2842
+ permissions: [
2843
+ "haptics:allow-impact-feedback",
2844
+ "haptics:allow-notification-feedback",
2845
+ "haptics:allow-selection-feedback",
2846
+ "haptics:allow-vibrate"
2847
+ ],
2848
+ platforms: ["ios", "android"],
2849
+ confidence: "high"
2391
2850
  }
2392
2851
  ];
2393
2852
  const KNOWN_NAMES = REGISTRY.map((row) => row.name);
@@ -2464,8 +2923,8 @@ function buildConfFragment(row, config) {
2464
2923
  }
2465
2924
  /**
2466
2925
  * Typed registry lookup — resolves a capability row against optional consumer config,
2467
- * producing the full packaging contribution (conf fragment + the future-mechanism
2468
- * sidecar/manifest seams, both empty for every v1 row).
2926
+ * producing the full packaging contribution (conf fragment + the sidecar/manifest seams,
2927
+ * both empty for every row today).
2469
2928
  *
2470
2929
  * @param name - A capability name known at compile time (`keyof CapabilityConfigMap`).
2471
2930
  * @param config - Optional per-capability packaging parameters.
@@ -2493,7 +2952,8 @@ function resolve(name, config) {
2493
2952
  * @returns A fresh copy of every registry row — callers can never mutate the registry.
2494
2953
  * @example
2495
2954
  * ```ts
2496
- * registryRows().map(row => row.name); // ["store", "notification", ...]
2955
+ * registryRows().map(row => row.name);
2956
+ * // ["store", "notification", "clipboard-manager", "tray", "deep-link", "back", "haptics"]
2497
2957
  * ```
2498
2958
  */
2499
2959
  function registryRows() {
@@ -2529,6 +2989,25 @@ function resolveConfiguredCapabilities(global, target) {
2529
2989
  return resolved;
2530
2990
  }
2531
2991
  /**
2992
+ * Collects what the Android main activity must carry: the `activity-attribute` entries of
2993
+ * every capability resolved for android, then the orientation lock. Orientation comes
2994
+ * last so it wins a clash, the same order the iOS sidecar merges in. It is always present:
2995
+ * an unset orientation asks for `android:screenOrientation` to be absent, which removes a
2996
+ * lock a previous build left in the gen/ tree.
2997
+ *
2998
+ * @param global - Frozen global framework config.
2999
+ * @returns The manifest entries for `patchMobile`'s Android pass.
3000
+ * @example
3001
+ * ```ts
3002
+ * // `config` is any full native Config; no registry row carries a manifest entry today
3003
+ * androidManifestEntries({ ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } });
3004
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "portrait" }]
3005
+ * ```
3006
+ */
3007
+ function androidManifestEntries(global) {
3008
+ return [...resolveConfiguredCapabilities(global, "android").flatMap((capability) => capability.manifest).filter((entry) => entry.kind === "activity-attribute"), ...orientationManifest(global.app.orientation)];
3009
+ }
3010
+ /**
2532
3011
  * Returns the required-file set a mobile `gen/<platform>` tree must carry — the options
2533
3012
  * object keeps every target-scoped API method reading the same way.
2534
3013
  *
@@ -2652,20 +3131,18 @@ function createProjectApi(ctx) {
2652
3131
  */
2653
3132
  const checkCompleteness = (opts) => completeness(ctx.global.projectDir, opts.target);
2654
3133
  /**
2655
- * Runs the idempotent mobile post-init patch pass — Android release signing, plus the
2656
- * Xcode/Android-Studio runner-command rewrite when a `runner` is supplied.
3134
+ * Implements {@link Api.patchMobile}: hands Android its manifest entries, then logs.
2657
3135
  *
2658
- * @param opts - The patch options.
2659
- * @param opts.target - The mobile platform to patch.
2660
- * @param opts.runner - The absolute Node/`tauri.js` pair from `tauri.runner()`.
2661
- * @returns The paths patched vs. left unchanged.
3136
+ * @param opts - See {@link Api.patchMobile}.
3137
+ * @returns See {@link Api.patchMobile}.
2662
3138
  * @example
2663
3139
  * ```ts
2664
- * await runPatchMobile({ target: "ios", runner: tauri.runner() });
3140
+ * await runPatchMobile({ target: "ios" }); // { patched: [], unchanged: [] } before `tauri ios init`
2665
3141
  * ```
2666
3142
  */
2667
3143
  const runPatchMobile = async (opts) => {
2668
- const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing);
3144
+ const manifest = opts.target === "android" ? androidManifestEntries(ctx.global) : [];
3145
+ const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing, manifest);
2669
3146
  ctx.log.info("project:patchMobile", {
2670
3147
  target: opts.target,
2671
3148
  patched: result.patched.length
@@ -2766,6 +3243,10 @@ const BUILD_NUMBER_PATTERN = /^[\w.]+$/;
2766
3243
  const URL_SCHEME_PATTERN = /^[a-z][a-z\d+.-]*$/i;
2767
3244
  /** POSIX environment variable name — lands raw inside a Kotlin `System.getenv("…")` call. */
2768
3245
  const ENV_VAR_NAME_PATTERN = /^[a-z_][a-z\d_]*$/i;
3246
+ /** `#rrggbb` or `#rrggbbaa` — the hex forms Tauri parses a window colour from. */
3247
+ const HEX_COLOUR_PATTERN = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
3248
+ /** The three `Orientation` values — plain-JS config can carry anything else. */
3249
+ const ORIENTATION_PATTERN = /^(?:portrait|landscape|any)$/;
2769
3250
  /**
2770
3251
  * Validates one free-text config value that is interpolated verbatim into a generated
2771
3252
  * file. Every generated format (TOML, Kotlin, plist, XML) has its own escape rules, so a
@@ -2826,13 +3307,14 @@ function assertDeliveryDirectory(value) {
2826
3307
  /**
2827
3308
  * Validates the global config at composition time — throws `[native]`-formatted errors
2828
3309
  * for missing app identity, missing web wiring, values that would break out of the
2829
- * generated file they are written into, a `projectDir` outside the project, an `outDir`
2830
- * this app must not deliver into, unknown `config.system` names, or a `deep-link`
2831
- * composition missing its scheme.
3310
+ * generated file they are written into, a window colour or orientation outside its
3311
+ * allowed shape, a `projectDir` outside the project, an `outDir` this app must not
3312
+ * deliver into, unknown `config.system` names, or a `deep-link` composition missing its
3313
+ * scheme.
2832
3314
  *
2833
3315
  * @param global - Frozen global framework config.
2834
- * @throws {Error} When identity, web wiring, interpolated values, derived directories,
2835
- * system names, or deep-link config are invalid.
3316
+ * @throws {Error} When identity, web wiring, interpolated values, presentation fields,
3317
+ * derived directories, system names, or deep-link config are invalid.
2836
3318
  * @example
2837
3319
  * ```ts
2838
3320
  * validateProjectConfig(ctx.global);
@@ -2847,6 +3329,8 @@ function validateProjectConfig(global) {
2847
3329
  if (!global.web.dist) throw new Error("[native] web.dist is required.\n Set config.web.dist to your web build's output directory.");
2848
3330
  assertShape("app.version", global.app.version, VERSION_PATTERN, "semantic version", "Use a MAJOR.MINOR.PATCH version such as \"1.0.0\".");
2849
3331
  assertShape("app.buildNumber", global.app.buildNumber, BUILD_NUMBER_PATTERN, "build number", "Use digits, letters, dots or underscores, such as \"42\" or \"1.0.3\".");
3332
+ assertShape("app.backgroundColor", global.app.backgroundColor, HEX_COLOUR_PATTERN, "colour", "Use a hex colour such as \"#10161d\".");
3333
+ assertShape("app.orientation", global.app.orientation, ORIENTATION_PATTERN, "orientation", "Use \"portrait\", \"landscape\" or \"any\".");
2850
3334
  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.");
2851
3335
  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.");
2852
3336
  assertDerivedDirectory(global.projectDir);
@@ -2861,8 +3345,9 @@ function validateProjectConfig(global) {
2861
3345
  //#region src/plugins/project/index.ts
2862
3346
  /**
2863
3347
  * Complex tier — capability registry + generators/ + write-if-changed writer + the mobile/
2864
- * sub-domain (completeness gate, Android signing block, runner-command rewrite) + the
2865
- * guarded clean.
3348
+ * sub-domain (completeness gate, Android signing block, Android manifest attributes,
3349
+ * Xcode settings, runner-command rewrite) + the build-time orientation lock + the guarded
3350
+ * clean.
2866
3351
  *
2867
3352
  * @see README.md
2868
3353
  * @example
@@ -4095,7 +4580,7 @@ function createTauriApi(ctx) {
4095
4580
  * ```
4096
4581
  */
4097
4582
  async function run(cmd, hooks) {
4098
- const startedAt = Date.now();
4583
+ const startedAt = performance.now();
4099
4584
  /**
4100
4585
  * Scrubs one output line, forwards it to the caller's hooks, and parses
4101
4586
  * any compile-progress tick out of it.
@@ -4118,7 +4603,7 @@ function createTauriApi(ctx) {
4118
4603
  cwd: runCwd(),
4119
4604
  onLine: handleLine
4120
4605
  });
4121
- const durationMs = Date.now() - startedAt;
4606
+ const durationMs = Math.round(performance.now() - startedAt);
4122
4607
  const scrubbedStdout = scrub(result.stdout);
4123
4608
  const scrubbedStderr = scrub(result.stderr);
4124
4609
  if (result.code !== 0) {
@@ -4853,7 +5338,7 @@ function emitPhase(ctx, target, phase, status, extra) {
4853
5338
  */
4854
5339
  async function runCompileAndBundle(ctx, deps, opts) {
4855
5340
  const { target } = opts;
4856
- const startedAt = Date.now();
5341
+ const startedAt = performance.now();
4857
5342
  let transitionAt;
4858
5343
  emitPhase(ctx, target, "compile", "start");
4859
5344
  try {
@@ -4892,8 +5377,8 @@ async function runCompileAndBundle(ctx, deps, opts) {
4892
5377
  onOutput: (line) => {
4893
5378
  if (transitionAt !== void 0) return;
4894
5379
  if (!BUNDLING_TRANSITION_PATTERN.test(line)) return;
4895
- transitionAt = Date.now();
4896
- emitPhase(ctx, target, "compile", "done", { durationMs: transitionAt - startedAt });
5380
+ transitionAt = performance.now();
5381
+ emitPhase(ctx, target, "compile", "done", { durationMs: Math.round(transitionAt - startedAt) });
4897
5382
  emitPhase(ctx, target, "bundle", "start");
4898
5383
  }
4899
5384
  });
@@ -4901,14 +5386,14 @@ async function runCompileAndBundle(ctx, deps, opts) {
4901
5386
  const openPhase = transitionAt === void 0 ? "compile" : "bundle";
4902
5387
  const detail = error instanceof Error ? error.message : String(error);
4903
5388
  emitPhase(ctx, target, openPhase, "error", {
4904
- durationMs: Date.now() - (transitionAt ?? startedAt),
5389
+ durationMs: Math.round(performance.now() - (transitionAt ?? startedAt)),
4905
5390
  detail
4906
5391
  });
4907
5392
  throw error;
4908
5393
  }
4909
- const endedAt = Date.now();
5394
+ const endedAt = performance.now();
4910
5395
  if (transitionAt === void 0) {
4911
- const compileDurationMs = endedAt - startedAt;
5396
+ const compileDurationMs = Math.round(endedAt - startedAt);
4912
5397
  emitPhase(ctx, target, "compile", "done", { durationMs: compileDurationMs });
4913
5398
  emitPhase(ctx, target, "bundle", "start");
4914
5399
  emitPhase(ctx, target, "bundle", "done", { durationMs: 0 });
@@ -4917,17 +5402,18 @@ async function runCompileAndBundle(ctx, deps, opts) {
4917
5402
  bundleDurationMs: 0
4918
5403
  };
4919
5404
  }
4920
- const bundleDurationMs = endedAt - transitionAt;
5405
+ const bundleDurationMs = Math.round(endedAt - transitionAt);
4921
5406
  emitPhase(ctx, target, "bundle", "done", { durationMs: bundleDurationMs });
4922
5407
  return {
4923
- compileDurationMs: transitionAt - startedAt,
5408
+ compileDurationMs: Math.round(transitionAt - startedAt),
4924
5409
  bundleDurationMs
4925
5410
  };
4926
5411
  }
4927
5412
  /**
4928
5413
  * Runs one phase generically: emits `native:phase` start/done/error and measures
4929
- * duration, rethrowing on failure so the caller stops the pipeline (no partial-continue,
4930
- * v1) — the phase after a failing one is never started.
5414
+ * duration (monotonic clock, whole milliseconds), rethrowing on failure so the caller
5415
+ * stops the pipeline (no partial-continue, v1) — the phase after a failing one is never
5416
+ * started.
4931
5417
  *
4932
5418
  * @param ctx - The build pipeline's domain context.
4933
5419
  * @param target - The packaging target the phase runs for.
@@ -4942,11 +5428,11 @@ async function runCompileAndBundle(ctx, deps, opts) {
4942
5428
  * ```
4943
5429
  */
4944
5430
  async function runPhase(ctx, target, phase, run, detailOf) {
4945
- const startedAt = Date.now();
5431
+ const startedAt = performance.now();
4946
5432
  emitPhase(ctx, target, phase, "start");
4947
5433
  try {
4948
5434
  const result = await run();
4949
- const durationMs = Date.now() - startedAt;
5435
+ const durationMs = Math.round(performance.now() - startedAt);
4950
5436
  const detail = detailOf?.(result);
4951
5437
  emitPhase(ctx, target, phase, "done", detail === void 0 ? { durationMs } : {
4952
5438
  durationMs,
@@ -4958,7 +5444,7 @@ async function runPhase(ctx, target, phase, run, detailOf) {
4958
5444
  };
4959
5445
  } catch (error) {
4960
5446
  emitPhase(ctx, target, phase, "error", {
4961
- durationMs: Date.now() - startedAt,
5447
+ durationMs: Math.round(performance.now() - startedAt),
4962
5448
  detail: error instanceof Error ? error.message : String(error)
4963
5449
  });
4964
5450
  throw error;
@@ -5015,7 +5501,7 @@ async function runPrepare(ctx, deps, target) {
5015
5501
  */
5016
5502
  async function runPipeline(ctx, deps, opts) {
5017
5503
  const { target } = opts;
5018
- const startedAt = Date.now();
5504
+ const startedAt = performance.now();
5019
5505
  const phases = [...await runPrepare(ctx, deps, target)];
5020
5506
  const { compileDurationMs, bundleDurationMs } = await runCompileAndBundle(ctx, deps, opts);
5021
5507
  phases.push({
@@ -5034,7 +5520,7 @@ async function runPipeline(ctx, deps, opts) {
5034
5520
  phase: "collect",
5035
5521
  durationMs: collect.durationMs
5036
5522
  });
5037
- const durationMs = Date.now() - startedAt;
5523
+ const durationMs = Math.round(performance.now() - startedAt);
5038
5524
  const { outPath, artifacts } = collect.result;
5039
5525
  ctx.emit("native:complete", {
5040
5526
  target,
@@ -7006,8 +7492,9 @@ function createCliHandlers(ctx) {
7006
7492
  * ```
7007
7493
  */
7008
7494
  "native:phase"(payload) {
7009
- if (payload.status === "start") ctx.state.progress = { startedAt: Date.now() };
7010
- const elapsedMs = ctx.state.progress.startedAt ? Date.now() - ctx.state.progress.startedAt : 0;
7495
+ if (payload.status === "start") ctx.state.progress = { startedAt: performance.now() };
7496
+ const { startedAt } = ctx.state.progress;
7497
+ const elapsedMs = startedAt === void 0 ? 0 : Math.round(performance.now() - startedAt);
7011
7498
  renderPhaseEvent(ui, payload, elapsedMs);
7012
7499
  if (payload.status === "done" || payload.status === "error") ctx.state.progress = { startedAt: void 0 };
7013
7500
  },
@@ -7159,10 +7646,10 @@ const cliPlugin = createPlugin$1("cli", {
7159
7646
  *
7160
7647
  * | Field | Type | Default |
7161
7648
  * |---|---|---|
7162
- * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition |
7649
+ * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber?; orientation?; backgroundColor? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition; `orientation` (`"portrait" \| "landscape" \| "any"`) is a build-time mobile lock, `backgroundColor` a hex window colour |
7163
7650
  * | `web` | `{ build; devCommand; devUrl; dist; cwd? }` | `"bun run build"`, `"bun run dev"`, `"http://localhost:5173"`, `"dist"` |
7164
7651
  * | `system` | `ReadonlyArray<{ name: string }>` | `[]` — the composed `@moku-labs/system` plugins |
7165
- * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` |
7652
+ * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` — keys: `store`, `notification`, `clipboard-manager`, `tray`, `deep-link`, `back`, `haptics` |
7166
7653
  * | `targets` | `readonly Target[]` | `hostTargets(process.platform)` — one desktop target, mobile is opt-in |
7167
7654
  * | `projectDir` | `string` | `".moku/tauri"` — generated Tauri project (gitignored build output) |
7168
7655
  * | `outDir` | `string` | `"dist-native"` — installer delivery root |