@moku-labs/native 0.2.0 → 0.2.1

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
@@ -3,7 +3,7 @@ import { envPlugin, logPlugin, workerSafeProcessEnv } from "@moku-labs/common";
3
3
  import { createCoreConfig } from "@moku-labs/core";
4
4
  import { existsSync, readFileSync, realpathSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { cp, glob, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
6
+ import { cp, glob, lstat, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
7
7
  import os from "node:os";
8
8
  import process$1 from "node:process";
9
9
  import { Buffer } from "node:buffer";
@@ -474,9 +474,8 @@ function isDeliveryPath(candidate, boundaries = {}) {
474
474
  }
475
475
  //#endregion
476
476
  //#region src/plugins/project/clean.ts
477
- /**
478
- * @file project plugin — target-scoped destructive cleanup (pure path computation + guarded rm).
479
- */
477
+ /** Directory `xcodebuild` writes an iOS build into, below `gen/apple`. */
478
+ const IOS_BUILD_OUTPUT_DIRECTORY = "build";
480
479
  /**
481
480
  * Computes the absolute path(s) a clean pass would delete for a given scope, without
482
481
  * touching the filesystem. Mobile targets scope to `gen/<platform>` only; desktop
@@ -584,6 +583,129 @@ async function clean(projectDirectory, target) {
584
583
  }
585
584
  return { removed };
586
585
  }
586
+ /**
587
+ * Computes the directory one mobile target's PREVIOUS build output sits in, without
588
+ * touching the filesystem. iOS builds into `gen/apple/build` (`xcodebuild`'s own output
589
+ * root, read from `layout.ts`); Android has no such path here, because Gradle manages its
590
+ * `app/build` tree itself and reuses it correctly across builds.
591
+ *
592
+ * @param projectDirectory - The Tauri project root.
593
+ * @param target - The mobile packaging target.
594
+ * @returns The absolute build-output directory, or undefined when the platform has none.
595
+ * @example
596
+ * ```ts
597
+ * mobileBuildOutputPath("/repo/.moku/tauri", "ios"); // ".../src-tauri/gen/apple/build"
598
+ * ```
599
+ */
600
+ function mobileBuildOutputPath(projectDirectory, target) {
601
+ if (target !== "ios") return void 0;
602
+ return path.join(genDirectoryPath(projectDirectory, target), IOS_BUILD_OUTPUT_DIRECTORY);
603
+ }
604
+ /**
605
+ * Decides whether a build-output directory may be removed — the pure predicate in front of
606
+ * the only other recursive delete in this plugin. Two conditions, both borrowed from the
607
+ * guards that already exist: `root` must be derived state this app owns
608
+ * ({@link isDerivedPath}, the same rule {@link assertCleanableRoot} applies), and the
609
+ * candidate's REAL path must sit strictly inside `root`'s real path. Symlinks are resolved
610
+ * first, so a `build` link pointing at somebody else's directory is refused rather than
611
+ * followed.
612
+ *
613
+ * Pure by design — it is tested by calling it with unsafe paths directly, never by letting
614
+ * {@link clearMobileBuildOutput} loose on one.
615
+ *
616
+ * @param root - The configured `projectDir`.
617
+ * @param candidate - The build-output directory a clear pass wants to remove.
618
+ * @param boundaries - Overrides for cwd/home/tmp/platform/anchor; each defaults to the real value.
619
+ * @returns Whether the candidate may be removed.
620
+ * @example
621
+ * ```ts
622
+ * isClearableBuildOutput("/repo/.moku/tauri", "/repo/.moku/tauri/src-tauri/gen/apple/build"); // true
623
+ * ```
624
+ */
625
+ function isClearableBuildOutput(root, candidate, boundaries = {}) {
626
+ if (!isDerivedPath(root, boundaries)) return false;
627
+ const platform = boundaries.platform ?? process$1.platform;
628
+ return isStrictlyInside$1(realResolve(root), realResolve(candidate), platform);
629
+ }
630
+ /**
631
+ * Refuses to remove anything but a build-output directory nested inside a derived
632
+ * `projectDir` — the last gate before the recursive delete.
633
+ *
634
+ * @param root - The configured `projectDir`.
635
+ * @param candidate - The build-output directory a clear pass wants to remove.
636
+ * @param isRealDirectory - Whether the candidate is a real directory rather than a link or a
637
+ * file (default `true` — callers that have not looked at the entry assert containment only).
638
+ * @throws {Error} When `projectDir` is not derived state, when the candidate is not a real
639
+ * directory, or when its real path is not strictly inside `projectDir`.
640
+ * @example
641
+ * ```ts
642
+ * assertClearableBuildOutput("/repo/.moku/tauri", "/repo/.moku/tauri/src-tauri/gen/apple/build");
643
+ * ```
644
+ */
645
+ function assertClearableBuildOutput(root, candidate, isRealDirectory = true) {
646
+ assertCleanableRoot(root);
647
+ if (isRealDirectory && isClearableBuildOutput(root, candidate)) return;
648
+ throw new Error(`[native] Refusing to remove build output outside projectDir: ${realResolve(candidate)}.\n Remove that link by hand — "${candidate}" must be a real directory inside ${realResolve(root)}.`);
649
+ }
650
+ /**
651
+ * Reads a directory entry WITHOUT following it — the link itself, never its target — and
652
+ * reports an absent path as "no entry" rather than as a failure.
653
+ *
654
+ * `existsSync` and every other stat that follows links answers "no" for a DANGLING link, so
655
+ * a `build` symlink whose target is gone would look like a missing directory and skip the
656
+ * guard that exists to refuse it. `lstat` sees the link.
657
+ *
658
+ * @param target - The path to inspect.
659
+ * @returns The entry's own stats, or undefined when nothing is there.
660
+ * @example
661
+ * ```ts
662
+ * (await lstatSafe("/repo/.moku/tauri/src-tauri/gen/apple/build"))?.isDirectory();
663
+ * ```
664
+ */
665
+ async function lstatSafe(target) {
666
+ try {
667
+ return await lstat(target);
668
+ } catch (error) {
669
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
670
+ throw error;
671
+ }
672
+ }
673
+ /**
674
+ * Removes a mobile target's PREVIOUS build output, so the next build writes into an empty
675
+ * tree. iOS needs it: `tauri ios build` renames its freshly built `.app` into the existing
676
+ * `gen/apple/build/<app>.xcarchive`, and a second build fails there with
677
+ * `Directory not empty (os error 66)`. Android removes nothing — Gradle owns its `build`
678
+ * tree and reuses it correctly.
679
+ *
680
+ * A missing directory is fine (nothing removed). Everything that IS there goes through
681
+ * {@link assertClearableBuildOutput} first, so a symlinked `build` is refused instead of
682
+ * followed out of the project. The entry is read with {@link lstatSafe}: a dangling link is
683
+ * an entry like any other here, and reaches the guard rather than passing for a missing
684
+ * directory.
685
+ *
686
+ * @param projectDirectory - The Tauri project root.
687
+ * @param target - The mobile packaging target.
688
+ * @returns The paths actually removed — empty when there was nothing to remove.
689
+ * @throws {Error} When `projectDir` is not derived state, or the build output resolves
690
+ * outside it.
691
+ * @example
692
+ * ```ts
693
+ * await clearMobileBuildOutput("/repo/.moku/tauri", "ios");
694
+ * ```
695
+ */
696
+ async function clearMobileBuildOutput(projectDirectory, target) {
697
+ const root = path.resolve(projectDirectory);
698
+ const buildOutput = mobileBuildOutputPath(root, target);
699
+ if (!buildOutput) return { removed: [] };
700
+ const entry = await lstatSafe(buildOutput);
701
+ if (!entry) return { removed: [] };
702
+ assertClearableBuildOutput(root, buildOutput, entry.isDirectory());
703
+ await rm(buildOutput, {
704
+ recursive: true,
705
+ force: true
706
+ });
707
+ return { removed: [buildOutput] };
708
+ }
587
709
  //#endregion
588
710
  //#region src/plugins/project/generators/build-script.ts
589
711
  /**
@@ -1340,6 +1462,91 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1340
1462
  return "written";
1341
1463
  }
1342
1464
  //#endregion
1465
+ //#region src/plugins/project/mobile/files.ts
1466
+ /**
1467
+ * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
1468
+ * touch". Both iOS patches (the runner-command rewrite and the Xcode build-settings patch)
1469
+ * read the same list from here, so neither can drift into a file the other does not know
1470
+ * about — and neither ever descends into `gen/apple/build` or `gen/android/build`, which
1471
+ * belong to the toolchain.
1472
+ */
1473
+ /** Source extensions that can carry the Android runner command. */
1474
+ const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
1475
+ ".kt",
1476
+ ".kts",
1477
+ ".gradle"
1478
+ ]);
1479
+ /** Derived directories a patch scan never descends into — the toolchain owns them. */
1480
+ const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1481
+ "build",
1482
+ ".gradle",
1483
+ ".idea"
1484
+ ]);
1485
+ /**
1486
+ * Lists the generated iOS files a patch pass may rewrite: `project.yml` plus the
1487
+ * `project.pbxproj` of every generated Xcode project. `gen/apple/build` is never listed —
1488
+ * that tree is `xcodebuild` output, not project source.
1489
+ *
1490
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
1491
+ * @returns The existing files to patch.
1492
+ * @example
1493
+ * ```ts
1494
+ * await iosPatchFiles("/repo/.moku/tauri/src-tauri/gen/apple");
1495
+ * ```
1496
+ */
1497
+ async function iosPatchFiles(genDirectory) {
1498
+ const files = [];
1499
+ const projectYml = path.join(genDirectory, "project.yml");
1500
+ if (existsSync(projectYml)) files.push(projectYml);
1501
+ for (const entry of await readdir(genDirectory, { withFileTypes: true })) {
1502
+ if (!entry.isDirectory() || !entry.name.endsWith(".xcodeproj")) continue;
1503
+ const pbxproj = path.join(genDirectory, entry.name, "project.pbxproj");
1504
+ if (existsSync(pbxproj)) files.push(pbxproj);
1505
+ }
1506
+ return files;
1507
+ }
1508
+ /**
1509
+ * Walks a directory tree collecting accepted files, skipping derived build output.
1510
+ *
1511
+ * @param directory - The directory to walk (a missing directory yields nothing).
1512
+ * @param accept - Predicate over the file name.
1513
+ * @returns Every accepted file path below `directory`.
1514
+ * @example
1515
+ * ```ts
1516
+ * await collectFiles(buildSrcDirectory, name => name.endsWith(".kt"));
1517
+ * ```
1518
+ */
1519
+ async function collectFiles(directory, accept) {
1520
+ if (!existsSync(directory)) return [];
1521
+ const found = [];
1522
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
1523
+ const full = path.join(directory, entry.name);
1524
+ if (entry.isDirectory()) {
1525
+ if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
1526
+ found.push(...await collectFiles(full, accept));
1527
+ continue;
1528
+ }
1529
+ if (accept(entry.name)) found.push(full);
1530
+ }
1531
+ return found;
1532
+ }
1533
+ /**
1534
+ * Lists the generated Android files a patch pass may rewrite: every Kotlin/Gradle source
1535
+ * under `buildSrc`, plus the two top-level Gradle build files.
1536
+ *
1537
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1538
+ * @returns The existing files to patch.
1539
+ * @example
1540
+ * ```ts
1541
+ * await androidPatchFiles("/repo/.moku/tauri/src-tauri/gen/android");
1542
+ * ```
1543
+ */
1544
+ async function androidPatchFiles(genDirectory) {
1545
+ const buildSource = await collectFiles(path.join(genDirectory, "buildSrc"), (name) => ANDROID_SOURCE_EXTENSIONS.has(path.extname(name)));
1546
+ const gradleFiles = [path.join(genDirectory, "build.gradle.kts"), path.join(genDirectory, "app", "build.gradle.kts")].filter((file) => existsSync(file));
1547
+ return [...buildSource, ...gradleFiles];
1548
+ }
1549
+ //#endregion
1343
1550
  //#region src/plugins/project/mobile/runner.ts
