@limrun/api 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/index.d.mts +3 -1
  3. package/index.d.mts.map +1 -1
  4. package/index.d.ts +3 -1
  5. package/index.d.ts.map +1 -1
  6. package/index.js +17 -1
  7. package/index.js.map +1 -1
  8. package/index.mjs +2 -0
  9. package/index.mjs.map +1 -1
  10. package/internal/direct-instance-errors.d.mts +9 -0
  11. package/internal/direct-instance-errors.d.mts.map +1 -1
  12. package/internal/direct-instance-errors.d.ts +9 -0
  13. package/internal/direct-instance-errors.d.ts.map +1 -1
  14. package/internal/direct-instance-errors.js +6 -1
  15. package/internal/direct-instance-errors.js.map +1 -1
  16. package/internal/direct-instance-errors.mjs +5 -1
  17. package/internal/direct-instance-errors.mjs.map +1 -1
  18. package/internal/proxy-transport.d.mts +9 -0
  19. package/internal/proxy-transport.d.mts.map +1 -1
  20. package/internal/proxy-transport.d.ts +9 -0
  21. package/internal/proxy-transport.d.ts.map +1 -1
  22. package/internal/proxy-transport.js +19 -0
  23. package/internal/proxy-transport.js.map +1 -1
  24. package/internal/proxy-transport.mjs +19 -0
  25. package/internal/proxy-transport.mjs.map +1 -1
  26. package/internal/sse-fetch.d.mts +11 -0
  27. package/internal/sse-fetch.d.mts.map +1 -0
  28. package/internal/sse-fetch.d.ts +11 -0
  29. package/internal/sse-fetch.d.ts.map +1 -0
  30. package/internal/sse-fetch.js +23 -0
  31. package/internal/sse-fetch.js.map +1 -0
  32. package/internal/sse-fetch.mjs +20 -0
  33. package/internal/sse-fetch.mjs.map +1 -0
  34. package/package.json +21 -1
  35. package/rbe-session.d.mts +35 -0
  36. package/rbe-session.d.mts.map +1 -0
  37. package/rbe-session.d.ts +35 -0
  38. package/rbe-session.d.ts.map +1 -0
  39. package/rbe-session.js +72 -0
  40. package/rbe-session.js.map +1 -0
  41. package/rbe-session.mjs +65 -0
  42. package/rbe-session.mjs.map +1 -0
  43. package/rbe-workspace.d.mts +163 -0
  44. package/rbe-workspace.d.mts.map +1 -0
  45. package/rbe-workspace.d.ts +163 -0
  46. package/rbe-workspace.d.ts.map +1 -0
  47. package/rbe-workspace.js +394 -0
  48. package/rbe-workspace.js.map +1 -0
  49. package/rbe-workspace.mjs +382 -0
  50. package/rbe-workspace.mjs.map +1 -0
  51. package/resources/xcode-instances-helpers.d.mts +61 -0
  52. package/resources/xcode-instances-helpers.d.mts.map +1 -1
  53. package/resources/xcode-instances-helpers.d.ts +61 -0
  54. package/resources/xcode-instances-helpers.d.ts.map +1 -1
  55. package/resources/xcode-instances-helpers.js +126 -7
  56. package/resources/xcode-instances-helpers.js.map +1 -1
  57. package/resources/xcode-instances-helpers.mjs +127 -8
  58. package/resources/xcode-instances-helpers.mjs.map +1 -1
  59. package/src/index.ts +25 -0
  60. package/src/internal/direct-instance-errors.ts +11 -1
  61. package/src/internal/proxy-transport.ts +22 -0
  62. package/src/internal/sse-fetch.ts +20 -0
  63. package/src/rbe-session.ts +92 -0
  64. package/src/rbe-workspace.ts +407 -0
  65. package/src/resources/xcode-instances-helpers.ts +223 -13
  66. package/src/version.ts +1 -1
  67. package/version.d.mts +1 -1
  68. package/version.d.ts +1 -1
  69. package/version.js +1 -1
  70. package/version.mjs +1 -1