1344
1551
  /**
1345
1552
  * @file project plugin — the runner-command rewrite. `tauri ios|android init` bakes
@@ -1352,20 +1559,8 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1352
1559
  const IOS_RUNNER_VERB = "ios xcode-script";
1353
1560
  /** The Android equivalent, written into buildSrc/gradle sources by `tauri android init`. */
1354
1561
  const ANDROID_RUNNER_VERB = "android android-studio-script";
1355
- /** Source extensions that can carry the Android runner command. */
1356
- const ANDROID_RUNNER_EXTENSIONS = /* @__PURE__ */ new Set([
1357
- ".kt",
1358
- ".kts",
1359
- ".gradle"
1360
- ]);
1361
1562
  /** A quote inside a pbxproj/Kotlin/Gradle string literal is backslash-escaped. */
1362
1563
  const ESCAPED_QUOTE = String.raw`\"`;
1363
- /** Derived directories a runner-command scan never descends into. */
1364
- const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1365
- "build",
1366
- ".gradle",
1367
- ".idea"
1368
- ]);
1369
1564
  /**
1370
1565
  * One quoted shell word, with or without the backslash a source string literal escapes its
1371
1566
  * quotes with — how an already-patched absolute runner path appears in every file we touch.
@@ -1522,69 +1717,6 @@ function quoteFor(filePath) {
1522
1717
  return filePath.endsWith(".yml") ? "\"" : ESCAPED_QUOTE;
1523
1718
  }
1524
1719
  /**
1525
- * Lists the iOS files that carry the runner command: `project.yml` plus the
1526
- * `project.pbxproj` of every generated Xcode project.
1527
- *
1528
- * @param genDirectory - The `src-tauri/gen/apple` directory.
1529
- * @returns The existing files to patch.
1530
- * @example
1531
- * ```ts
1532
- * await iosRunnerFiles("/repo/.moku/tauri/src-tauri/gen/apple");
1533
- * ```
1534
- */
1535
- async function iosRunnerFiles(genDirectory) {
1536
- const files = [];
1537
- const projectYml = path.join(genDirectory, "project.yml");
1538
- if (existsSync(projectYml)) files.push(projectYml);
1539
- for (const entry of await readdir(genDirectory, { withFileTypes: true })) {
1540
- if (!entry.isDirectory() || !entry.name.endsWith(".xcodeproj")) continue;
1541
- const pbxproj = path.join(genDirectory, entry.name, "project.pbxproj");
1542
- if (existsSync(pbxproj)) files.push(pbxproj);
1543
- }
1544
- return files;
1545
- }
1546
- /**
1547
- * Walks a directory tree collecting accepted files, skipping derived build output.
1548
- *
1549
- * @param directory - The directory to walk (a missing directory yields nothing).
1550
- * @param accept - Predicate over the file name.
1551
- * @returns Every accepted file path below `directory`.
1552
- * @example
1553
- * ```ts
1554
- * await collectFiles(buildSrcDirectory, name => name.endsWith(".kt"));
1555
- * ```
1556
- */
1557
- async function collectFiles(directory, accept) {
1558
- if (!existsSync(directory)) return [];
1559
- const found = [];
1560
- for (const entry of await readdir(directory, { withFileTypes: true })) {
1561
- const full = path.join(directory, entry.name);
1562
- if (entry.isDirectory()) {
1563
- if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
1564
- found.push(...await collectFiles(full, accept));
1565
- continue;
1566
- }
1567
- if (accept(entry.name)) found.push(full);
1568
- }
1569
- return found;
1570
- }
1571
- /**
1572
- * Lists the Android files that can carry the runner command: every Kotlin/Gradle source
1573
- * under `buildSrc`, plus the two top-level Gradle build files.
1574
- *
1575
- * @param genDirectory - The `src-tauri/gen/android` directory.
1576
- * @returns The existing files to patch.
1577
- * @example
1578
- * ```ts
1579
- * await androidRunnerFiles("/repo/.moku/tauri/src-tauri/gen/android");
1580
- * ```
1581
- */
1582
- async function androidRunnerFiles(genDirectory) {
1583
- const buildSource = await collectFiles(path.join(genDirectory, "buildSrc"), (name) => ANDROID_RUNNER_EXTENSIONS.has(path.extname(name)));
1584
- const gradleFiles = [path.join(genDirectory, "build.gradle.kts"), path.join(genDirectory, "app", "build.gradle.kts")].filter((file) => existsSync(file));
1585
- return [...buildSource, ...gradleFiles];
1586
- }
1587
- /**
1588
1720
  * Applies the runner rewrite to every candidate file for a platform, reporting which
1589
1721
  * files actually changed. A second pass rewrites the absolute pair onto itself and
1590
1722
  * reports everything unchanged.
@@ -1609,7 +1741,7 @@ async function androidRunnerFiles(genDirectory) {
1609
1741
  */