@@ -0,0 +1,92 @@
1
+ import type { RbeStatus, XcodeClient } from './resources/xcode-instances-helpers';
2
+
3
+ /**
4
+ * Client-side helpers for driving an instance's RBE stack: waiting for it to
5
+ * come up and riding out the transient gateway errors that occur right after
6
+ * instance creation. Shared by the CLI and pure-SDK consumers (e.g. CI
7
+ * actions).
8
+ */
9
+
10
+ export type Sleep = (ms: number) => Promise<void>;
11
+ export const defaultSleep: Sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+
13
+ /**
14
+ * Matches the transient gateway / dropped-connection errors that occur right
15
+ * after an instance is created, when its proxy path is not fully serving yet.
16
+ *
17
+ * The HTTP part anchors on the exact `failed: <code>` shape `directInstanceHttpError`
18
+ * produces (`${operation} failed: ${status}...`), so a bare 502/503/504 buried in
19
+ * a response body or an instance id does NOT count as transient. Fetch-thrown
20
+ * network errors carry their own names and are matched directly. A 404 never
21
+ * reaches here; `readRbeResponse` maps it to RbeUnsupportedError first.
22
+ */
23
+ const TRANSIENT = /failed: (?:502|503|504)\b|\bEOF\b|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed/i;
24
+
25
+ export function isTransientError(err: unknown): boolean {
26
+ const message = err instanceof Error ? err.message : String(err);
27
+ return TRANSIENT.test(message);
28
+ }
29
+
30
+ /**
31
+ * Retries `fn` on transient gateway errors (or on whatever `retryOn` matches
32
+ * when given). Non-matching errors propagate immediately. After exhausting
33
+ * `attempts`, throws the last error.
34
+ */
35
+ export async function retryTransient<T>(
36
+ fn: () => Promise<T>,
37
+ opts: {
38
+ sleep?: Sleep;
39
+ log?: (msg: string) => void;
40
+ attempts?: number;
41
+ retryOn?: (err: unknown) => boolean;
42
+ } = {},
43
+ ): Promise<T> {
44
+ const sleep = opts.sleep ?? defaultSleep;
45
+ const attempts = opts.attempts ?? 5;
46
+ const retryOn = opts.retryOn ?? isTransientError;
47
+ let lastErr: unknown;
48
+ for (let attempt = 1; attempt <= attempts; attempt++) {
49
+ try {
50
+ return await fn();
51
+ } catch (err) {
52
+ if (!retryOn(err)) {
53
+ throw err;
54
+ }
55
+ lastErr = err;
56
+ if (attempt < attempts) {
57
+ const message = err instanceof Error ? err.message : String(err);
58
+ opts.log?.(`Retrying after error (${message.trim()})...`);
59
+ await sleep(2000 * attempt);
60
+ }
61
+ }
62
+ }
63
+ throw lastErr;
64
+ }
65
+
66
+ /** RbeStatus once the stack is running: frontendPort and xcodeVersion are set. */
67
+ export type RunningRbeStatus = RbeStatus & Required<Pick<RbeStatus, 'frontendPort' | 'xcodeVersion'>>;
68
+
69
+ /**
70
+ * Polls `getRbe` until the stack is `running` (with a usable frontend port and
71
+ * Xcode version), starting from the `initial` status returned by `startRbe`.
72
+ * Each poll is wrapped in retryTransient so a transient blip mid-startup does
73
+ * not abort. Throws when the stack ends in `failed`, stays `starting` past
74
+ * `maxAttempts`, or reports `running` without the fields the caller needs.
75
+ */
76
+ export async function waitForRbeRunning(
77
+ client: Pick<XcodeClient, 'getRbe'>,
78
+ initial: RbeStatus,
79
+ opts: { sleep?: Sleep; maxAttempts?: number } = {},
80
+ ): Promise<RunningRbeStatus> {
81
+ const sleep = opts.sleep ?? defaultSleep;
82
+ const maxAttempts = opts.maxAttempts ?? 15;
83
+ let status = initial;
84
+ for (let attempt = 0; status.state === 'starting' && attempt < maxAttempts; attempt++) {
85
+ await sleep(2000);
86
+ status = await retryTransient(() => client.getRbe(), { sleep });
87
+ }
88
+ if (status.state !== 'running' || !status.frontendPort || !status.xcodeVersion) {
89
+ throw new Error(`Remote-execution stack failed to start: ${status.error ?? `state is ${status.state}`}`);
90
+ }
91
+ return status as RunningRbeStatus;
92
+ }
@@ -0,0 +1,407 @@
1
+ // Mirrored between src/rbe-workspace.ts (canonical) and packages/cli/src/lib/rbe-workspace.ts
2
+ // until the CLI imports it from a published @limrun/api; tests/rbe-copy-sync.test.ts keeps the
3
+ // two copies byte-identical. Apply any edit to both.
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+
7
+ /**
8
+ * Generates the .limrun/ workspace companion for Limrun remote execution: a Bazel
9
+ * package pinning the remote fleet's Xcode version and an rc fragment with the
10
+ * remote-execution flags under the `limrun` config. The caller learns the
11
+ * fleet's version key from the instance's RBE status, so the generated config
12
+ * always matches the fleet without any user action; regenerating the files
13
+ * after a fleet Xcode upgrade refreshes the pin.
14
+ */
15
+
16
+ export const LIMRUN_DIR = '.limrun';
17
+ export const TRY_IMPORT_LINE = 'try-import %workspace%/.limrun/bazelrc';
18
+ const TRY_IMPORT_COMMENT = '# Added by Limrun remote-execution setup: loads the generated config.';
19
+
20
+ const WORKSPACE_MARKERS = ['MODULE.bazel', 'WORKSPACE', 'WORKSPACE.bazel'];
21
+
22
+ /**
23
+ * Finds the Bazel workspace root by walking up from `startDir` to the first
24
+ * ancestor containing a MODULE.bazel / WORKSPACE / WORKSPACE.bazel, mirroring
25
+ * how Bazel itself locates the workspace when run from a subdirectory. Returns
26
+ * null when no workspace is found up to the filesystem root. The generated
27
+ * `.limrun/` and the `try-import` must live at this root, since `%workspace%`
28
+ * in bazelrc resolves here regardless of the directory the build is run from.
29
+ */
30
+ export function findBazelWorkspaceRoot(startDir: string): string | null {
31
+ let dir = path.resolve(startDir);
32
+ for (;;) {
33
+ if (WORKSPACE_MARKERS.some((m) => fs.existsSync(path.join(dir, m)))) {
34
+ return dir;
35
+ }
36
+ const parent = path.dirname(dir);
37
+ if (parent === dir) {
38
+ return null;
39
+ }
40
+ dir = parent;
41
+ }
42
+ }
43
+
44
+ const APP_RULE_RE = /\b(?:ios|macos|tvos|watchos)_application\s*\(/;
45
+ const TARGET_NAME_RE = /^\s*name\s*=\s*"([^"]+)"/;
46
+ const TARGET_SCAN_SKIP_DIRS = new Set(['.git', 'node_modules', '.limrun']);
47
+
48
+ /**
49
+ * Best-effort guess of a single buildable app target to show in the printed
50
+ * build command, so it reads `//App` instead of a `//your:target` placeholder.
51
+ * Scans the workspace's BUILD files (buildifier-formatted) for apple
52
+ * `*_application` rules (no bazel invocation) and returns the label in short
53
+ * form (`//pkg` when the target name matches the package's last segment).
54
+ * Returns null when there are zero or multiple candidates (ambiguous → caller
55
+ * keeps the placeholder).
56
+ */
57
+ export function inferBuildTarget(workspaceRoot: string): string | null {
58
+ const found: string[] = [];
59
+ const walk = (dir: string): void => {
60
+ if (found.length > 1) return; // already ambiguous; stop early
61
+ let entries: fs.Dirent[];
62
+ try {
63
+ entries = fs.readdirSync(dir, { withFileTypes: true });
64
+ } catch {
65
+ return;
66
+ }
67
+ for (const entry of entries) {
68
+ if (entry.isDirectory()) {
69
+ if (TARGET_SCAN_SKIP_DIRS.has(entry.name) || entry.name.startsWith('bazel-')) continue;
70
+ walk(path.join(dir, entry.name));
71
+ } else if (entry.name === 'BUILD' || entry.name === 'BUILD.bazel') {
72
+ collectAppTargets(path.join(dir, entry.name), workspaceRoot, found);
73
+ }
74
+ }
75
+ };
76
+ walk(workspaceRoot);
77
+ return found.length === 1 ? found[0]! : null;
78
+ }
79
+
80
+ /** Appends `//pkg[:name]` labels of apple application rules in one BUILD file. */
81
+ function collectAppTargets(buildFile: string, workspaceRoot: string, out: string[]): void {
82
+ let content: string;
83
+ try {
84
+ content = fs.readFileSync(buildFile, 'utf8');
85
+ } catch {
86
+ return;
87
+ }
88
+ const pkg = path.relative(workspaceRoot, path.dirname(buildFile)).split(path.sep).join('/');
89
+ let inAppRule = false;
90
+ for (const line of content.split('\n')) {
91
+ // Skip comment lines so a commented-out `# ios_application(` can't start a
92
+ // phantom rule (and a commented `# name = ...` can't be captured), which
93
+ // would otherwise leave inAppRule set and mislabel a later rule's name.
94
+ if (line.trimStart().startsWith('#')) continue;
95
+ if (!inAppRule) {
96
+ if (APP_RULE_RE.test(line)) inAppRule = true;
97
+ continue;
98
+ }
99
+ const match = line.match(TARGET_NAME_RE);
100
+ if (match) {
101
+ const name = match[1]!;
102
+ const last = pkg.split('/').pop();
103
+ out.push(
104
+ pkg === '' || pkg === '.' ? `//:${name}`
105
+ : last === name ? `//${pkg}`
106
+ : `//${pkg}:${name}`,
107
+ );
108
+ inAppRule = false;
109
+ } else if (/^\)/.test(line)) {
110
+ inAppRule = false; // rule closed before a name line we could read
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Reads the workspace's pinned Bazel major version from `.bazelversion`, or
117
+ * null when the file is absent or its first line has no leading integer.
118
+ *
119
+ * Used to decide whether the generated BUILD must `load` the Xcode rules from
120
+ * apple_support: in Bazel 9 they are no longer native globals and must be
121
+ * loaded, while in Bazel 8 they ARE native globals and the apple_support rule
122
+ * impls `fail()` on the unmigrated Bazel, so loading them there breaks
123
+ * analysis. The generator runs in the workspace on the client, so the file is
124
+ * the authoritative signal for the Bazel that bazelisk will launch.
125
+ */
126
+ export function detectBazelMajorVersion(workspaceDir: string): number | null {
127
+ try {
128
+ const raw = fs.readFileSync(path.join(workspaceDir, '.bazelversion'), 'utf8');
129
+ const firstLine = (raw.split('\n', 1)[0] ?? '').trim();
130
+ const match = firstLine.match(/^(\d+)/);
131
+ return match ? Number(match[1]) : null;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Whether to treat the workspace as Bazel 9+ for RBE config: true when the
139
+ * detected major version is >= 9, OR unknown (no `.bazelversion` means bazelisk
140
+ * runs the latest release, which is 9+). This single predicate decides both
141
+ * emitting the apple_support Xcode-rule loads and surfacing the SHA256 digest
142
+ * hint, so the two stay in lockstep.
143
+ */
144
+ export function isBazel9OrLater(bazelMajor: number | null): boolean {
145
+ return bazelMajor === null || bazelMajor >= 9;
146
+ }
147
+
148
+ /** Major.minor short alias (e.g. "26.4") used for the SDK default and --xcode_version. */
149
+ function shortVersion(versionKey: string): string {
150
+ const parts = versionKey.split('.');
151
+ if (parts.length < 3) {
152
+ throw new Error(`unexpected Xcode version key from the instance: ${versionKey}`);
153
+ }
154
+ return `${parts[0]}.${parts[1]}`;
155
+ }
156
+
157
+ /** Renders one xcode_version rule from a major.minor.patch.build version key. */
158
+ function renderXcodeVersionRule(name: string, versionKey: string): string {
159
+ // shortVersion validates the key shape (major.minor.patch[.build]) and yields
160
+ // the major.minor used for both the SDK defaults and the short alias.
161
+ const sdk = shortVersion(versionKey);
162
+ const parts = versionKey.split('.');
163
+ const fullAlias = `${parts[0]}.${parts[1]}.${parts[2]}`;
164
+ return `xcode_version(
165
+ name = "${name}",
166
+ aliases = [
167
+ "${sdk}",
168
+ "${fullAlias}",
169
+ ],
170
+ default_ios_sdk_version = "${sdk}",
171
+ default_macos_sdk_version = "${sdk}",
172
+ default_tvos_sdk_version = "${sdk}",
173
+ default_watchos_sdk_version = "${sdk}",
174
+ version = "${versionKey}",
175
+ )`;
176
+ }
177
+
178
+ /**
179
+ * Renders an `available_xcodes` set with a single member that is also its
180
+ * mandatory default. Both sets the BUILD file emits (remote, local) are
181
+ * single-version sets of this shape, pointing at the same fleet pin.
182
+ */
183
+ function renderAvailableXcodes(name: string, target: string): string {
184
+ return `available_xcodes(
185
+ name = "${name}",
186
+ default = "${target}",
187
+ versions = ["${target}"],
188
+ )`;
189
+ }
190
+
191
+ /**
192
+ * Renders the generated Bazel package pinning the Xcode version to the fleet's.
193
+ *
194
+ * remoteVersionKey is the fleet's `xcodebuild -version` in major.minor.patch.build
195
+ * form (e.g. 26.4.0.17E192).
196
+ *
197
+ * Uses Bazel's remote/local `xcode_config` split with BOTH sets pointing at the
198
+ * SAME fleet pin (rather than a single `default=/versions=` bucket, which
199
+ * resolves with availability UNKNOWN and leaves Apple/Swift actions eligible for
200
+ * local execution). With local == remote, `--xcode_version` resolves as
201
+ * "mutually available" (BOTH), which declares up front that this build uses only
202
+ * the fleet's Xcode AND keeps apple_support from emitting its remote-only
203
+ * "...specified, but it is not available locally..." DEBUG notice (that notice
204
+ * fires only when the pinned version is in `remote_versions` but not
205
+ * `local_versions`).
206
+ *
207
+ * We intentionally do NOT name the client's own local Xcode: under
208
+ * `--config=limrun` every action runs remotely (`--spawn_strategy=remote` +
209
+ * `--noremote_local_fallback`), so a local DEVELOPER_DIR is never resolved.
210
+ * Declaring a distinct local version would only reintroduce that DEBUG notice on
211
+ * a client whose Xcode differs from the fleet's. (The fleet pin is used, not
212
+ * Bazel's `@local_config_xcode//:host_available_xcodes`: that repo is not
213
+ * visible from the main module under bzlmod and is never generated off-darwin.)
214
+ *
215
+ * When `emitLoads` is true (Bazel 9+), the Xcode rules are loaded from
216
+ * apple_support; on Bazel 8 they are native globals and MUST NOT be loaded
217
+ * (the apple_support rule impls fail on the unmigrated Bazel).
218
+ */
219
+ export function renderXcodeConfigBuild(remoteVersionKey: string, emitLoads: boolean): string {
220
+ // Bazel 9 migrated xcode_version/available_xcodes/xcode_config out of native
221
+ // globals into apple_support; they must be loaded there. The repo_name
222
+ // @build_bazel_apple_support is the apple_support module convention.
223
+ const loads =
224
+ emitLoads ?
225
+ `load("@build_bazel_apple_support//xcode:xcode_version.bzl", "xcode_version")
226
+ load("@build_bazel_apple_support//xcode:available_xcodes.bzl", "available_xcodes")
227
+ load("@build_bazel_apple_support//xcode:xcode_config.bzl", "xcode_config")
228
+
229
+ `
230
+ : '';
231
+ const remoteRule = renderXcodeVersionRule('remote_xcode', remoteVersionKey);
232
+
233
+ return `# Generated by lim xcode rbe. Do not edit; rerun the command to refresh.
234
+ #
235
+ # Pins the Xcode version Bazel uses to the limrun fleet's Xcode, independent of
236
+ # any Xcode installed on this machine. Both the remote and local sets point at
237
+ # the SAME pin so --xcode_version resolves as mutually available (no
238
+ # apple_support remote-only DEBUG notice); under --config=limrun all actions run
239
+ # remotely, so a local DEVELOPER_DIR is never resolved. Selected via
240
+ # .limrun/bazelrc (--config=limrun).
241
+ ${loads}${remoteRule}
242
+
243
+ # Both sets point at the single fleet pin.
244
+ ${renderAvailableXcodes('remote_xcodes', ':remote_xcode')}
245
+
246
+ ${renderAvailableXcodes('local_xcodes', ':remote_xcode')}
247
+
248
+ xcode_config(
249
+ name = "remote_xcode_config",
250
+ remote_versions = ":remote_xcodes",
251
+ local_versions = ":local_xcodes",
252
+ )
253
+ `;
254
+ }
255
+
256
+ /**
257
+ * Renders the rc fragment with the remote-execution flags under
258
+ * --config=limrun.
259
+ *
260
+ * - `--remote_cache=` (empty) clears any workspace-level `--remote_cache`. The
261
+ * limrun executor carries its own CAS, so a separate cache backend (e.g. a
262
+ * repo pointing `--remote_cache` at BuildBuddy/EngFlow) splits inputs and
263
+ * outputs across two stores the executor cannot reconcile, surfacing as "Lost
264
+ * inputs no longer available remotely". Emptying it under --config=limrun
265
+ * routes caching back to the executor's CAS while leaving the repo's non-limrun
266
+ * builds (where that cache is valid) untouched.
267
+ * - The `--bes_*` flags stream the Build Event Protocol to the daemon's BES
268
+ * service, co-hosted on the same RBE frontend as the executor (hence the same
269
+ * `127.0.0.1:${port}`), powering the live + persisted console.
270
+ * `--bes_upload_mode=nowait_for_upload_complete` keeps the current build from
271
+ * blocking at exit on the BES upload (the wait moves to the start of the next
272
+ * invocation, bounded by `--bes_timeout`), while streams stay complete/acked
273
+ * for the persisted record. An older daemon without the BES service registered
274
+ * answers PublishBuildEvent with a non-fatal warning, so the flags are safe
275
+ * ahead of the image rollout.
276
+ * - `--xcode_version` pins the fleet's version: without it, a mac client
277
+ * lacking that exact version has no mutual version and silently falls back
278
+ * to its LOCAL default, shipping the wrong version to the remote worker via
279
+ * XCODE_VERSION_OVERRIDE (the worker then rejects it).
280
+ * - `--strategy=SwiftCompile=remote` / `--strategy=Genrule=remote` override
281
+ * mnemonic-specific strategies a workspace may pin (rules_swift defaults
282
+ * SwiftCompile to a local persistent `worker`; repos often pin Genrule to
283
+ * `standalone`). Those run locally and break RBE: a local Swift worker can't
284
+ * run on a Linux client at all, and on a mac it would demand the fleet's
285
+ * Xcode locally. --spawn_strategy=remote does not override per-mnemonic
286
+ * pins, so these explicit overrides are required.
287
+ * - `--ios_multi_cpus=sim_arm64` pins the app to the **arm64 iOS simulator**.
288
+ * Limrun's Mac fleet (workers and the attached simulators) is Apple Silicon,
289
+ * so the build product must be arm64. Without this, the simulator cpu follows
290
+ * the CLIENT's Bazel default (`sim_arm64` on an Apple Silicon Mac, but
291
+ * `x86_64` on an Intel Mac or a Linux client), and an x86_64 app installed on
292
+ * the arm64 fleet simulator fails to launch with "needs to be updated by the
293
+ * developer to work on this version of iOS". The pin makes the artifact match
294
+ * the fleet regardless of where bazel runs (the whole point of RBE).
295
+ * - PATH includes /usr/sbin:/sbin so genrules that probe `sysctl` (e.g.
296
+ * `hw.logicalcpu` for `make -j`) resolve it on the worker.
297
+ * - `--remote_download_outputs=minimal` keeps the built .ipa in the instance's
298
+ * CAS instead of downloading it; the daemon auto-installs it server-side from
299
+ * there (driven by the BES stream), so the bytes never round-trip. The printed
300
+ * `lim xcode rbe` output tells users to add `--remote_download_outputs=toplevel`
301
+ * on the command line when they want the .ipa materialized locally (a
302
+ * command-line flag overrides this rc setting).
303
+ * - `--extra_execution_platforms` is emitted ONLY for non-mac clients: a Linux
304
+ * host has no auto-detected darwin execution platform, so the Apple/Swift
305
+ * toolchain (exec_compatible_with macos) needs one registered to route
306
+ * actions to the mac RBE pool. On a mac it is HARMFUL: it makes bazel run
307
+ * exec-config actions on the local host instead of the remote worker, which
308
+ * then demand a local Xcode.
309
+ * - `--modify_execution_info=.*=-no-remote,.*=-no-remote-exec` strips the
310
+ * `no-remote`/`no-remote-exec` execution-info tags rules_apple sets on
311
+ * bundling/linking/signing actions (in-code on device builds, and via its
312
+ * recommended `+no-remote` bazelrc that real iOS repos carry). Under
313
+ * --config=limrun every action runs remotely, so any such tag leaves the
314
+ * action with no usable strategy ("cannot be executed with any of the
315
+ * available strategies: [remote]") and the build fails. That is the exact
316
+ * breakage a Linux client (no local Xcode) hits. This is the execution-info
317
+ * analog of the --strategy=...=remote overrides above; stripping globally is
318
+ * safe because removing a tag an action never had is a no-op.
319
+ * - A `user.limrun.bazelrc` at the workspace root is try-imported last as a user
320
+ * override hook, so callers can extend or override the generated config
321
+ * without editing this file or passing flags on the command line.
322
+ */
323
+ export function renderLimrunBazelrc(port: number, versionKey: string, isMacClient: boolean): string {
324
+ const execPlatform =
325
+ isMacClient ? '' : (
326
+ 'build:limrun --extra_execution_platforms=@build_bazel_apple_support//platforms:darwin_arm64\n'
327
+ );
328
+ return `# Generated by lim xcode rbe. Do not edit; rerun the command to refresh.
329
+ build:limrun --remote_executor=grpc://127.0.0.1:${port}
330
+ build:limrun --bes_backend=grpc://127.0.0.1:${port}
331
+ build:limrun --bes_upload_mode=nowait_for_upload_complete
332
+ build:limrun --bes_timeout=60s
333
+ build:limrun --remote_cache=
334
+ build:limrun --remote_default_exec_properties=OSFamily=Darwin
335
+ build:limrun --spawn_strategy=remote
336
+ build:limrun --noremote_local_fallback
337
+ build:limrun --strategy=SwiftCompile=remote
338
+ build:limrun --strategy=Genrule=remote
339
+ build:limrun --modify_execution_info=.*=-no-remote,.*=-no-remote-exec
340
+ build:limrun --xcode_version_config=//.limrun:remote_xcode_config
341
+ build:limrun --xcode_version=${shortVersion(versionKey)}
342
+ build:limrun --ios_multi_cpus=sim_arm64
343
+ build:limrun --remote_download_outputs=minimal
344
+ ${execPlatform}build:limrun --action_env=PATH=/usr/bin:/bin:/usr/sbin:/sbin
345
+
346
+ # A user.limrun.bazelrc at the workspace root is try-imported last, so it can
347
+ # extend or override anything above without editing this generated file or
348
+ # passing flags on the command line. A missing file is silently skipped.
349
+ try-import %workspace%/user.limrun.bazelrc
350
+ `;
351
+ }
352
+
353
+ /**
354
+ * Idempotently ensures the workspace .bazelrc try-imports the generated
355
+ * fragment. Creates .bazelrc when missing. Returns true when the file changed.
356
+ */
357
+ export function ensureTryImport(workspaceDir: string): boolean {
358
+ const bazelrcPath = path.join(workspaceDir, '.bazelrc');
359
+ let current = '';
360
+ if (fs.existsSync(bazelrcPath)) {
361
+ current = fs.readFileSync(bazelrcPath, 'utf8');
362
+ // Match the try-import on a line basis (exact, uncommented) rather than a
363
+ // raw substring, so a commented-out occurrence (e.g. `# try-import ...`)
364
+ // doesn't make us skip wiring the active import.
365
+ const alreadyWired = current.split('\n').some((line) => line.trim() === TRY_IMPORT_LINE);
366
+ if (alreadyWired) {
367
+ return false;
368
+ }
369
+ }
370
+ const block = `${TRY_IMPORT_COMMENT}\n${TRY_IMPORT_LINE}\n`;
371
+ const next = current === '' ? block : `${current.replace(/\n*$/, '\n\n')}${block}`;
372
+ fs.writeFileSync(bazelrcPath, next);
373
+ return true;
374
+ }
375
+
376
+ export type RbeWorkspaceFiles = {
377
+ buildFile: string;
378
+ bazelrcFragment: string;
379
+ bazelrcUpdated: boolean;
380
+ };
381
+
382
+ /**
383
+ * Writes .limrun/{BUILD,bazelrc,.gitignore} into the workspace and wires the
384
+ * try-import. The .gitignore containing "*" makes the directory self-ignoring
385
+ * so nothing else in the user's repo needs to change.
386
+ */
387
+ export function writeRbeWorkspaceFiles(
388
+ workspaceDir: string,
389
+ xcodeVersionKey: string,
390
+ port: number,
391
+ isMacClient: boolean = process.platform === 'darwin',
392
+ bazelMajor: number | null = detectBazelMajorVersion(workspaceDir),
393
+ ): RbeWorkspaceFiles {
394
+ const dir = path.join(workspaceDir, LIMRUN_DIR);
395
+ fs.mkdirSync(dir, { recursive: true });
396
+ const buildFile = path.join(dir, 'BUILD');
397
+ const bazelrcFragment = path.join(dir, 'bazelrc');
398
+ // Load the Xcode rules from apple_support on Bazel 9+, where they are no
399
+ // longer native globals. On a known Bazel 8 workspace they ARE native (and
400
+ // loading would fail), so omit the loads.
401
+ const emitLoads = isBazel9OrLater(bazelMajor);
402
+ fs.writeFileSync(buildFile, renderXcodeConfigBuild(xcodeVersionKey, emitLoads));
403
+ fs.writeFileSync(bazelrcFragment, renderLimrunBazelrc(port, xcodeVersionKey, isMacClient));
404
+ fs.writeFileSync(path.join(dir, '.gitignore'), '*\n');
405
+ const bazelrcUpdated = ensureTryImport(workspaceDir);
406
+ return { buildFile, bazelrcFragment, bazelrcUpdated };
407
+ }