1610
1742
  async function patchRunner(projectDirectory, genDirectory, opts) {
1611
1743
  const verb = opts.target === "ios" ? IOS_RUNNER_VERB : ANDROID_RUNNER_VERB;
1612
- const files = opts.target === "ios" ? await iosRunnerFiles(genDirectory) : await androidRunnerFiles(genDirectory);
1744
+ const files = opts.target === "ios" ? await iosPatchFiles(genDirectory) : await androidPatchFiles(genDirectory);
1613
1745
  const patched = [];
1614
1746
  const unchanged = [];
1615
1747
  for (const file of files) {
@@ -1776,18 +1908,354 @@ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1776
1908
  };
1777
1909
  }
1778
1910
  //#endregion
1911
+ //#region src/plugins/project/mobile/xcode-settings.ts
1912
+ /**
1913
+ * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
1914
+ *
1915
+ * A capability plugin's build script rewrites the generated `<app>_iOS.entitlements` file
1916
+ * while Xcode is compiling, and Xcode fails the second build on that:
1917
+ * `Entitlements file "<app>_iOS.entitlements" was modified during the build, which is not
1918
+ * supported`. Xcode names the way out itself — `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION`
1919
+ * — so every `buildSettings` block of the generated `project.pbxproj` carries it, and the
1920
+ * `project.yml` target carries it too, so a later xcodegen regeneration keeps it.
1921
+ *
1922
+ * Both transforms are pure text functions over the real generated shapes: line endings,
1923
+ * indentation and every neighbouring line survive byte for byte, and a second pass is a
1924
+ * no-op.
1925
+ */
1926
+ /** The Xcode build setting that permits a build script to rewrite the entitlements file. */
1927
+ const ENTITLEMENTS_MODIFICATION_KEY = "CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION";
1928
+ /** The pbxproj value form — Xcode writes booleans as `YES`/`NO`. */
1929
+ const PBXPROJ_ENABLED_VALUE = "YES";
1930
+ /**
1931
+ * The project.yml value form. xcodegen renders a YAML boolean as `YES` in the pbxproj it
1932
+ * generates, which is why the target's sibling settings read `true`/`false` there.
1933
+ */
1934
+ const YML_ENABLED_VALUE = "true";
1935
+ /** Opens one settings block inside a `XCBuildConfiguration` section. */
1936
+ const BUILD_SETTINGS_OPEN_PATTERN = /^([ \t]*)buildSettings = \{[ \t]*$/;
1937
+ /** The setting, already present as a pbxproj assignment (whatever its value). */
1938
+ const PBXPROJ_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*=`);
1939
+ /** The setting, already present as a YAML key (whatever its value). */
1940
+ const YML_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*:`);
1941
+ /** Opens a target's `settings:` mapping in `project.yml`. */
1942
+ const YML_SETTINGS_PATTERN = /^([ \t]*)settings:[ \t]*$/;
1943
+ /** Opens the `base:` mapping a `settings:` block carries its own build settings in. */
1944
+ const YML_BASE_PATTERN = /^([ \t]*)base:[ \t]*$/;
1945
+ /** The leading whitespace of a line — never matches a line break. */
1946
+ const INDENT_PATTERN = /^[ \t]*/;
1947
+ /** Splits text into lines, keeping each line's own terminator attached to it. */
1948
+ const LINE_SPLIT_PATTERN = /(?<=\n)/;
1949
+ /** A line's terminator (LF or CRLF), stripped to compare the line's text alone. */
1950
+ const LINE_ENDING_PATTERN = /\r?\n$/;
1951
+ /** One indentation step inside a pbxproj — the generated file is tab-indented. */
1952
+ const PBXPROJ_NESTED_INDENT = " ";
1953
+ /** One indentation step inside a project.yml — YAML mappings never indent with tabs. */
1954
+ const YML_NESTED_INDENT = " ";
1955
+ /**
1956
+ * Splits text into lines that each remember their own terminator, so a file mixing (or
1957
+ * using) CRLF comes back out exactly as it went in.
1958
+ *
1959
+ * @param text - The file content.
1960
+ * @returns One entry per line, in order.
1961
+ * @example
1962
+ * ```ts
1963
+ * splitLines("a\r\nb"); // [{ body: "a", ending: "\r\n" }, { body: "b", ending: "" }]
1964
+ * ```
1965
+ */
1966
+ function splitLines$1(text) {
1967
+ return text.split(LINE_SPLIT_PATTERN).map((chunk) => {
1968
+ const body = chunk.replace(LINE_ENDING_PATTERN, "");
1969
+ return {
1970
+ body,
1971
+ ending: chunk.slice(body.length)
1972
+ };
1973
+ });
1974
+ }
1975
+ /**
1976
+ * Joins lines back into file content.
1977
+ *
1978
+ * @param lines - The lines to join.
1979
+ * @returns The file content.
1980
+ * @example
1981
+ * ```ts
1982
+ * joinLines([{ body: "a", ending: "\n" }]); // "a\n"
1983
+ * ```
1984
+ */
1985
+ function joinLines(lines) {
1986
+ return lines.map((line) => line.body + line.ending).join("");
1987
+ }
1988
+ /**
1989
+ * Reads a line's leading whitespace — the indentation a new sibling line has to match.
1990
+ *
1991
+ * @param body - The line's text.
1992
+ * @returns The leading spaces/tabs, possibly empty.
1993
+ * @example
1994
+ * ```ts
1995
+ * indentOf("\t\t\tisa = XCBuildConfiguration;"); // "\t\t\t"
1996
+ * ```
1997
+ */
1998
+ function indentOf(body) {
1999
+ return INDENT_PATTERN.exec(body)?.[0] ?? "";
2000
+ }
2001
+ /**
2002
+ * Returns a block that carries the setting exactly once: an assignment already there is
2003
+ * rewritten in place (a block that turned the setting OFF would still break the rebuild),
2004
+ * and an absent one is inserted as the block's first entry, at its siblings' indentation.
2005
+ *
2006
+ * @param block - The lines inside the block, without its opening and closing line.
2007
+ * @param options - How to place the setting.
2008
+ * @param options.present - Matches an assignment of the setting already in the block.
2009
+ * @param options.render - Renders the setting line at a given indentation.
2010
+ * @param options.fallbackIndent - Indentation used when the block carries no line to match.
2011
+ * @param options.fallbackEnding - Terminator used when the block carries no line to match.
2012
+ * @returns The block's lines, with the setting present exactly once.
2013
+ * @example
2014
+ * ```ts
2015
+ * placeSetting(block, { present: PBXPROJ_SETTING_PATTERN, render, fallbackIndent, fallbackEnding });
2016
+ * ```
2017
+ */
2018
+ function placeSetting(block, options) {
2019
+ const { present, render, fallbackIndent, fallbackEnding } = options;
2020
+ const existingIndex = block.findIndex((line) => present.test(line.body));
2021
+ if (existingIndex !== -1) return block.map((line, index) => index === existingIndex ? {
2022
+ body: render(indentOf(line.body)),
2023
+ ending: line.ending
2024
+ } : line);
2025
+ const sibling = block.find((line) => line.body.trim().length > 0);
2026
+ return [{
2027
+ body: render(sibling ? indentOf(sibling.body) : fallbackIndent),
2028
+ ending: sibling?.ending ?? fallbackEnding
2029
+ }, ...block];
2030
+ }
2031
+ /**
2032
+ * Collects the lines of one block, starting at `start` and stopping at the first line the
2033
+ * block does not own.
2034
+ *
2035
+ * @param lines - Every line of the file.
2036
+ * @param start - Index of the block's first line.
2037
+ * @param isMember - Whether a line still belongs to the block.
2038
+ * @returns The block's lines, and the index of the first line after it.
2039
+ * @example
2040
+ * ```ts
2041
+ * const { block, next } = collectBlock(lines, index, line => line.body !== "\t\t\t};");
2042
+ * ```
2043
+ */
2044
+ function collectBlock(lines, start, isMember) {
2045
+ const block = [];
2046
+ let index = start;
2047
+ while (index < lines.length) {
2048
+ const line = lines[index];
2049
+ if (!line || !isMember(line)) break;
2050
+ block.push(line);
2051
+ index += 1;
2052
+ }
2053
+ return {
2054
+ block,
2055
+ next: index
2056
+ };
2057
+ }
2058
+ /**
2059
+ * Renders the setting as a pbxproj assignment.
2060
+ *
2061
+ * @param indent - The indentation its sibling settings use.
2062
+ * @returns The assignment line.
2063
+ * @example
2064
+ * ```ts
2065
+ * renderPbxprojSetting("\t\t\t\t"); // "\t\t\t\tCODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;"
2066
+ * ```
2067
+ */
2068
+ function renderPbxprojSetting(indent) {
2069
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY} = ${PBXPROJ_ENABLED_VALUE};`;
2070
+ }
2071
+ /**
2072
+ * Renders the setting as a YAML mapping entry.
2073
+ *
2074
+ * @param indent - The indentation its sibling entries use.
2075
+ * @returns The entry line.
2076
+ * @example
2077
+ * ```ts
2078
+ * renderYmlSetting(" "); // " CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: true"
2079
+ * ```
2080
+ */
2081
+ function renderYmlSetting(indent) {
2082
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY}: ${YML_ENABLED_VALUE}`;
2083
+ }
2084
+ /**
2085
+ * Reads the `base:` mapping a target's `settings:` line opens — the one block in
2086
+ * `project.yml` that holds build settings.
2087
+ *
2088
+ * The block is walked, not peeked at: `base:` is a direct child of `settings:`, but not
2089
+ * necessarily the FIRST one — xcodegen is equally happy with `settings:` followed by
2090
+ * `groups: [app]` and `base:` below it. So every line indented deeper than `settings:` is
2091
+ * scanned until the block dedents, and the first `base:` sitting at the direct-child level
2092
+ * wins; a nested `base:` deeper inside somebody else's sub-mapping does not. A `settings:`
2093
+ * block carrying no `base:` at all owns no such block and is left alone.
2094
+ *
2095
+ * @param lines - Every line of the file.
2096
+ * @param settingsIndex - Index of the candidate `settings:` line.
2097
+ * @returns The `base:` line, its index and its indentation, or undefined when there is none.
2098
+ * @example
2099
+ * ```ts
2100
+ * baseMappingAt(splitLines(" settings:\n groups: [app]\n base:\n"), 0);
2101
+ * ```
2102
+ */
2103
+ function baseMappingAt(lines, settingsIndex) {
2104
+ const settingsLine = lines[settingsIndex];
2105
+ const settings = settingsLine && YML_SETTINGS_PATTERN.exec(settingsLine.body);
2106
+ if (!settings) return void 0;
2107
+ const settingsIndent = (settings[1] ?? "").length;
2108
+ let childIndent;
2109
+ for (let index = settingsIndex + 1; index < lines.length; index += 1) {
2110
+ const line = lines[index];
2111
+ if (!line) break;
2112
+ if (line.body.trim().length === 0) continue;
2113
+ const indent = indentOf(line.body);
2114
+ if (indent.length <= settingsIndent) break;
2115
+ childIndent ??= indent.length;
2116
+ if (indent.length !== childIndent) continue;
2117
+ if (YML_BASE_PATTERN.test(line.body)) return {
2118
+ line,
2119
+ index,
2120
+ indent
2121
+ };
2122
+ }
2123
+ }
2124
+ /**
2125
+ * Adds `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;` to every `buildSettings` block of
2126
+ * a generated `project.pbxproj`, exactly once per block and at the indentation its sibling
2127
+ * settings use. Content outside those blocks — the shell-script build phase included — is
2128
+ * returned byte for byte, and a file that already carries the setting comes back unchanged.
2129
+ *
2130
+ * @param existing - The current `project.pbxproj` content.
2131
+ * @returns The content with the setting in every settings block.
2132
+ * @example
2133
+ * ```ts
2134
+ * applyPbxprojEntitlementsSetting(await readFile(pbxprojPath, "utf8"));
2135
+ * ```
2136
+ */
2137
+ function applyPbxprojEntitlementsSetting(existing) {
2138
+ const lines = splitLines$1(existing);
2139
+ const patched = [];
2140
+ let index = 0;
2141
+ while (index < lines.length) {
2142
+ const line = lines[index];
2143
+ if (!line) break;
2144
+ patched.push(line);
2145
+ index += 1;
2146
+ const opening = BUILD_SETTINGS_OPEN_PATTERN.exec(line.body);
2147
+ if (!opening) continue;
2148
+ const blockIndent = opening[1] ?? "";
2149
+ const closing = `${blockIndent}};`;
2150
+ const { block, next } = collectBlock(lines, index, (inner) => inner.body !== closing);
2151
+ index = next;
2152
+ patched.push(...placeSetting(block, {
2153
+ present: PBXPROJ_SETTING_PATTERN,
2154
+ render: renderPbxprojSetting,
2155
+ fallbackIndent: `${blockIndent}${PBXPROJ_NESTED_INDENT}`,
2156
+ fallbackEnding: line.ending
2157
+ }));
2158
+ }
2159
+ return joinLines(patched);
2160
+ }
2161
+ /**
2162
+ * Adds the setting to every target's `settings.base` block in a generated `project.yml`, so
2163
+ * an xcodegen regeneration writes it back into the pbxproj. Only a `base:` mapping that is a
2164
+ * direct child of a `settings:` mapping is touched — a `settingGroups:` block is somebody
2165
+ * else's. A blank line inside the block does not end it: YAML mappings end at a dedent, so
2166
+ * an entry printed below an empty line is still seen and never duplicated.
2167
+ *
2168
+ * @param existing - The current `project.yml` content.
2169
+ * @returns The content with the setting under each target's `settings.base`.
2170
+ * @example
2171
+ * ```ts
2172
+ * applyProjectYmlEntitlementsSetting(await readFile(projectYmlPath, "utf8"));
2173
+ * ```
2174
+ */
2175
+ function applyProjectYmlEntitlementsSetting(existing) {
2176
+ const lines = splitLines$1(existing);
2177
+ const patched = [];
2178
+ let index = 0;
2179
+ while (index < lines.length) {
2180
+ const line = lines[index];
2181
+ if (!line) break;
2182
+ const base = baseMappingAt(lines, index);
2183
+ patched.push(line);
2184
+ index += 1;
2185
+ if (!base) continue;
2186
+ patched.push(...lines.slice(index, base.index + 1));
2187
+ index = base.index + 1;
2188
+ const { block, next } = collectBlock(lines, index, (entry) => entry.body.trim().length === 0 || indentOf(entry.body).length > base.indent.length);
2189
+ index = next;
2190
+ patched.push(...placeSetting(block, {
2191
+ present: YML_SETTING_PATTERN,
2192
+ render: renderYmlSetting,
2193
+ fallbackIndent: `${base.indent}${YML_NESTED_INDENT}`,
2194
+ fallbackEnding: base.line.ending
2195
+ }));
2196
+ }
2197
+ return joinLines(patched);
2198
+ }
2199
+ /**
2200
+ * Applies the entitlements-modification setting to every generated iOS project file —
2201
+ * `project.yml` and each `*.xcodeproj/project.pbxproj`. Idempotent: a second pass reports
2202
+ * every file unchanged. Nothing under `gen/apple/build` is ever read or written.
2203
+ *
2204
+ * @param projectDirectory - The Tauri project root.
2205
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
2206
+ * @returns The paths patched vs. left unchanged.
2207
+ * @example
2208
+ * ```ts
2209
+ * await patchXcodeSettings(projectDir, path.join(projectDir, "src-tauri/gen/apple"));
2210
+ * ```
2211
+ */
2212
+ async function patchXcodeSettings(projectDirectory, genDirectory) {
2213
+ const patched = [];
2214
+ const unchanged = [];
2215
+ for (const file of await iosPatchFiles(genDirectory)) {
2216
+ const existing = await readFile(file, "utf8");
2217
+ (await writeIfChanged(file, file.endsWith(".yml") ? applyProjectYmlEntitlementsSetting(existing) : applyPbxprojEntitlementsSetting(existing), projectDirectory) === "written" ? patched : unchanged).push(file);
2218
+ }
2219
+ return {
2220
+ patched,
2221
+ unchanged
2222
+ };
2223
+ }
2224
+ //#endregion
1779
2225
  //#region src/plugins/project/mobile/patch.ts
1780
2226
  /**
1781
2227
  * @file project plugin — the post-init mobile patch pass: it decides WHICH patches a
1782
- * platform needs and in which order. The two patches themselves live next door, in
1783
- * `signing.ts` (the Android release-signing block) and `runner.ts` (the Xcode /
1784
- * Android-Studio runner command).
2228
+ * 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 /
2230
+ * Android-Studio runner command) and `xcode-settings.ts` (the iOS
2231
+ * entitlements-modification setting that makes a REBUILD work).
2232
+ */
2233
+ /**
2234
+ * Merges the results of several patches over an overlapping file set into one report. A
2235
+ * file both patches touched is PATCHED — it appears once, and never in both lists.
2236
+ *
2237
+ * @param results - One result per patch, in the order the patches ran.
2238
+ * @returns The merged report.
2239
+ * @example
2240
+ * ```ts
2241
+ * mergePatchResults(settingsResult, runnerResult);
2242
+ * ```
1785
2243
  */
2244
+ function mergePatchResults(...results) {
2245
+ const patched = new Set(results.flatMap((result) => [...result.patched]));
2246
+ const unchanged = new Set(results.flatMap((result) => result.unchanged.filter((file) => !patched.has(file))));
2247
+ return {
2248
+ patched: [...patched],
2249
+ unchanged: [...unchanged]
2250
+ };
2251
+ }
1786
2252
  /**
1787
2253
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
1788
- * Android gets its release signing block; both platforms get the runner-command rewrite
1789
- * when the caller supplies a `runner` (omit it and the rewrite is skipped). iOS carries no
1790
- * mobile-permission plist mechanism in v1 (D-012), so signing is conf-only there.
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.
1791
2259
  *
1792
2260
  * @param projectDirectory - The Tauri project root.
1793
2261
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
@@ -1802,27 +2270,25 @@ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1802
2270
  async function patchMobile(projectDirectory, opts, signing) {
1803
2271
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
1804
2272
  if (opts.target === "ios") {
1805
- if (!opts.runner || !existsSync(genDirectory)) return {
2273
+ if (!existsSync(genDirectory)) return {
1806
2274
  patched: [],
1807
2275
  unchanged: []
1808
2276
  };
1809
- return patchRunner(projectDirectory, genDirectory, {
2277
+ const settingsResult = await patchXcodeSettings(projectDirectory, genDirectory);
2278
+ if (!opts.runner) return settingsResult;
2279
+ return mergePatchResults(settingsResult, await patchRunner(projectDirectory, genDirectory, {
1810
2280
  target: opts.target,
1811
2281
  runner: opts.runner
1812
- });
2282
+ }));
1813
2283
  }
1814
2284
  const buildGradlePath = path.join(genDirectory, "app", "build.gradle.kts");
1815
2285
  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.`);
1816
2286
  const result = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
1817
2287
  if (!opts.runner) return result;
1818
- const runnerResult = await patchRunner(projectDirectory, genDirectory, {
2288
+ return mergePatchResults(result, await patchRunner(projectDirectory, genDirectory, {
1819
2289
  target: opts.target,
1820
2290
  runner: opts.runner
1821
- });
1822
- return {
1823
- patched: [...result.patched, ...runnerResult.patched],
1824
- unchanged: [...result.unchanged, ...runnerResult.unchanged]
1825
- };
2291
+ }));
1826
2292
  }
1827
2293
  //#endregion
1828
2294
  //#region src/plugins/project/registry.ts
@@ -2253,12 +2719,34 @@ function createProjectApi(ctx) {
2253
2719
  });
2254
2720
  return result;
2255
2721
  };
2722
+ /**
2723
+ * Removes the previous build output of a mobile target, so the next compile writes into
2724
+ * an empty tree — iOS only (Gradle manages Android's own `build` tree). Guarded by the
2725
+ * same derived-path rule as {@link runClean}.
2726
+ *
2727
+ * @param opts - The clear options.
2728
+ * @param opts.target - The mobile platform whose previous build output to remove.
2729
+ * @returns The paths actually removed — empty when there was nothing to remove.
2730
+ * @example
2731
+ * ```ts
2732
+ * await runClearMobileBuildOutput({ target: "ios" });
2733
+ * ```
2734
+ */
2735
+ const runClearMobileBuildOutput = async (opts) => {
2736
+ const result = await clearMobileBuildOutput(ctx.global.projectDir, opts.target);
2737
+ ctx.log.debug("project:clearMobileBuildOutput", {
2738
+ target: opts.target,
2739
+ removed: result.removed.length
2740
+ });
2741
+ return result;
2742
+ };
2256
2743
  return {
2257
2744
  generate: generateArtifacts,
2258
2745
  getBundleLayout,
2259
2746
  getCompleteness: checkCompleteness,
2260
2747
  patchMobile: runPatchMobile,
2261
2748
  clean: runClean,
2749
+ clearMobileBuildOutput: runClearMobileBuildOutput,
2262
2750
  resolveDerivedPath,
2263
2751
  ensureIconSource,
2264
2752
  resolve,
@@ -4294,6 +4782,8 @@ async function runIcons(ctx, deps, opts) {
4294
4782
  }
4295
4783
  /** Matches a tauri build output line signalling the compile→bundle transition. */
4296
4784
  const BUNDLING_TRANSITION_PATTERN = /bundling/i;
4785
+ /** Compile-phase detail reported when a previous build's output had to be removed first. */
4786
+ const CLEARED_BUILD_OUTPUT_DETAIL = "cleared previous build output";
4297
4787
  /**
4298
4788
  * Formats a compile tick into the `native:phase` "progress" detail string — real crate
4299
4789
  * counts, never a fake percentage.
@@ -4345,6 +4835,12 @@ function emitPhase(ctx, target, phase, status, extra) {
4345
4835
  * transition line ever appears, `compile` closes at exit and `bundle` is reported as a
4346
4836
  * zero-duration pass. A failure is attributed to whichever phase is open.
4347
4837
  *
4838
+ * iOS opens with one extra step: the previous build's output is removed before the
4839
+ * compiler starts. `tauri ios build` renames its fresh `.app` into the existing
4840
+ * `gen/apple/build` archive and fails the SECOND build of the same tree with
4841
+ * `Directory not empty`. Removing it is part of compile, so a refusal from the guarded
4842
+ * remove surfaces as a compile error rather than an unattributed throw.
4843
+ *
4348
4844
  * @param ctx - The build pipeline's domain context.
4349
4845
  * @param deps - The resolved project/tauri APIs.
4350
4846
  * @param opts - The target plus the platform build flags to forward.
@@ -4361,6 +4857,9 @@ async function runCompileAndBundle(ctx, deps, opts) {
4361
4857
  let transitionAt;
4362
4858
  emitPhase(ctx, target, "compile", "start");
4363
4859
  try {
4860
+ if (target === "ios") {
4861
+ if ((await deps.project.clearMobileBuildOutput({ target })).removed.length > 0) emitPhase(ctx, target, "compile", "progress", { detail: CLEARED_BUILD_OUTPUT_DETAIL });
4862
+ }
4364
4863
  await deps.tauri.build({
4365
4864
  target,
4366
4865
  simulator: opts.simulator,
@@ -6241,28 +6740,35 @@ const BOX_CHROME_COLUMNS = 6;
6241
6740
  */
6242
6741
  const MIN_TAIL_LINE_LENGTH = 40;
6243
6742
  /**
6244
- * Widest tail line the failure box keeps, derived from the branded console's own width —
6245
- * which {@link terminalWidth} bound to the terminal, so the box follows the real terminal
6246
- * instead of a fixed guess. A single Rust/xcodebuild diagnostic can run thousands of
6247
- * characters; unbounded, it wraps the branded box into unreadable noise, and a fixed bound
6248
- * wide enough to matter (160) wrapped every ordinary 80-column terminal just the same.
6743
+ * Decides how wide a tail line may be — or that it may be any width at all.
6744
+ *
6745
+ * With a terminal attached, the bound follows the real terminal ({@link terminalWidth}
6746
+ * clamps it) minus the box chrome: a single Rust/xcodebuild diagnostic can run thousands of
6747
+ * characters and would wrap the branded box into unreadable noise.
6249
6748
  *
6250
- * @param consoleWidth - The branded console's width (`ui.width`).
6251
- * @returns The maximum tail line length for that width.
6749
+ * With no terminal — CI, `native build > build.log`, a piped run — there is nothing to wrap
6750
+ * against, and the output is READ afterwards: truncating there deletes the one copy of the
6751
+ * toolchain's own error text. So a stream without columns gets no bound at all.
6752
+ *
6753
+ * @param columns - The stream's column count (`process.stdout.columns`), undefined when piped.
6754
+ * @returns The maximum tail line length, or undefined when lines must be kept whole.
6252
6755
  * @example
6253
6756
  * ```ts
6254
- * maxTailLineLength(66); // 60
6255
- * maxTailLineLength(120); // 114
6757
+ * tailLineBound(120); // 114
6758
+ * tailLineBound(40); // 54 — clamped up to 60, minus the chrome
6759
+ * tailLineBound(undefined); // undefined — piped: keep the full line
6256
6760
  * ```
6257
6761
  */
6258
- function maxTailLineLength(consoleWidth) {
6259
- return Math.max(MIN_TAIL_LINE_LENGTH, consoleWidth - BOX_CHROME_COLUMNS);
6762
+ function tailLineBound(columns) {
6763
+ if (columns === void 0) return void 0;
6764
+ return Math.max(MIN_TAIL_LINE_LENGTH, terminalWidth(columns) - BOX_CHROME_COLUMNS);
6260
6765
  }
6261
6766
  /**
6262
- * Truncates one tail line to `budget`, marking the cut with an ellipsis.
6767
+ * Truncates one tail line to `budget`, marking the cut with an ellipsis. An undefined
6768
+ * budget keeps the line whole.
6263
6769
  *
6264
6770
  * @param line - One line of the scrubbed stderr tail.
6265
- * @param budget - The maximum length, from {@link maxTailLineLength}.
6771
+ * @param budget - The maximum length, from {@link tailLineBound}.
6266
6772
  * @returns The line, at most `budget` characters long.
6267
6773
  * @example
6268
6774
  * ```ts
@@ -6270,26 +6776,38 @@ function maxTailLineLength(consoleWidth) {
6270
6776
  * ```
6271
6777
  */
6272
6778
  function truncateLine(line, budget) {
6273
- if (line.length <= budget) return line;
6779
+ if (budget === void 0 || line.length <= budget) return line;
6274
6780
  return `${line.slice(0, budget - 1)}…`;
6275
6781
  }
6276
6782
  /**
6277
- * Renders a failed build: the classified {@link TauriError}'s scrubbed stderr tail framed
6278
- * in a branded box, then the `[native]` error line. Cause first, verdict second —
6279
- * the tail is the only place the real toolchain diagnostic survives. A non-`TauriError`
6280
- * failure (or an empty tail) prints the error line alone.
6783
+ * Renders a failed build: the classified {@link TauriError}'s scrubbed stderr tail first,
6784
+ * then the `[native]` error line. Cause first, verdict second — the tail is the only place
6785
+ * the real toolchain diagnostic survives. A non-`TauriError` failure (or an empty tail)
6786
+ * prints the error line alone.
6787
+ *
6788
+ * How the tail is framed follows the stream, for the same reason its lines are (or are not)
6789
+ * truncated ({@link tailLineBound}). With a terminal attached it is a branded box, cut to
6790
+ * the terminal's width. With none — CI, `native build > build.log`, a pipe — every line is
6791
+ * printed plainly, in order: the box pads each line to the widest one, so a single
6792
+ * 5000-character Rust diagnostic would pad the entire tail to 5000 columns and bloat the
6793
+ * very log the lines were kept whole for.
6281
6794
  *
6282
6795
  * @param ui - The branded console to render through.
6283
6796
  * @param error - The failure thrown by `build.run`/`build.runAll`.
6797
+ * @param columns - The stream's column count (default: `process.stdout.columns`).
6284
6798
  * @example
6285
6799
  * ```ts
6286
6800
  * try { await build.run({ target: "macos" }); } catch (error) { renderBuildFailure(ui, error); throw error; }
6287
6801
  * ```
6288
6802
  */
6289
- function renderBuildFailure(ui, error) {
6803
+ function renderBuildFailure(ui, error, columns = process.stdout.columns) {
6290
6804
  const stderrTail = error instanceof TauriError ? error.stderrTail.trim() : "";
6291
- const budget = maxTailLineLength(ui.width);
6292
- if (stderrTail) ui.box(stderrTail.split(/\r?\n/).map((line) => truncateLine(line, budget)));
6805
+ const budget = tailLineBound(columns);
6806
+ if (stderrTail) {
6807
+ const tailLines = stderrTail.split(/\r?\n/);
6808
+ if (budget === void 0) for (const line of tailLines) ui.line(line);
6809
+ else ui.box(tailLines.map((line) => truncateLine(line, budget)));
6810
+ }
6293
6811
  ui.error(error instanceof Error ? error.message : String(error));
6294
6812
  }
6295
6813
  //#endregion