peachsim 0.1.697 → 0.1.699

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 (75) hide show
  1. package/cli/cloud-test-tunnel.ts +2 -10
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/agent-identity.cjs +1 -1
  5. package/dist-lib/agent-sessions.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/capture-contract.cjs +1 -1
  17. package/dist-lib/capture-contract.mjs +1 -1
  18. package/dist-lib/cli-constants.cjs +1 -1
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +1 -1
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +1 -1
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +1 -1
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/detox/index.cjs +1 -1
  27. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  28. package/dist-lib/home-paths.cjs +1 -1
  29. package/dist-lib/host/bridge-host.cjs +1561 -1439
  30. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  31. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  32. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  33. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  34. package/dist-lib/host/websocket-proxy.cjs +1 -1
  35. package/dist-lib/index.cjs +1 -1
  36. package/dist-lib/jump-to-source-babel.cjs +1 -1
  37. package/dist-lib/jump-to-source-native.cjs +1 -1
  38. package/dist-lib/kotlin-host.cjs +1 -1
  39. package/dist-lib/menu.cjs +1 -1
  40. package/dist-lib/menu.mjs +1 -1
  41. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  42. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  43. package/dist-lib/metro-production-bundle.cjs +1 -1
  44. package/dist-lib/metro-production-bundle.mjs +1 -1
  45. package/dist-lib/metro.cjs +1 -1
  46. package/dist-lib/native-app-identity.cjs +1 -1
  47. package/dist-lib/native-app-identity.mjs +1 -1
  48. package/dist-lib/native-firebase-metadata.cjs +1 -1
  49. package/dist-lib/native-firebase-metadata.mjs +1 -1
  50. package/dist-lib/plist.cjs +1 -1
  51. package/dist-lib/plist.mjs +1 -1
  52. package/dist-lib/profiles.cjs +1 -1
  53. package/dist-lib/public-brand.cjs +1 -1
  54. package/dist-lib/react-native-host-modules.cjs +1 -1
  55. package/dist-lib/react-native-host-modules.mjs +1 -1
  56. package/dist-lib/render-mode.cjs +1 -1
  57. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  58. package/dist-lib/sdk.cjs +1 -1
  59. package/dist-lib/sdk.mjs +1 -1
  60. package/dist-lib/skills.cjs +1482 -1359
  61. package/dist-lib/swift-compile.cjs +3 -1
  62. package/dist-lib/swift-compile.mjs +2 -1
  63. package/dist-lib/swift-package.cjs +1 -1
  64. package/dist-lib/swift-package.mjs +1 -1
  65. package/dist-lib/swift-submit.cjs +2 -2
  66. package/dist-lib/swift-submit.mjs +2 -2
  67. package/dist-lib/swift-toolchain.cjs +1 -1
  68. package/dist-lib/swift.cjs +1 -1
  69. package/dist-lib/vite-swift.cjs +2 -2
  70. package/dist-lib/vite.cjs +1 -1
  71. package/package.json +1 -1
  72. package/src/expo-swift-host.ts +174 -43
  73. package/src/expoSwiftContract.ts +19 -0
  74. package/src/swift-compile.ts +1 -1
  75. package/src/swift-submit.ts +2 -1
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.697 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.699 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  let __sootsim_import_meta_url = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -21185,965 +21185,522 @@ var init_internal_child = __esm({
21185
21185
  }
21186
21186
  });
21187
21187
 
21188
- // ../contrast-runtime-delivery/src/product.ts
21189
- function isValidRuntimeVersion(value) {
21190
- return value.length <= 100 && /^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value);
21188
+ // src/swift-distribution-contract.ts
21189
+ function swiftDistributionHost(platform, arch) {
21190
+ const host2 = `${platform}-${arch}`;
21191
+ return SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === host2) ?? null;
21191
21192
  }
21192
- function listInstalledRuntimes(product) {
21193
- try {
21194
- return import_node_fs6.default.readdirSync(product.runtimesDir(), { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(compareSemver);
21195
- } catch {
21196
- return [];
21193
+ function parseSwiftDistributionManifest(value) {
21194
+ if (!isRecord(value) || typeof value.id !== "string" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || !isStrings(value.modules) || !isStrings(value.objects) || !isStrings(value.link) || !isRecord(value.files) || !Object.values(value.files).every((sha) => typeof sha === "string") || typeof value.host !== "string" || !isStrings(value.plugins)) {
21195
+ throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`);
21197
21196
  }
21198
- }
21199
- function runtimeTarballCacheName(product, version) {
21200
- return import_node_path6.default.posix.basename(product.tarballPath(version));
21201
- }
21202
- function compareSemver(a, b) {
21203
- const parse2 = (v) => {
21204
- const hyphen = v.indexOf("-");
21205
- const core = hyphen >= 0 ? v.slice(0, hyphen) : v;
21206
- const pre = hyphen >= 0 ? v.slice(hyphen + 1) : "";
21207
- const parts = core.split(".").map((n) => Number.parseInt(n, 10));
21208
- if (parts.some((n) => !Number.isFinite(n))) return [[Number.POSITIVE_INFINITY], v];
21209
- return [parts, pre];
21197
+ const host2 = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host);
21198
+ if (!host2) throw new Error(`Swift distribution names an unknown host ${value.host}`);
21199
+ return {
21200
+ id: value.id,
21201
+ release: value.release,
21202
+ wasmSdkId: value.wasmSdkId,
21203
+ wasmSdkUrl: value.wasmSdkUrl,
21204
+ wasmSdkChecksum: value.wasmSdkChecksum,
21205
+ modules: value.modules,
21206
+ objects: value.objects,
21207
+ link: value.link,
21208
+ files: Object.fromEntries(
21209
+ Object.entries(value.files).map(([file, sha]) => [file, String(sha)])
21210
+ ),
21211
+ host: host2,
21212
+ plugins: value.plugins
21210
21213
  };
21211
- const [an, ap] = parse2(a);
21212
- const [bn, bp] = parse2(b);
21213
- for (let i = 0; i < Math.max(an.length, bn.length); i++) {
21214
- const av = an[i] ?? 0;
21215
- const bv = bn[i] ?? 0;
21216
- if (av !== bv) return av - bv;
21214
+ }
21215
+ function parseSwiftDistributionLock(value) {
21216
+ if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || typeof value.source !== "string" || !isRecord(value.hosts)) {
21217
+ throw new Error("invalid Swift distribution lock");
21217
21218
  }
21218
- if (ap === bp) return 0;
21219
- if (!ap) return 1;
21220
- if (!bp) return -1;
21221
- return ap < bp ? -1 : 1;
21219
+ const hosts = value.hosts;
21220
+ const entry = (host2) => {
21221
+ const item = hosts[host2];
21222
+ if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
21223
+ throw new Error(`invalid Swift distribution lock entry for ${host2}`);
21224
+ }
21225
+ return { sha256: item.sha256, size: item.size };
21226
+ };
21227
+ return {
21228
+ id: value.id,
21229
+ release: value.release,
21230
+ wasmSdkId: value.wasmSdkId,
21231
+ wasmSdkUrl: value.wasmSdkUrl,
21232
+ wasmSdkChecksum: value.wasmSdkChecksum,
21233
+ source: value.source,
21234
+ hosts: {
21235
+ "darwin-arm64": entry("darwin-arm64"),
21236
+ "linux-x64": entry("linux-x64"),
21237
+ "linux-arm64": entry("linux-arm64")
21238
+ }
21239
+ };
21222
21240
  }
21223
- var import_node_fs6, import_node_path6;
21224
- var init_product = __esm({
21225
- "../contrast-runtime-delivery/src/product.ts"() {
21241
+ function swiftDistributionKey(id, host2) {
21242
+ return `${id}/${host2}.tar.gz`;
21243
+ }
21244
+ var SWIFT_DISTRIBUTION_MANIFEST, SWIFT_DISTRIBUTION_HOSTS, isStrings;
21245
+ var init_swift_distribution_contract = __esm({
21246
+ "src/swift-distribution-contract.ts"() {
21226
21247
  "use strict";
21227
- import_node_fs6 = __toESM(require("node:fs"), 1);
21228
- import_node_path6 = __toESM(require("node:path"), 1);
21248
+ init_is_record();
21249
+ SWIFT_DISTRIBUTION_MANIFEST = "distribution.json";
21250
+ SWIFT_DISTRIBUTION_HOSTS = [
21251
+ "darwin-arm64",
21252
+ "linux-x64",
21253
+ "linux-arm64"
21254
+ ];
21255
+ isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
21229
21256
  }
21230
21257
  });
21231
21258
 
21232
- // ../contrast-runtime-delivery/src/index.ts
21233
- function createRuntimeDelivery(product) {
21234
- function readConfig() {
21235
- try {
21236
- const parsed = JSON.parse(
21237
- import_node_fs7.default.readFileSync(product.configFile(), "utf8")
21238
- );
21239
- return parsed && typeof parsed === "object" ? parsed : {};
21240
- } catch {
21241
- return {};
21242
- }
21243
- }
21244
- function resolveCdnOrigin(input) {
21245
- const config = readConfig();
21246
- const value = input || process.env[product.env.cdnOrigin] || config.cdnOrigin || product.defaultCdnOrigin;
21247
- return value.replace(/\/+$/, "");
21248
- }
21249
- function resolveChannel(input) {
21250
- const config = readConfig();
21251
- return input || process.env[product.env.channel] || config.runtimeChannel || "stable";
21252
- }
21253
- function resolvePin() {
21254
- if (!product.env.pin) return null;
21255
- const env = process.env[product.env.pin];
21256
- if (env && env.trim()) return env.trim();
21257
- const config = readConfig();
21258
- return typeof config.runtimeVersion === "string" && config.runtimeVersion.trim() ? config.runtimeVersion.trim() : null;
21259
- }
21260
- function manifestUrl(cdnOrigin) {
21261
- const url = new URL(`${resolveCdnOrigin(cdnOrigin)}${product.manifestPath}`);
21262
- url.searchParams.set("t", String(Date.now()));
21263
- return url.toString();
21259
+ // src/swift-icu.ts
21260
+ function memo(cache, key, load2) {
21261
+ let pending = cache.get(key);
21262
+ if (!pending) {
21263
+ pending = load2();
21264
+ pending.catch(() => cache.delete(key));
21265
+ cache.set(key, pending);
21264
21266
  }
21265
- function tarballUrl(version, cdnOrigin) {
21266
- return `${resolveCdnOrigin(cdnOrigin)}${product.tarballPath(version)}`;
21267
+ return pending;
21268
+ }
21269
+ function swiftIcuData(toolchainBin, sdk) {
21270
+ return memo(raw, `${toolchainBin}\0${sdk}`, () => load(toolchainBin, sdk));
21271
+ }
21272
+ function swiftIcuAsset(toolchainBin, sdk) {
21273
+ return memo(assets, `${toolchainBin}\0${sdk}`, async () => {
21274
+ const zipped = await deflate(await swiftIcuData(toolchainBin, sdk));
21275
+ return { sha256: (0, import_node_crypto2.createHash)("sha256").update(zipped).digest("hex"), gzip: zipped };
21276
+ });
21277
+ }
21278
+ async function load(toolchainBin, sdk) {
21279
+ const { stdout } = await run(import_node_path6.default.join(toolchainBin, "swift"), [
21280
+ "sdk",
21281
+ "configure",
21282
+ "--show-configuration",
21283
+ sdk,
21284
+ "wasm32-unknown-wasip1"
21285
+ ]);
21286
+ const resources = /^swiftStaticResourcesPath: (.+)$/m.exec(stdout)?.[1]?.trim();
21287
+ if (!resources) throw new Error(`swift-icu: ${sdk} names no static resources`);
21288
+ return Buffer.from(
21289
+ icuSegment(archiveMember((0, import_node_fs6.readFileSync)(import_node_path6.default.join(resources, ARCHIVE)), MEMBER))
21290
+ );
21291
+ }
21292
+ function archiveMember(archive, name2) {
21293
+ if (archive.toString("latin1", 0, 8) !== "!<arch>\n")
21294
+ throw new Error("swift-icu: not an ar archive");
21295
+ let names = "";
21296
+ for (let at = 8; at + 60 <= archive.length; ) {
21297
+ const raw2 = archive.toString("latin1", at, at + 16).trimEnd();
21298
+ const size = Number(archive.toString("latin1", at + 48, at + 58).trim());
21299
+ const body = archive.subarray(at + 60, at + 60 + size);
21300
+ if (raw2 === "//") names = body.toString("latin1");
21301
+ const member = /^\/\d+$/.test(raw2) ? names.slice(Number(raw2.slice(1)), names.indexOf("/\n", Number(raw2.slice(1)))) : raw2.replace(/\/$/, "");
21302
+ if (member === name2) return body;
21303
+ at += 60 + size + size % 2;
21267
21304
  }
21268
- const UP_TO_DATE_CHECK_TIMEOUT_MS = 2e3;
21269
- async function fetchManifest(cdnOrigin, timeoutMs) {
21270
- const url = manifestUrl(cdnOrigin);
21271
- const res = await fetch(url, {
21272
- headers: { Accept: "application/json" },
21273
- // an install is allowed to wait; a best-effort check is not. see
21274
- // UP_TO_DATE_CHECK_TIMEOUT_MS.
21275
- ...timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {}
21276
- });
21277
- if (!res.ok) {
21278
- throw new Error(`manifest fetch failed: ${res.status} ${res.statusText} (${url})`);
21305
+ throw new Error(`swift-icu: ${name2} is not in the sdk's icu archive`);
21306
+ }
21307
+ function icuSegment(object) {
21308
+ let at = 8;
21309
+ const leb = () => {
21310
+ let result = 0;
21311
+ let shift = 0;
21312
+ let byte;
21313
+ do {
21314
+ byte = object[at++];
21315
+ result += (byte & 127) * 2 ** shift;
21316
+ shift += 7;
21317
+ } while (byte & 128);
21318
+ return result;
21319
+ };
21320
+ const found = [];
21321
+ while (at < object.length) {
21322
+ const id = object[at++];
21323
+ const size = leb();
21324
+ const end = at + size;
21325
+ if (id === 11) {
21326
+ for (let count = leb(); count > 0; count--) {
21327
+ if (leb() !== 0) throw new Error("swift-icu: unexpected data segment kind");
21328
+ at++;
21329
+ leb();
21330
+ at++;
21331
+ const length = leb();
21332
+ const bytes = object.subarray(at, at + length);
21333
+ if (bytes[2] === 218 && bytes[3] === 39) found.push(bytes);
21334
+ at += length;
21335
+ }
21279
21336
  }
21280
- return await res.json();
21337
+ at = end;
21281
21338
  }
21282
- function resolveVersion(manifest, opts = {}) {
21283
- const channel = resolveChannel(opts.channel);
21284
- const version = opts.version || resolvePin() || manifest.channels[channel]?.latest;
21285
- if (!version) {
21286
- throw new Error(
21287
- `no version specified and channel '${channel}' has no latest entry in the manifest`
21288
- );
21289
- }
21290
- if (!isValidRuntimeVersion(version)) {
21291
- throw new Error(`invalid runtime version: ${version}`);
21292
- }
21293
- const entry = manifest.versions[version];
21294
- if (!entry) {
21295
- throw new Error(
21296
- `version ${version} not found in manifest; available: ${Object.keys(manifest.versions).slice(-10).join(", ") || "(none)"}`
21297
- );
21298
- }
21299
- return { version, channel, entry };
21339
+ if (found.length !== 1)
21340
+ throw new Error(`swift-icu: expected one icu data segment, found ${found.length}`);
21341
+ return found[0];
21342
+ }
21343
+ var import_node_child_process3, import_node_crypto2, import_node_fs6, import_node_path6, import_node_util, import_node_zlib, run, deflate, ARCHIVE, MEMBER, raw, assets;
21344
+ var init_swift_icu = __esm({
21345
+ "src/swift-icu.ts"() {
21346
+ "use strict";
21347
+ import_node_child_process3 = require("node:child_process");
21348
+ import_node_crypto2 = require("node:crypto");
21349
+ import_node_fs6 = require("node:fs");
21350
+ import_node_path6 = __toESM(require("node:path"), 1);
21351
+ import_node_util = require("node:util");
21352
+ import_node_zlib = require("node:zlib");
21353
+ run = (0, import_node_util.promisify)(import_node_child_process3.execFile);
21354
+ deflate = (0, import_node_util.promisify)(import_node_zlib.gzip);
21355
+ ARCHIVE = "wasi/lib_FoundationICU.a";
21356
+ MEMBER = "icu_packaged_data.cpp.obj";
21357
+ raw = /* @__PURE__ */ new Map();
21358
+ assets = /* @__PURE__ */ new Map();
21300
21359
  }
21301
- async function install(opts = {}) {
21302
- product.ensureHome();
21303
- const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
21304
- const manifest = await fetchManifest(cdnOrigin);
21305
- const { version, channel, entry } = resolveVersion(manifest, opts);
21306
- const destDir = product.runtimeDir(version);
21307
- const setActive = opts.setActive !== false;
21308
- const protectVersions = [version, ...opts.protectVersions ?? []];
21309
- pruneLocalRetention({ protectVersions });
21310
- if (!opts.force && import_node_fs7.default.existsSync(import_node_path7.default.join(destDir, product.installedMarker))) {
21311
- if (setActive) product.writeActiveRuntime(version);
21312
- pruneLocalRetention({ protectVersions });
21313
- return {
21314
- version,
21315
- channel,
21316
- cdnOrigin,
21317
- runtimeDir: destDir,
21318
- installed: false,
21319
- activated: setActive,
21320
- manifest
21321
- };
21322
- }
21323
- if (!opts.quiet)
21324
- process.stderr.write(`${product.id}: downloading runtime ${version}\u2026
21325
- `);
21326
- await installVerifiedTarball({
21327
- url: entry.tarball || tarballUrl(version, cdnOrigin),
21328
- digest: { algorithm: "sha256", encoding: "hex", value: entry.sha256 },
21329
- destDir,
21330
- installedMarker: product.installedMarker,
21331
- label: `runtime ${version}`
21332
- });
21333
- if (setActive) product.writeActiveRuntime(version);
21334
- pruneLocalRetention({ protectVersions });
21335
- return {
21336
- version,
21337
- channel,
21338
- cdnOrigin,
21339
- runtimeDir: destDir,
21340
- installed: true,
21341
- activated: setActive,
21342
- manifest
21343
- };
21344
- }
21345
- async function updateToLatest(opts = {}) {
21346
- product.ensureHome();
21347
- pruneLocalRetention({ protectVersions: opts.protectVersions });
21348
- const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
21349
- const channel = resolveChannel(opts.channel);
21350
- const pin = resolvePin();
21351
- if (pin) {
21352
- const activeVersion2 = product.readActiveRuntime();
21353
- const pinInstalled = import_node_fs7.default.existsSync(
21354
- import_node_path7.default.join(product.runtimeDir(pin), product.installedMarker)
21355
- );
21356
- if (activeVersion2 === pin && pinInstalled) {
21357
- return {
21358
- checked: true,
21359
- updated: false,
21360
- reason: `runtime is pinned to ${pin}`,
21361
- activeVersion: activeVersion2,
21362
- latestVersion: pin
21363
- };
21360
+ });
21361
+
21362
+ // src/swift-package.ts
21363
+ function swiftManifestTargets(manifest) {
21364
+ const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
21365
+ const targets = [];
21366
+ const pattern = /\.(executableTarget|target)\s*\(/g;
21367
+ let match;
21368
+ while ((match = pattern.exec(code)) !== null) {
21369
+ const executable = match[1] === "executableTarget";
21370
+ let depth = 1;
21371
+ const start = pattern.lastIndex;
21372
+ let i = start;
21373
+ let inString = false;
21374
+ let escaped = false;
21375
+ let flat = "";
21376
+ while (i < code.length && depth > 0) {
21377
+ const ch = code[i];
21378
+ if (inString) {
21379
+ if (escaped) escaped = false;
21380
+ else if (ch === "\\") escaped = true;
21381
+ else if (ch === '"') inString = false;
21382
+ if (depth === 1) flat += ch;
21383
+ } else if (ch === '"') {
21384
+ inString = true;
21385
+ if (depth === 1) flat += ch;
21386
+ } else if (ch === "(") {
21387
+ depth++;
21388
+ if (depth === 1) flat += ch;
21389
+ } else if (ch === ")") {
21390
+ depth--;
21391
+ if (depth >= 1) flat += ch;
21392
+ } else if (depth === 1) {
21393
+ flat += ch;
21364
21394
  }
21365
- const installed3 = await install({
21366
- version: pin,
21367
- channel,
21368
- cdnOrigin,
21369
- setActive: false,
21370
- protectVersions: opts.protectVersions
21371
- });
21372
- return {
21373
- checked: true,
21374
- updated: true,
21375
- reason: `runtime is pinned to ${pin}`,
21376
- activeVersion: pin,
21377
- latestVersion: pin,
21378
- install: installed3
21379
- };
21380
- }
21381
- const manifest = await fetchManifest(cdnOrigin);
21382
- const latestVersion = manifest.channels[channel]?.latest;
21383
- if (!latestVersion) {
21384
- return {
21385
- checked: true,
21386
- updated: false,
21387
- reason: `channel '${channel}' has no latest runtime`,
21388
- activeVersion: product.readActiveRuntime()
21389
- };
21390
- }
21391
- const entry = manifest.versions[latestVersion];
21392
- if (!entry) {
21393
- return {
21394
- checked: true,
21395
- updated: false,
21396
- reason: `manifest is missing version ${latestVersion}`,
21397
- activeVersion: product.readActiveRuntime(),
21398
- latestVersion
21399
- };
21400
- }
21401
- const activeVersion = product.readActiveRuntime();
21402
- const activeDir = activeVersion ? product.runtimeDir(activeVersion) : null;
21403
- const activeInstalled = activeDir ? import_node_fs7.default.existsSync(import_node_path7.default.join(activeDir, product.installedMarker)) : false;
21404
- const shouldInstall = !activeVersion || !activeInstalled || compareSemver(latestVersion, activeVersion) > 0;
21405
- if (!shouldInstall) {
21406
- return {
21407
- checked: true,
21408
- updated: false,
21409
- reason: "active runtime is current",
21410
- activeVersion,
21411
- latestVersion
21412
- };
21395
+ i++;
21413
21396
  }
21414
- const installed2 = await install({
21415
- version: latestVersion,
21416
- channel,
21417
- cdnOrigin,
21418
- setActive: false,
21419
- protectVersions: opts.protectVersions
21397
+ const name2 = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
21398
+ if (!name2) continue;
21399
+ const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
21400
+ const targetPath = rawPath == null || rawPath === "" ? `Sources/${name2}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
21401
+ const call = code.slice(start, i);
21402
+ const languageMode = Number(
21403
+ /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
21404
+ );
21405
+ const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
21406
+ const resources = /\bresources\s*:/.test(flat);
21407
+ targets.push({
21408
+ name: name2,
21409
+ path: targetPath,
21410
+ executable,
21411
+ languageMode,
21412
+ mainActorIsolation,
21413
+ resources
21420
21414
  });
21421
- return {
21422
- checked: true,
21423
- updated: true,
21424
- activeVersion: latestVersion,
21425
- latestVersion,
21426
- install: installed2
21427
- };
21428
21415
  }
21429
- async function checkUpToDate(opts = {}) {
21430
- const active = product.readActiveRuntime();
21431
- const pinned = resolvePin();
21432
- if (pinned) {
21433
- return { active, latest: pinned, pinned, outdated: active !== pinned };
21416
+ return targets;
21417
+ }
21418
+ function swiftPackagePartition(manifest) {
21419
+ const targets = swiftManifestTargets(manifest);
21420
+ return targets.length === 1 && targets[0].executable && targets[0].path === "." ? [] : targets;
21421
+ }
21422
+ var init_swift_package = __esm({
21423
+ "src/swift-package.ts"() {
21424
+ "use strict";
21425
+ }
21426
+ });
21427
+
21428
+ // src/swift-compile.ts
21429
+ function swiftDistributionAt(root) {
21430
+ const file = import_node_path7.default.join(root, SWIFT_DISTRIBUTION_MANIFEST);
21431
+ if (!(0, import_node_fs7.existsSync)(file)) return null;
21432
+ return parseSwiftDistributionManifest(JSON.parse((0, import_node_fs7.readFileSync)(file, "utf8")));
21433
+ }
21434
+ function swiftModuleSdk(root) {
21435
+ const pin = swiftDistributionAt(root) ?? JSON.parse((0, import_node_fs7.readFileSync)(import_node_path7.default.join(root, "toolchain.json"), "utf8"));
21436
+ if (!pin || typeof pin !== "object" || typeof Reflect.get(pin, "wasmSdkId") !== "string" || typeof Reflect.get(pin, "wasmSdkUrl") !== "string" || typeof Reflect.get(pin, "wasmSdkChecksum") !== "string")
21437
+ throw new Error(`${root} pins no wasm SDK id, url and checksum`);
21438
+ return {
21439
+ wasmSdkId: String(Reflect.get(pin, "wasmSdkId")),
21440
+ wasmSdkUrl: String(Reflect.get(pin, "wasmSdkUrl")),
21441
+ wasmSdkChecksum: String(Reflect.get(pin, "wasmSdkChecksum"))
21442
+ };
21443
+ }
21444
+ function swiftModuleInputFiles(root) {
21445
+ if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST];
21446
+ const files = [
21447
+ "Package.swift",
21448
+ "scripts/contrast-app-Package.swift",
21449
+ "toolchain.json"
21450
+ ];
21451
+ const walk = (dir) => {
21452
+ for (const entry of (0, import_node_fs7.readdirSync)(import_node_path7.default.join(root, dir), { withFileTypes: true })) {
21453
+ const relative2 = `${dir}/${entry.name}`;
21454
+ if (entry.isDirectory()) walk(relative2);
21455
+ else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative2);
21434
21456
  }
21435
- try {
21436
- const manifest = await fetchManifest(
21437
- resolveCdnOrigin(opts.cdnOrigin),
21438
- UP_TO_DATE_CHECK_TIMEOUT_MS
21439
- );
21440
- const channel = resolveChannel(opts.channel);
21441
- const latest = manifest.channels[channel]?.latest ?? null;
21442
- const outdated = !!(latest && (!active || compareSemver(latest, active) > 0));
21443
- return { active, latest, pinned: null, outdated };
21444
- } catch {
21445
- return { active, latest: null, pinned: null, outdated: false };
21457
+ };
21458
+ walk("Sources");
21459
+ return files.sort();
21460
+ }
21461
+ async function ensureMacroPlugins(moduleRoot, toolchainBin) {
21462
+ const distribution = swiftDistributionAt(moduleRoot);
21463
+ if (distribution)
21464
+ return distribution.plugins.map((plugin) => import_node_path7.default.join(moduleRoot, plugin));
21465
+ const dir = import_node_path7.default.join(moduleRoot, ".build/host/RnxPreviewMacros");
21466
+ const ext = process.platform === "darwin" ? "dylib" : "so";
21467
+ const plugins = [
21468
+ {
21469
+ library: import_node_path7.default.join(dir, `libRnxPreviewMacros.${ext}`),
21470
+ source: import_node_path7.default.join(moduleRoot, "Sources/RnxPreviewMacros/PreviewMacro.swift")
21471
+ },
21472
+ {
21473
+ library: import_node_path7.default.join(dir, `libFoundationMacros.${ext}`),
21474
+ source: import_node_path7.default.join(moduleRoot, "Sources/FoundationMacros/PredicateMacro.swift")
21446
21475
  }
21476
+ ];
21477
+ const stale = plugins.some(
21478
+ ({ library, source }) => !(0, import_node_fs7.existsSync)(library) || (0, import_node_fs7.statSync)(source).mtimeMs > (0, import_node_fs7.statSync)(library).mtimeMs
21479
+ );
21480
+ if (stale) {
21481
+ await run2("sh", [
21482
+ import_node_path7.default.join(moduleRoot, "scripts/build-preview-plugin.sh"),
21483
+ toolchainBin,
21484
+ plugins[0].library
21485
+ ]);
21447
21486
  }
21448
- function planLocalRetention(opts = {}) {
21449
- product.ensureHome();
21450
- const retainVersions = Math.max(
21451
- 1,
21452
- Math.floor(opts.retainVersions ?? DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT)
21487
+ return plugins.map(({ library }) => library);
21488
+ }
21489
+ function swiftModuleDigest(root) {
21490
+ const files = swiftModuleInputFiles(root);
21491
+ const stampHash = (0, import_node_crypto3.createHash)("sha256");
21492
+ for (const file of files) {
21493
+ const stat2 = (0, import_node_fs7.statSync)(import_node_path7.default.join(root, file), { bigint: true });
21494
+ stampHash.update(file);
21495
+ stampHash.update(
21496
+ `${stat2.dev}:${stat2.ino}:${stat2.size}:${stat2.mtimeNs}:${stat2.ctimeNs}
21497
+ `
21453
21498
  );
21454
- const installed2 = listInstalledRuntimes(product);
21455
- const installedSet = new Set(installed2);
21456
- const activeVersion = product.readActiveRuntime();
21457
- const pinnedVersion = resolvePin();
21458
- const keep = /* @__PURE__ */ new Set();
21459
- for (const version of [
21460
- activeVersion,
21461
- pinnedVersion,
21462
- ...opts.protectVersions ?? []
21463
- ]) {
21464
- if (version && installedSet.has(version)) keep.add(version);
21465
- }
21466
- for (const version of [...installed2].reverse()) {
21467
- if (keep.size >= retainVersions) break;
21468
- keep.add(version);
21469
- }
21470
- const cacheTemplateMarker = "__RUNTIME_VERSION__";
21471
- const cacheTemplate = runtimeTarballCacheName(product, cacheTemplateMarker);
21472
- const markerOffset = cacheTemplate.indexOf(cacheTemplateMarker);
21473
- const cachePrefix = cacheTemplate.slice(0, markerOffset);
21474
- const cacheSuffix = cacheTemplate.slice(markerOffset + cacheTemplateMarker.length);
21475
- let removeCacheFiles = [];
21476
- if (markerOffset >= 0) {
21477
- try {
21478
- removeCacheFiles = import_node_fs7.default.readdirSync(product.cacheDir(), { withFileTypes: true }).filter((entry) => {
21479
- if (!entry.isFile()) return false;
21480
- const complete = entry.name.startsWith(cachePrefix) && entry.name.endsWith(cacheSuffix);
21481
- const partial = entry.name.startsWith(cachePrefix) && entry.name.endsWith(`${cacheSuffix}.partial`);
21482
- return complete || partial;
21483
- }).map((entry) => import_node_path7.default.join(product.cacheDir(), entry.name)).sort();
21484
- } catch {
21485
- }
21486
- }
21487
- return {
21488
- activeVersion,
21489
- pinnedVersion,
21490
- keepVersions: installed2.filter((version) => keep.has(version)),
21491
- removeVersions: installed2.filter((version) => !keep.has(version)),
21492
- removeCacheFiles
21493
- };
21494
21499
  }
21495
- function pruneLocalRetention(opts = {}) {
21496
- const plan = planLocalRetention(opts);
21497
- for (const version of plan.removeVersions) {
21498
- import_node_fs7.default.rmSync(product.runtimeDir(version), { recursive: true, force: true });
21499
- }
21500
- for (const cacheFile of plan.removeCacheFiles) {
21501
- import_node_fs7.default.rmSync(cacheFile, { force: true });
21502
- }
21503
- return plan;
21500
+ const stamp = stampHash.digest("hex");
21501
+ const cached4 = linkedModuleDigests.get(root);
21502
+ if (cached4?.stamp === stamp) return cached4.digest;
21503
+ const hash = (0, import_node_crypto3.createHash)("sha256");
21504
+ for (const file of files) {
21505
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(file).digest());
21506
+ hash.update(
21507
+ (0, import_node_crypto3.createHash)("sha256").update((0, import_node_fs7.readFileSync)(import_node_path7.default.join(root, file))).digest()
21508
+ );
21509
+ }
21510
+ const digest = hash.digest();
21511
+ linkedModuleDigests.set(root, { stamp, digest });
21512
+ return digest;
21513
+ }
21514
+ function compileTargets(input) {
21515
+ const manifest = input.files["Package.swift"];
21516
+ return manifest === void 0 ? [] : swiftPackagePartition(manifest);
21517
+ }
21518
+ function withNativeSourceGlue(input, glue) {
21519
+ const targets = compileTargets(input);
21520
+ if (targets.length > 1) {
21521
+ throw new Error("swift native modules need one SwiftPM target");
21504
21522
  }
21523
+ const targetPath = targets[0]?.path === "." ? "" : targets[0]?.path ?? "";
21505
21524
  return {
21506
- product,
21507
- resolveCdnOrigin,
21508
- resolveChannel,
21509
- resolvePin,
21510
- manifestUrl,
21511
- tarballUrl,
21512
- fetchManifest,
21513
- resolveVersion,
21514
- install,
21515
- updateToLatest,
21516
- checkUpToDate,
21517
- planLocalRetention,
21518
- pruneLocalRetention,
21519
- listInstalled: () => listInstalledRuntimes(product)
21525
+ ...input,
21526
+ files: {
21527
+ ...input.files,
21528
+ [import_node_path7.default.posix.join(targetPath, "OneNativeSource.generated.swift")]: glue
21529
+ },
21530
+ oneModule: true
21520
21531
  };
21521
21532
  }
21522
- async function installVerifiedTarball(tarball) {
21523
- const { url, digest, destDir, installedMarker, label } = tarball;
21524
- const downloadDir = import_node_fs7.default.mkdtempSync(import_node_path7.default.join(import_node_os2.default.tmpdir(), "runtime-delivery-download-"));
21525
- const archivePath = import_node_path7.default.join(downloadDir, "archive.tar.gz");
21526
- import_node_fs7.default.mkdirSync(import_node_path7.default.dirname(destDir), { recursive: true });
21527
- const tmpDir = import_node_fs7.default.mkdtempSync(
21528
- import_node_path7.default.join(import_node_path7.default.dirname(destDir), `.installing-${import_node_path7.default.basename(destDir)}-`)
21529
- );
21530
- try {
21531
- await downloadToFile(url, archivePath);
21532
- const actual = await digestFile(archivePath, digest.algorithm, digest.encoding);
21533
- if (actual !== digest.value) {
21534
- throw new Error(
21535
- `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
21536
- );
21537
- }
21538
- await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
21539
- if (!import_node_fs7.default.existsSync(import_node_path7.default.join(tmpDir, installedMarker))) {
21540
- throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
21541
- }
21542
- try {
21543
- import_node_fs7.default.renameSync(tmpDir, destDir);
21544
- } catch (err) {
21545
- if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
21546
- const aside = `${tmpDir}-replaced`;
21547
- try {
21548
- import_node_fs7.default.renameSync(destDir, aside);
21549
- } catch (moveErr) {
21550
- if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
21551
- }
21552
- try {
21553
- import_node_fs7.default.renameSync(tmpDir, destDir);
21554
- } catch (landErr) {
21555
- if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs7.default.existsSync(import_node_path7.default.join(destDir, installedMarker))) {
21556
- throw landErr;
21557
- }
21558
- } finally {
21559
- import_node_fs7.default.rmSync(aside, { recursive: true, force: true });
21533
+ function swiftTargetDependencies(files, targets) {
21534
+ const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
21535
+ const siblings = /* @__PURE__ */ new Map();
21536
+ for (const target of targets) {
21537
+ const prefix = target.path === "." ? "" : `${target.path}/`;
21538
+ const deps = /* @__PURE__ */ new Set();
21539
+ for (const [file, contents] of Object.entries(files)) {
21540
+ if (file === "Package.swift" || !file.startsWith(prefix)) continue;
21541
+ if (targets.some(
21542
+ (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
21543
+ ))
21544
+ continue;
21545
+ for (const match of contents.matchAll(
21546
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm
21547
+ )) {
21548
+ if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1]);
21560
21549
  }
21561
21550
  }
21562
- } finally {
21563
- import_node_fs7.default.rmSync(tmpDir, { recursive: true, force: true });
21564
- import_node_fs7.default.rmSync(downloadDir, { recursive: true, force: true });
21551
+ siblings.set(target.name, [...deps].sort());
21565
21552
  }
21553
+ return siblings;
21566
21554
  }
21567
- function isErrnoCode(err, ...codes) {
21568
- return err instanceof Error && "code" in err && codes.includes(String(err.code));
21569
- }
21570
- async function downloadToFile(url, destPath) {
21571
- const res = await fetch(url);
21572
- if (!res.ok || !res.body) {
21573
- throw new Error(`download failed: ${res.status} ${res.statusText} (${url})`);
21555
+ function swiftArtifactHash(input, release, moduleRoot) {
21556
+ const hash = (0, import_node_crypto3.createHash)("sha256");
21557
+ hash.update(`swift-compile/v12
21558
+ ${release}
21559
+ `);
21560
+ if (input.oneModule) hash.update("one-module\n");
21561
+ hash.update(swiftModuleDigest(moduleRoot));
21562
+ for (const file of Object.keys(input.files).sort()) {
21563
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(file).digest());
21564
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(input.files[file]).digest());
21574
21565
  }
21575
- import_node_fs7.default.mkdirSync(import_node_path7.default.dirname(destPath), { recursive: true });
21576
- const tmp = `${destPath}.partial`;
21577
- try {
21578
- await (0, import_promises3.pipeline)(
21579
- import_node_stream.Readable.fromWeb(res.body),
21580
- import_node_fs7.default.createWriteStream(tmp)
21566
+ for (const base of Object.keys(input.resources ?? {}).sort()) {
21567
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(base).digest());
21568
+ hash.update(
21569
+ (0, import_node_crypto3.createHash)("sha256").update(input.resources?.[base] ?? "").digest()
21581
21570
  );
21582
- import_node_fs7.default.renameSync(tmp, destPath);
21583
- } catch (err) {
21584
- try {
21585
- import_node_fs7.default.unlinkSync(tmp);
21586
- } catch {
21587
- }
21588
- throw err;
21589
- }
21590
- }
21591
- function digestFile(filePath, algorithm, encoding) {
21592
- return new Promise((resolve10, reject) => {
21593
- const hash = import_node_crypto2.default.createHash(algorithm);
21594
- const stream = import_node_fs7.default.createReadStream(filePath);
21595
- stream.on("data", (chunk) => hash.update(chunk));
21596
- stream.on("error", reject);
21597
- stream.on("end", () => resolve10(hash.digest(encoding)));
21598
- });
21599
- }
21600
- function extractTarball(tarPath, destDir, stripComponents) {
21601
- return new Promise((resolve10, reject) => {
21602
- const args = ["-xzf", tarPath, "-C", destDir];
21603
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
21604
- const child = (0, import_node_child_process3.spawn)("tar", args, {
21605
- stdio: ["ignore", "inherit", "inherit"]
21606
- });
21607
- child.on("error", reject);
21608
- child.on("exit", (code) => {
21609
- if (code === 0) resolve10();
21610
- else reject(new Error(`tar exited with code ${code}`));
21611
- });
21612
- });
21613
- }
21614
- var import_node_child_process3, import_node_crypto2, import_node_fs7, import_node_os2, import_node_path7, import_node_stream, import_promises3, DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT;
21615
- var init_src = __esm({
21616
- "../contrast-runtime-delivery/src/index.ts"() {
21617
- "use strict";
21618
- import_node_child_process3 = require("node:child_process");
21619
- import_node_crypto2 = __toESM(require("node:crypto"), 1);
21620
- import_node_fs7 = __toESM(require("node:fs"), 1);
21621
- import_node_os2 = __toESM(require("node:os"), 1);
21622
- import_node_path7 = __toESM(require("node:path"), 1);
21623
- import_node_stream = require("node:stream");
21624
- import_promises3 = require("node:stream/promises");
21625
- init_product();
21626
- init_product();
21627
- DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT = 2;
21628
21571
  }
21629
- });
21630
-
21631
- // src/swift-distribution-contract.ts
21632
- function swiftDistributionHost(platform, arch) {
21633
- const host2 = `${platform}-${arch}`;
21634
- return SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === host2) ?? null;
21635
- }
21636
- function parseSwiftDistributionManifest(value) {
21637
- if (!isRecord(value) || typeof value.id !== "string" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || !isStrings(value.modules) || !isStrings(value.objects) || !isStrings(value.link) || !isRecord(value.files) || !Object.values(value.files).every((sha) => typeof sha === "string") || typeof value.host !== "string" || !isStrings(value.plugins)) {
21638
- throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`);
21572
+ for (const name2 of Object.keys(input.images ?? {}).sort()) {
21573
+ const image = input.images?.[name2];
21574
+ if (!image) continue;
21575
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(name2).digest());
21576
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(image.file).digest());
21577
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(image.data).digest());
21639
21578
  }
21640
- const host2 = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host);
21641
- if (!host2) throw new Error(`Swift distribution names an unknown host ${value.host}`);
21642
- return {
21643
- id: value.id,
21644
- release: value.release,
21645
- wasmSdkId: value.wasmSdkId,
21646
- wasmSdkUrl: value.wasmSdkUrl,
21647
- wasmSdkChecksum: value.wasmSdkChecksum,
21648
- modules: value.modules,
21649
- objects: value.objects,
21650
- link: value.link,
21651
- files: Object.fromEntries(
21652
- Object.entries(value.files).map(([file, sha]) => [file, String(sha)])
21653
- ),
21654
- host: host2,
21655
- plugins: value.plugins
21656
- };
21657
- }
21658
- function parseSwiftDistributionLock(value) {
21659
- if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || typeof value.source !== "string" || !isRecord(value.hosts)) {
21660
- throw new Error("invalid Swift distribution lock");
21579
+ const targets = compileTargets(input);
21580
+ if (targets.length > 0) {
21581
+ hash.update(`swift-multi/v${MULTI_MANIFEST_VERSION}
21582
+ `);
21583
+ hash.update(
21584
+ JSON.stringify({
21585
+ targets,
21586
+ siblings: [...swiftTargetDependencies(input.files, targets)].sort(
21587
+ (a, b) => String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0
21588
+ )
21589
+ })
21590
+ );
21661
21591
  }
21662
- const hosts = value.hosts;
21663
- const entry = (host2) => {
21664
- const item = hosts[host2];
21665
- if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
21666
- throw new Error(`invalid Swift distribution lock entry for ${host2}`);
21667
- }
21668
- return { sha256: item.sha256, size: item.size };
21669
- };
21670
- return {
21671
- id: value.id,
21672
- release: value.release,
21673
- wasmSdkId: value.wasmSdkId,
21674
- wasmSdkUrl: value.wasmSdkUrl,
21675
- wasmSdkChecksum: value.wasmSdkChecksum,
21676
- source: value.source,
21677
- hosts: {
21678
- "darwin-arm64": entry("darwin-arm64"),
21679
- "linux-x64": entry("linux-x64"),
21680
- "linux-arm64": entry("linux-arm64")
21681
- }
21682
- };
21683
- }
21684
- function swiftDistributionKey(id, host2) {
21685
- return `${id}/${host2}.tar.gz`;
21592
+ return hash.digest("hex");
21686
21593
  }
21687
- var SWIFT_DISTRIBUTION_MANIFEST, SWIFT_DISTRIBUTION_HOSTS, isStrings;
21688
- var init_swift_distribution_contract = __esm({
21689
- "src/swift-distribution-contract.ts"() {
21690
- "use strict";
21691
- init_is_record();
21692
- SWIFT_DISTRIBUTION_MANIFEST = "distribution.json";
21693
- SWIFT_DISTRIBUTION_HOSTS = [
21694
- "darwin-arm64",
21695
- "linux-x64",
21696
- "linux-arm64"
21697
- ];
21698
- isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
21699
- }
21700
- });
21701
-
21702
- // src/swift-icu.ts
21703
- function memo(cache, key, load2) {
21704
- let pending = cache.get(key);
21705
- if (!pending) {
21706
- pending = load2();
21707
- pending.catch(() => cache.delete(key));
21708
- cache.set(key, pending);
21709
- }
21710
- return pending;
21711
- }
21712
- function swiftIcuData(toolchainBin, sdk) {
21713
- return memo(raw, `${toolchainBin}\0${sdk}`, () => load(toolchainBin, sdk));
21714
- }
21715
- function swiftIcuAsset(toolchainBin, sdk) {
21716
- return memo(assets, `${toolchainBin}\0${sdk}`, async () => {
21717
- const zipped = await deflate(await swiftIcuData(toolchainBin, sdk));
21718
- return { sha256: (0, import_node_crypto3.createHash)("sha256").update(zipped).digest("hex"), gzip: zipped };
21719
- });
21720
- }
21721
- async function load(toolchainBin, sdk) {
21722
- const { stdout } = await run(import_node_path8.default.join(toolchainBin, "swift"), [
21723
- "sdk",
21724
- "configure",
21725
- "--show-configuration",
21726
- sdk,
21727
- "wasm32-unknown-wasip1"
21728
- ]);
21729
- const resources = /^swiftStaticResourcesPath: (.+)$/m.exec(stdout)?.[1]?.trim();
21730
- if (!resources) throw new Error(`swift-icu: ${sdk} names no static resources`);
21731
- return Buffer.from(
21732
- icuSegment(archiveMember((0, import_node_fs8.readFileSync)(import_node_path8.default.join(resources, ARCHIVE)), MEMBER))
21594
+ function emitSwiftPackageManifest(args) {
21595
+ const { targets, siblings, moduleRoot, oneModule, spriteKit, distribution } = args;
21596
+ const reachedFrameworks = new Set(
21597
+ [...siblings.values()].flat().filter(
21598
+ (name2) => OPTIONAL_FRAMEWORKS.has(name2) && !targets.some((target) => target.name === name2)
21599
+ ).flatMap((name2) => [name2, ...OPTIONAL_FRAMEWORK_DEPENDENCIES[name2] ?? []])
21733
21600
  );
21734
- }
21735
- function archiveMember(archive, name2) {
21736
- if (archive.toString("latin1", 0, 8) !== "!<arch>\n")
21737
- throw new Error("swift-icu: not an ar archive");
21738
- let names = "";
21739
- for (let at = 8; at + 60 <= archive.length; ) {
21740
- const raw2 = archive.toString("latin1", at, at + 16).trimEnd();
21741
- const size = Number(archive.toString("latin1", at + 48, at + 58).trim());
21742
- const body = archive.subarray(at + 60, at + 60 + size);
21743
- if (raw2 === "//") names = body.toString("latin1");
21744
- const member = /^\/\d+$/.test(raw2) ? names.slice(Number(raw2.slice(1)), names.indexOf("/\n", Number(raw2.slice(1)))) : raw2.replace(/\/$/, "");
21745
- if (member === name2) return body;
21746
- at += 60 + size + size % 2;
21747
- }
21748
- throw new Error(`swift-icu: ${name2} is not in the sdk's icu archive`);
21749
- }
21750
- function icuSegment(object) {
21751
- let at = 8;
21752
- const leb = () => {
21753
- let result = 0;
21754
- let shift = 0;
21755
- let byte;
21756
- do {
21757
- byte = object[at++];
21758
- result += (byte & 127) * 2 ** shift;
21759
- shift += 7;
21760
- } while (byte & 128);
21761
- return result;
21601
+ const distributionObjects = distribution?.objects.filter(
21602
+ (object) => [...OPTIONAL_FRAMEWORKS].every(
21603
+ (name2) => !object.startsWith(`lib/${name2}-`) || reachedFrameworks.has(name2)
21604
+ )
21605
+ );
21606
+ const executable = targets.find((target) => target.executable);
21607
+ if (!executable) throw new Error("swift-compile: no executable target to emit");
21608
+ const stanza = (target) => {
21609
+ const isolation = target.mainActorIsolation ? " .defaultIsolation(MainActor.self)," : "";
21610
+ const imports = distribution ? `, "-I", ${JSON.stringify(import_node_path7.default.join(moduleRoot, "modules"))}` : "";
21611
+ const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ""}${imports}])]`;
21612
+ const deps = [
21613
+ ...distribution ? [] : [
21614
+ '.product(name: "SwiftUI", package: "sootsim-swift")',
21615
+ ...oneModule ? [ONE_PRODUCT] : [],
21616
+ ...spriteKit ? [SPRITEKIT_PRODUCT] : []
21617
+ ],
21618
+ ...(siblings.get(target.name) ?? []).flatMap(
21619
+ (dependency) => OPTIONAL_FRAMEWORKS.has(dependency) && !targets.some((candidate) => candidate.name === dependency) ? distribution ? [] : [`.product(name: "${dependency}", package: "sootsim-swift")`] : [`"${dependency}"`]
21620
+ )
21621
+ ].join(", ");
21622
+ const library = distribution ? [
21623
+ ...(distributionObjects ?? []).map((object) => import_node_path7.default.join(moduleRoot, object)),
21624
+ ...distribution.link
21625
+ ].map((flag) => `, ${JSON.stringify(flag)}`).join("") : "";
21626
+ const kind = target.executable ? ".executableTarget" : ".target";
21627
+ const link = target.executable ? `,
21628
+ linkerSettings: [
21629
+ .unsafeFlags([
21630
+ "-Xclang-linker", "-mexec-model=reactor",
21631
+ "-Xlinker", "--export-if-defined=__main_argc_argv"${library},
21632
+ ]),
21633
+ .unsafeFlags(["-Xlinker", "--strip-all"], .when(configuration: .release)),
21634
+ ]` : "";
21635
+ return [
21636
+ ` ${kind}(`,
21637
+ ` name: "${target.name}",`,
21638
+ ` dependencies: [${deps}],`,
21639
+ ` path: "${target.path}",`,
21640
+ ` ${swiftSettings}${link}`,
21641
+ ` ),`
21642
+ ].join("\n");
21762
21643
  };
21763
- const found = [];
21764
- while (at < object.length) {
21765
- const id = object[at++];
21766
- const size = leb();
21767
- const end = at + size;
21768
- if (id === 11) {
21769
- for (let count = leb(); count > 0; count--) {
21770
- if (leb() !== 0) throw new Error("swift-icu: unexpected data segment kind");
21771
- at++;
21772
- leb();
21773
- at++;
21774
- const length = leb();
21775
- const bytes = object.subarray(at, at + length);
21776
- if (bytes[2] === 218 && bytes[3] === 39) found.push(bytes);
21777
- at += length;
21778
- }
21644
+ return [
21645
+ "// swift-tools-version: 6.2",
21646
+ "import PackageDescription",
21647
+ "",
21648
+ "// generated by swift-compile from the project package partition.",
21649
+ "let package = Package(",
21650
+ ' name: "app",',
21651
+ ` products: [.executable(name: "${executable.name}", targets: ["${executable.name}"])],`,
21652
+ ` dependencies: [${distribution ? "" : `.package(path: "${moduleRoot}")`}],`,
21653
+ " targets: [",
21654
+ ...targets.map(stanza),
21655
+ " ]",
21656
+ ")",
21657
+ ""
21658
+ ].join("\n");
21659
+ }
21660
+ function syncSwiftTree(base, files) {
21661
+ (0, import_node_fs7.mkdirSync)(base, { recursive: true });
21662
+ const walk = (dir) => {
21663
+ for (const entry of (0, import_node_fs7.readdirSync)(dir, { withFileTypes: true })) {
21664
+ const full = import_node_path7.default.join(dir, entry.name);
21665
+ if (dir === base && entry.name === ".build") continue;
21666
+ if (entry.isDirectory()) walk(full);
21667
+ else if (!files.has(full)) (0, import_node_fs7.rmSync)(full, { force: true });
21779
21668
  }
21780
- at = end;
21669
+ };
21670
+ walk(base);
21671
+ for (const [full, contents] of files) {
21672
+ if ((0, import_node_fs7.existsSync)(full) && (0, import_node_fs7.readFileSync)(full, "utf8") === contents) continue;
21673
+ (0, import_node_fs7.mkdirSync)(import_node_path7.default.dirname(full), { recursive: true });
21674
+ (0, import_node_fs7.writeFileSync)(full, contents, "utf8");
21781
21675
  }
21782
- if (found.length !== 1)
21783
- throw new Error(`swift-icu: expected one icu data segment, found ${found.length}`);
21784
- return found[0];
21785
21676
  }
21786
- var import_node_child_process4, import_node_crypto3, import_node_fs8, import_node_path8, import_node_util, import_node_zlib, run, deflate, ARCHIVE, MEMBER, raw, assets;
21787
- var init_swift_icu = __esm({
21788
- "src/swift-icu.ts"() {
21789
- "use strict";
21790
- import_node_child_process4 = require("node:child_process");
21791
- import_node_crypto3 = require("node:crypto");
21792
- import_node_fs8 = require("node:fs");
21793
- import_node_path8 = __toESM(require("node:path"), 1);
21794
- import_node_util = require("node:util");
21795
- import_node_zlib = require("node:zlib");
21796
- run = (0, import_node_util.promisify)(import_node_child_process4.execFile);
21797
- deflate = (0, import_node_util.promisify)(import_node_zlib.gzip);
21798
- ARCHIVE = "wasi/lib_FoundationICU.a";
21799
- MEMBER = "icu_packaged_data.cpp.obj";
21800
- raw = /* @__PURE__ */ new Map();
21801
- assets = /* @__PURE__ */ new Map();
21802
- }
21803
- });
21804
-
21805
- // src/swift-package.ts
21806
- function swiftManifestTargets(manifest) {
21807
- const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
21808
- const targets = [];
21809
- const pattern = /\.(executableTarget|target)\s*\(/g;
21810
- let match;
21811
- while ((match = pattern.exec(code)) !== null) {
21812
- const executable = match[1] === "executableTarget";
21813
- let depth = 1;
21814
- const start = pattern.lastIndex;
21815
- let i = start;
21816
- let inString = false;
21817
- let escaped = false;
21818
- let flat = "";
21819
- while (i < code.length && depth > 0) {
21820
- const ch = code[i];
21821
- if (inString) {
21822
- if (escaped) escaped = false;
21823
- else if (ch === "\\") escaped = true;
21824
- else if (ch === '"') inString = false;
21825
- if (depth === 1) flat += ch;
21826
- } else if (ch === '"') {
21827
- inString = true;
21828
- if (depth === 1) flat += ch;
21829
- } else if (ch === "(") {
21830
- depth++;
21831
- if (depth === 1) flat += ch;
21832
- } else if (ch === ")") {
21833
- depth--;
21834
- if (depth >= 1) flat += ch;
21835
- } else if (depth === 1) {
21836
- flat += ch;
21837
- }
21838
- i++;
21677
+ function splitTopLevel(text) {
21678
+ const parts = [];
21679
+ let depth = 0;
21680
+ let start = 0;
21681
+ for (let i = 0; i < text.length; i++) {
21682
+ const char = text[i];
21683
+ if (char === "(" || char === "[" || char === "<") depth++;
21684
+ else if (char === ")" || char === "]" || char === ">" && text[i - 1] !== "-")
21685
+ depth--;
21686
+ else if (char === "," && depth === 0) {
21687
+ parts.push(text.slice(start, i));
21688
+ start = i + 1;
21839
21689
  }
21840
- const name2 = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
21841
- if (!name2) continue;
21842
- const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
21843
- const targetPath = rawPath == null || rawPath === "" ? `Sources/${name2}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
21844
- const call = code.slice(start, i);
21845
- const languageMode = Number(
21846
- /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
21847
- );
21848
- const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
21849
- const resources = /\bresources\s*:/.test(flat);
21850
- targets.push({
21851
- name: name2,
21852
- path: targetPath,
21853
- executable,
21854
- languageMode,
21855
- mainActorIsolation,
21856
- resources
21857
- });
21858
21690
  }
21859
- return targets;
21860
- }
21861
- function swiftPackagePartition(manifest) {
21862
- const targets = swiftManifestTargets(manifest);
21863
- return targets.length === 1 && targets[0].executable && targets[0].path === "." ? [] : targets;
21691
+ parts.push(text.slice(start));
21692
+ return parts.map((part) => part.trim()).filter((part) => part !== "");
21864
21693
  }
21865
- var init_swift_package = __esm({
21866
- "src/swift-package.ts"() {
21867
- "use strict";
21694
+ function forwardedArguments(parameters) {
21695
+ const args = [];
21696
+ for (const parameter of splitTopLevel(parameters)) {
21697
+ const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter);
21698
+ if (!match || match[3].includes("...")) return null;
21699
+ const label = match[1] ?? match[2];
21700
+ const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]) ? "&" : "") + match[2];
21701
+ args.push(label === "_" ? value : `${label}: ${value}`);
21868
21702
  }
21869
- });
21870
-
21871
- // src/swift-compile.ts
21872
- function swiftDistributionAt(root) {
21873
- const file = import_node_path9.default.join(root, SWIFT_DISTRIBUTION_MANIFEST);
21874
- if (!(0, import_node_fs9.existsSync)(file)) return null;
21875
- return parseSwiftDistributionManifest(JSON.parse((0, import_node_fs9.readFileSync)(file, "utf8")));
21876
- }
21877
- function swiftModuleSdk(root) {
21878
- const pin = swiftDistributionAt(root) ?? JSON.parse((0, import_node_fs9.readFileSync)(import_node_path9.default.join(root, "toolchain.json"), "utf8"));
21879
- if (!pin || typeof pin !== "object" || typeof Reflect.get(pin, "wasmSdkId") !== "string" || typeof Reflect.get(pin, "wasmSdkUrl") !== "string" || typeof Reflect.get(pin, "wasmSdkChecksum") !== "string")
21880
- throw new Error(`${root} pins no wasm SDK id, url and checksum`);
21881
- return {
21882
- wasmSdkId: String(Reflect.get(pin, "wasmSdkId")),
21883
- wasmSdkUrl: String(Reflect.get(pin, "wasmSdkUrl")),
21884
- wasmSdkChecksum: String(Reflect.get(pin, "wasmSdkChecksum"))
21885
- };
21886
- }
21887
- function swiftModuleInputFiles(root) {
21888
- if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST];
21889
- const files = [
21890
- "Package.swift",
21891
- "scripts/contrast-app-Package.swift",
21892
- "toolchain.json"
21893
- ];
21894
- const walk = (dir) => {
21895
- for (const entry of (0, import_node_fs9.readdirSync)(import_node_path9.default.join(root, dir), { withFileTypes: true })) {
21896
- const relative2 = `${dir}/${entry.name}`;
21897
- if (entry.isDirectory()) walk(relative2);
21898
- else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative2);
21899
- }
21900
- };
21901
- walk("Sources");
21902
- return files.sort();
21903
- }
21904
- async function ensureMacroPlugins(moduleRoot, toolchainBin) {
21905
- const distribution = swiftDistributionAt(moduleRoot);
21906
- if (distribution)
21907
- return distribution.plugins.map((plugin) => import_node_path9.default.join(moduleRoot, plugin));
21908
- const dir = import_node_path9.default.join(moduleRoot, ".build/host/RnxPreviewMacros");
21909
- const ext = process.platform === "darwin" ? "dylib" : "so";
21910
- const plugins = [
21911
- {
21912
- library: import_node_path9.default.join(dir, `libRnxPreviewMacros.${ext}`),
21913
- source: import_node_path9.default.join(moduleRoot, "Sources/RnxPreviewMacros/PreviewMacro.swift")
21914
- },
21915
- {
21916
- library: import_node_path9.default.join(dir, `libFoundationMacros.${ext}`),
21917
- source: import_node_path9.default.join(moduleRoot, "Sources/FoundationMacros/PredicateMacro.swift")
21918
- }
21919
- ];
21920
- const stale = plugins.some(
21921
- ({ library, source }) => !(0, import_node_fs9.existsSync)(library) || (0, import_node_fs9.statSync)(source).mtimeMs > (0, import_node_fs9.statSync)(library).mtimeMs
21922
- );
21923
- if (stale) {
21924
- await run2("sh", [
21925
- import_node_path9.default.join(moduleRoot, "scripts/build-preview-plugin.sh"),
21926
- toolchainBin,
21927
- plugins[0].library
21928
- ]);
21929
- }
21930
- return plugins.map(({ library }) => library);
21931
- }
21932
- function swiftModuleDigest(root) {
21933
- const files = swiftModuleInputFiles(root);
21934
- const stampHash = (0, import_node_crypto4.createHash)("sha256");
21935
- for (const file of files) {
21936
- const stat2 = (0, import_node_fs9.statSync)(import_node_path9.default.join(root, file), { bigint: true });
21937
- stampHash.update(file);
21938
- stampHash.update(
21939
- `${stat2.dev}:${stat2.ino}:${stat2.size}:${stat2.mtimeNs}:${stat2.ctimeNs}
21940
- `
21941
- );
21942
- }
21943
- const stamp = stampHash.digest("hex");
21944
- const cached4 = linkedModuleDigests.get(root);
21945
- if (cached4?.stamp === stamp) return cached4.digest;
21946
- const hash = (0, import_node_crypto4.createHash)("sha256");
21947
- for (const file of files) {
21948
- hash.update((0, import_node_crypto4.createHash)("sha256").update(file).digest());
21949
- hash.update(
21950
- (0, import_node_crypto4.createHash)("sha256").update((0, import_node_fs9.readFileSync)(import_node_path9.default.join(root, file))).digest()
21951
- );
21952
- }
21953
- const digest = hash.digest();
21954
- linkedModuleDigests.set(root, { stamp, digest });
21955
- return digest;
21956
- }
21957
- function compileTargets(input) {
21958
- const manifest = input.files["Package.swift"];
21959
- return manifest === void 0 ? [] : swiftPackagePartition(manifest);
21960
- }
21961
- function withNativeSourceGlue(input, glue) {
21962
- const targets = compileTargets(input);
21963
- if (targets.length > 1) {
21964
- throw new Error("swift native modules need one SwiftPM target");
21965
- }
21966
- const targetPath = targets[0]?.path === "." ? "" : targets[0]?.path ?? "";
21967
- return {
21968
- ...input,
21969
- files: {
21970
- ...input.files,
21971
- [import_node_path9.default.posix.join(targetPath, "OneNativeSource.generated.swift")]: glue
21972
- },
21973
- oneModule: true
21974
- };
21975
- }
21976
- function swiftTargetDependencies(files, targets) {
21977
- const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
21978
- const siblings = /* @__PURE__ */ new Map();
21979
- for (const target of targets) {
21980
- const prefix = target.path === "." ? "" : `${target.path}/`;
21981
- const deps = /* @__PURE__ */ new Set();
21982
- for (const [file, contents] of Object.entries(files)) {
21983
- if (file === "Package.swift" || !file.startsWith(prefix)) continue;
21984
- if (targets.some(
21985
- (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
21986
- ))
21987
- continue;
21988
- for (const match of contents.matchAll(
21989
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm
21990
- )) {
21991
- if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1]);
21992
- }
21993
- }
21994
- siblings.set(target.name, [...deps].sort());
21995
- }
21996
- return siblings;
21997
- }
21998
- function swiftArtifactHash(input, release, moduleRoot) {
21999
- const hash = (0, import_node_crypto4.createHash)("sha256");
22000
- hash.update(`swift-compile/v12
22001
- ${release}
22002
- `);
22003
- if (input.oneModule) hash.update("one-module\n");
22004
- hash.update(swiftModuleDigest(moduleRoot));
22005
- for (const file of Object.keys(input.files).sort()) {
22006
- hash.update((0, import_node_crypto4.createHash)("sha256").update(file).digest());
22007
- hash.update((0, import_node_crypto4.createHash)("sha256").update(input.files[file]).digest());
22008
- }
22009
- for (const base of Object.keys(input.resources ?? {}).sort()) {
22010
- hash.update((0, import_node_crypto4.createHash)("sha256").update(base).digest());
22011
- hash.update(
22012
- (0, import_node_crypto4.createHash)("sha256").update(input.resources?.[base] ?? "").digest()
22013
- );
22014
- }
22015
- for (const name2 of Object.keys(input.images ?? {}).sort()) {
22016
- const image = input.images?.[name2];
22017
- if (!image) continue;
22018
- hash.update((0, import_node_crypto4.createHash)("sha256").update(name2).digest());
22019
- hash.update((0, import_node_crypto4.createHash)("sha256").update(image.file).digest());
22020
- hash.update((0, import_node_crypto4.createHash)("sha256").update(image.data).digest());
22021
- }
22022
- const targets = compileTargets(input);
22023
- if (targets.length > 0) {
22024
- hash.update(`swift-multi/v${MULTI_MANIFEST_VERSION}
22025
- `);
22026
- hash.update(
22027
- JSON.stringify({
22028
- targets,
22029
- siblings: [...swiftTargetDependencies(input.files, targets)].sort(
22030
- (a, b) => String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0
22031
- )
22032
- })
22033
- );
22034
- }
22035
- return hash.digest("hex");
22036
- }
22037
- function emitSwiftPackageManifest(args) {
22038
- const { targets, siblings, moduleRoot, oneModule, spriteKit, distribution } = args;
22039
- const reachedFrameworks = new Set(
22040
- [...siblings.values()].flat().filter(
22041
- (name2) => OPTIONAL_FRAMEWORKS.has(name2) && !targets.some((target) => target.name === name2)
22042
- ).flatMap((name2) => [name2, ...OPTIONAL_FRAMEWORK_DEPENDENCIES[name2] ?? []])
22043
- );
22044
- const distributionObjects = distribution?.objects.filter(
22045
- (object) => [...OPTIONAL_FRAMEWORKS].every(
22046
- (name2) => !object.startsWith(`lib/${name2}-`) || reachedFrameworks.has(name2)
22047
- )
22048
- );
22049
- const executable = targets.find((target) => target.executable);
22050
- if (!executable) throw new Error("swift-compile: no executable target to emit");
22051
- const stanza = (target) => {
22052
- const isolation = target.mainActorIsolation ? " .defaultIsolation(MainActor.self)," : "";
22053
- const imports = distribution ? `, "-I", ${JSON.stringify(import_node_path9.default.join(moduleRoot, "modules"))}` : "";
22054
- const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ""}${imports}])]`;
22055
- const deps = [
22056
- ...distribution ? [] : [
22057
- '.product(name: "SwiftUI", package: "sootsim-swift")',
22058
- ...oneModule ? [ONE_PRODUCT] : [],
22059
- ...spriteKit ? [SPRITEKIT_PRODUCT] : []
22060
- ],
22061
- ...(siblings.get(target.name) ?? []).flatMap(
22062
- (dependency) => OPTIONAL_FRAMEWORKS.has(dependency) && !targets.some((candidate) => candidate.name === dependency) ? distribution ? [] : [`.product(name: "${dependency}", package: "sootsim-swift")`] : [`"${dependency}"`]
22063
- )
22064
- ].join(", ");
22065
- const library = distribution ? [
22066
- ...(distributionObjects ?? []).map((object) => import_node_path9.default.join(moduleRoot, object)),
22067
- ...distribution.link
22068
- ].map((flag) => `, ${JSON.stringify(flag)}`).join("") : "";
22069
- const kind = target.executable ? ".executableTarget" : ".target";
22070
- const link = target.executable ? `,
22071
- linkerSettings: [
22072
- .unsafeFlags([
22073
- "-Xclang-linker", "-mexec-model=reactor",
22074
- "-Xlinker", "--export-if-defined=__main_argc_argv"${library},
22075
- ]),
22076
- .unsafeFlags(["-Xlinker", "--strip-all"], .when(configuration: .release)),
22077
- ]` : "";
22078
- return [
22079
- ` ${kind}(`,
22080
- ` name: "${target.name}",`,
22081
- ` dependencies: [${deps}],`,
22082
- ` path: "${target.path}",`,
22083
- ` ${swiftSettings}${link}`,
22084
- ` ),`
22085
- ].join("\n");
22086
- };
22087
- return [
22088
- "// swift-tools-version: 6.2",
22089
- "import PackageDescription",
22090
- "",
22091
- "// generated by swift-compile from the project package partition.",
22092
- "let package = Package(",
22093
- ' name: "app",',
22094
- ` products: [.executable(name: "${executable.name}", targets: ["${executable.name}"])],`,
22095
- ` dependencies: [${distribution ? "" : `.package(path: "${moduleRoot}")`}],`,
22096
- " targets: [",
22097
- ...targets.map(stanza),
22098
- " ]",
22099
- ")",
22100
- ""
22101
- ].join("\n");
22102
- }
22103
- function syncSwiftTree(base, files) {
22104
- (0, import_node_fs9.mkdirSync)(base, { recursive: true });
22105
- const walk = (dir) => {
22106
- for (const entry of (0, import_node_fs9.readdirSync)(dir, { withFileTypes: true })) {
22107
- const full = import_node_path9.default.join(dir, entry.name);
22108
- if (dir === base && entry.name === ".build") continue;
22109
- if (entry.isDirectory()) walk(full);
22110
- else if (!files.has(full)) (0, import_node_fs9.rmSync)(full, { force: true });
22111
- }
22112
- };
22113
- walk(base);
22114
- for (const [full, contents] of files) {
22115
- if ((0, import_node_fs9.existsSync)(full) && (0, import_node_fs9.readFileSync)(full, "utf8") === contents) continue;
22116
- (0, import_node_fs9.mkdirSync)(import_node_path9.default.dirname(full), { recursive: true });
22117
- (0, import_node_fs9.writeFileSync)(full, contents, "utf8");
22118
- }
22119
- }
22120
- function splitTopLevel(text) {
22121
- const parts = [];
22122
- let depth = 0;
22123
- let start = 0;
22124
- for (let i = 0; i < text.length; i++) {
22125
- const char = text[i];
22126
- if (char === "(" || char === "[" || char === "<") depth++;
22127
- else if (char === ")" || char === "]" || char === ">" && text[i - 1] !== "-")
22128
- depth--;
22129
- else if (char === "," && depth === 0) {
22130
- parts.push(text.slice(start, i));
22131
- start = i + 1;
22132
- }
22133
- }
22134
- parts.push(text.slice(start));
22135
- return parts.map((part) => part.trim()).filter((part) => part !== "");
22136
- }
22137
- function forwardedArguments(parameters) {
22138
- const args = [];
22139
- for (const parameter of splitTopLevel(parameters)) {
22140
- const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter);
22141
- if (!match || match[3].includes("...")) return null;
22142
- const label = match[1] ?? match[2];
22143
- const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]) ? "&" : "") + match[2];
22144
- args.push(label === "_" ? value : `${label}: ${value}`);
22145
- }
22146
- return args.join(", ");
21703
+ return args.join(", ");
22147
21704
  }
22148
21705
  function liftExtensionOverrides(source) {
22149
21706
  const { tokens } = swiftCodeScan(source);
@@ -22272,447 +21829,890 @@ function liftExtensionOverrides(source) {
22272
21829
  edits.push(...entry.edits);
22273
21830
  stubs.set(brace, [...stubs.get(brace) ?? [], entry.stub]);
22274
21831
  }
22275
- for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
22276
- let out = source;
22277
- for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
22278
- out = out.slice(0, at) + insert + out.slice(at + remove);
22279
- return out;
21832
+ for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
21833
+ let out = source;
21834
+ for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
21835
+ out = out.slice(0, at) + insert + out.slice(at + remove);
21836
+ return out;
21837
+ }
21838
+ function swiftSourceAsIOS(original) {
21839
+ const source = liftExtensionOverrides(original);
21840
+ const { lineStarts, tokens } = swiftCodeScan(source);
21841
+ let offset = 0;
21842
+ const conditioned = source.split("\n").map((line) => {
21843
+ const start = offset;
21844
+ offset += line.length + 1;
21845
+ if (!lineStarts.has(start) || !DIRECTIVE.test(line)) return line;
21846
+ return line.replace(OS_IOS, (match) => "true".padEnd(match.length));
21847
+ }).join("\n");
21848
+ let out = "";
21849
+ let copied = 0;
21850
+ const reusableViews = new Set(REUSABLE_VIEW_BASES);
21851
+ const reusableBodies = [];
21852
+ let depth = 0;
21853
+ let opensReusableBody = false;
21854
+ for (const at of tokens) {
21855
+ const rest = conditioned.slice(at, at + 400);
21856
+ if (rest.startsWith("{")) {
21857
+ depth++;
21858
+ if (opensReusableBody) reusableBodies.push(depth);
21859
+ opensReusableBody = false;
21860
+ continue;
21861
+ }
21862
+ if (rest.startsWith("}")) {
21863
+ if (reusableBodies.at(-1) === depth) reusableBodies.pop();
21864
+ depth--;
21865
+ continue;
21866
+ }
21867
+ if (rest.startsWith("override")) {
21868
+ if (REUSABLE_INIT.test(rest) || reusableBodies.at(-1) === depth && FRAME_INIT.test(rest)) {
21869
+ out += `${conditioned.slice(copied, at)}required`;
21870
+ copied = at + "override".length;
21871
+ }
21872
+ continue;
21873
+ }
21874
+ const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest);
21875
+ if (imported) {
21876
+ out += conditioned.slice(copied, at) + "import CoreImage".padEnd(imported[0].length);
21877
+ copied = at + imported[0].length;
21878
+ continue;
21879
+ }
21880
+ if (/^NSClassFromString\b/.test(rest)) {
21881
+ out += conditioned.slice(copied, at) + "_peachClassFromString";
21882
+ copied = at + "NSClassFromString".length;
21883
+ continue;
21884
+ }
21885
+ if (rest.startsWith("class")) {
21886
+ const declared = CLASS_BASE.exec(rest);
21887
+ if (declared && reusableViews.has(declared[2].split(".").pop())) {
21888
+ reusableViews.add(declared[1]);
21889
+ opensReusableBody = true;
21890
+ }
21891
+ const modifiers = conditioned.slice(conditioned.lastIndexOf("\n", at - 1) + 1, at);
21892
+ if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
21893
+ out += `${conditioned.slice(copied, at)}final `;
21894
+ copied = at;
21895
+ }
21896
+ continue;
21897
+ }
21898
+ const selector = SELECTOR.exec(rest);
21899
+ const match = selector ?? OBJC_ATTRIBUTE.exec(rest);
21900
+ if (!match) continue;
21901
+ let replacement = "@ObjC";
21902
+ if (selector) replacement = "#Selector";
21903
+ else if (match[0] === "@objcMembers") replacement = "@ObjCMembers";
21904
+ else if (match[0] === "@IBAction") replacement = "@ObjC".padEnd(match[0].length);
21905
+ else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
21906
+ replacement = " ".repeat(match[0].length);
21907
+ else if (match[2] !== void 0)
21908
+ replacement = `@ObjC${match[1]}("${match[2].trim()}")`;
21909
+ out += conditioned.slice(copied, at) + replacement;
21910
+ copied = at + match[0].length;
21911
+ }
21912
+ return out + conditioned.slice(copied);
21913
+ }
21914
+ function swiftCodeScan(source) {
21915
+ const starts = /* @__PURE__ */ new Set();
21916
+ const tokens = [];
21917
+ const stack = [{ kind: "code", parens: 0 }];
21918
+ const hashesAt = (at) => {
21919
+ let end = at;
21920
+ while (source[end] === "#") end++;
21921
+ return end - at;
21922
+ };
21923
+ const closes = (at, hashes) => source.startsWith("#".repeat(hashes), at);
21924
+ let i = 0;
21925
+ while (i < source.length) {
21926
+ const top = stack[stack.length - 1];
21927
+ if ((i === 0 || source[i - 1] === "\n") && top.kind === "code" && stack.length === 1)
21928
+ starts.add(i);
21929
+ const char = source[i];
21930
+ if (top.kind === "block") {
21931
+ if (source.startsWith("/*", i)) {
21932
+ top.depth++;
21933
+ i += 2;
21934
+ } else if (source.startsWith("*/", i)) {
21935
+ if (--top.depth === 0) stack.pop();
21936
+ i += 2;
21937
+ } else i++;
21938
+ continue;
21939
+ }
21940
+ if (top.kind === "string") {
21941
+ if (char === "\\" && closes(i + 1, top.hashes)) {
21942
+ const after = i + 1 + top.hashes;
21943
+ if (source[after] === "(") {
21944
+ stack.push({ kind: "code", parens: 0 });
21945
+ i = after + 1;
21946
+ } else i = after + 1;
21947
+ continue;
21948
+ }
21949
+ const quote = top.multiline ? '"""' : '"';
21950
+ if (source.startsWith(quote, i) && closes(i + quote.length, top.hashes)) {
21951
+ stack.pop();
21952
+ i += quote.length + top.hashes;
21953
+ } else i++;
21954
+ continue;
21955
+ }
21956
+ if (top.kind === "regex") {
21957
+ if (char === "/" && closes(i + 1, top.hashes)) {
21958
+ stack.pop();
21959
+ i += 1 + top.hashes;
21960
+ } else i++;
21961
+ continue;
21962
+ }
21963
+ if (source.startsWith("//", i)) {
21964
+ const end = source.indexOf("\n", i);
21965
+ i = end === -1 ? source.length : end;
21966
+ } else if (source.startsWith("/*", i)) {
21967
+ stack.push({ kind: "block", depth: 1 });
21968
+ i += 2;
21969
+ } else if (char === '"' || char === "#") {
21970
+ const hashes = hashesAt(i);
21971
+ const at = i + hashes;
21972
+ if (source.startsWith('"""', at)) {
21973
+ stack.push({ kind: "string", hashes, multiline: true });
21974
+ i = at + 3;
21975
+ } else if (source[at] === '"') {
21976
+ stack.push({ kind: "string", hashes, multiline: false });
21977
+ i = at + 1;
21978
+ } else if (hashes > 0 && source[at] === "/") {
21979
+ stack.push({ kind: "regex", hashes });
21980
+ i = at + 1;
21981
+ } else {
21982
+ if (hashes > 0) tokens.push(at - 1);
21983
+ i = Math.max(at, i + 1);
21984
+ }
21985
+ } else if (char === "{" || char === "}") {
21986
+ tokens.push(i);
21987
+ i++;
21988
+ } else if (char === "(") {
21989
+ top.parens++;
21990
+ i++;
21991
+ } else if (char === ")") {
21992
+ if (top.parens === 0 && stack.length > 1) stack.pop();
21993
+ else top.parens--;
21994
+ i++;
21995
+ } else {
21996
+ const keyword = source.startsWith("class", i) ? "class" : source.startsWith("extension", i) ? "extension" : source.startsWith("override", i) ? "override" : source.startsWith("import", i) ? "import" : source.startsWith("NSClassFromString", i) ? "NSClassFromString" : null;
21997
+ if (keyword && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
21998
+ tokens.push(i);
21999
+ i += keyword.length;
22000
+ } else {
22001
+ if (char === "@") tokens.push(i);
22002
+ i++;
22003
+ }
22004
+ }
22005
+ }
22006
+ return { lineStarts: starts, tokens };
22007
+ }
22008
+ function writeSwiftProject(layout, input, moduleRoot) {
22009
+ const distribution = swiftDistributionAt(moduleRoot);
22010
+ const targets = distribution && compileTargets(input).length === 0 ? [
22011
+ {
22012
+ name: "App",
22013
+ path: import_node_path7.default.relative(layout.root, layout.sources),
22014
+ executable: true,
22015
+ languageMode: 5,
22016
+ mainActorIsolation: false,
22017
+ resources: false
22018
+ }
22019
+ ] : compileTargets(input);
22020
+ const files = /* @__PURE__ */ new Map();
22021
+ const moduleFiles = `
22022
+ // sootsim-swift files ${(0, import_node_crypto3.createHash)("sha256").update(swiftModuleInputFiles(moduleRoot).join("\n")).digest("hex").slice(0, 16)}
22023
+ `;
22024
+ if (targets.length === 0) {
22025
+ for (const [file, contents] of Object.entries(input.files)) {
22026
+ if (file === "Package.swift") continue;
22027
+ files.set(import_node_path7.default.join(layout.sources, file), compiledSource(file, contents));
22028
+ }
22029
+ let manifest = (0, import_node_fs7.readFileSync)(
22030
+ import_node_path7.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
22031
+ "utf8"
22032
+ ).replaceAll("__SOOTSIM_SWIFT_PACKAGE__", moduleRoot);
22033
+ const optionalProducts = swiftTargetDependencies(input.files, [{ name: "App", path: "." }]).get("App") ?? [];
22034
+ if (optionalProducts.length > 0) {
22035
+ const product = '.product(name: "SwiftUI", package: "sootsim-swift"),';
22036
+ if (!manifest.includes(product))
22037
+ throw new Error("Swift app template lost its framework dependency anchor");
22038
+ manifest = manifest.replace(
22039
+ product,
22040
+ [
22041
+ product,
22042
+ ...optionalProducts.map(
22043
+ (name2) => `.product(name: "${name2}", package: "sootsim-swift"),`
22044
+ )
22045
+ ].join("\n ")
22046
+ );
22047
+ }
22048
+ if (input.oneModule) {
22049
+ const product = '.product(name: "CoreLocation", package: "sootsim-swift"),';
22050
+ const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`;
22051
+ if (!manifest.includes(product) || !manifest.includes(flags)) {
22052
+ throw new Error(
22053
+ "scripts/contrast-app-Package.swift lost the lines the One module links at"
22054
+ );
22055
+ }
22056
+ manifest = manifest.replace(product, `${product}
22057
+ ${ONE_PRODUCT},`).replace(flags, `${flags}${ONE_IMPLICIT_FLAGS}`);
22058
+ }
22059
+ if (importsSpriteKit(input.files)) {
22060
+ const anchor = '.product(name: "CoreLocation", package: "sootsim-swift"),';
22061
+ if (!manifest.includes(anchor))
22062
+ throw new Error(
22063
+ "scripts/contrast-app-Package.swift lost the line the SpriteKit product links at"
22064
+ );
22065
+ manifest = manifest.replace(anchor, `${anchor}
22066
+ ${SPRITEKIT_PRODUCT},`);
22067
+ }
22068
+ files.set(import_node_path7.default.join(layout.root, "Package.swift"), manifest + moduleFiles);
22069
+ } else {
22070
+ const base = layout.multi ? layout.root : layout.sources;
22071
+ for (const [file, contents] of Object.entries(input.files)) {
22072
+ if (file === "Package.swift") continue;
22073
+ files.set(import_node_path7.default.join(base, file), compiledSource(file, contents));
22074
+ }
22075
+ for (const target of targets) {
22076
+ if (!target.resources) continue;
22077
+ files.set(
22078
+ import_node_path7.default.join(layout.root, target.path, "ResourceBundleAccessor.generated.swift"),
22079
+ [
22080
+ "import Foundation",
22081
+ "",
22082
+ "extension Foundation.Bundle {",
22083
+ " static let module: Bundle = Bundle.main",
22084
+ "}",
22085
+ ""
22086
+ ].join("\n")
22087
+ );
22088
+ }
22089
+ files.set(
22090
+ import_node_path7.default.join(layout.root, "Package.swift"),
22091
+ emitSwiftPackageManifest({
22092
+ targets,
22093
+ siblings: swiftTargetDependencies(
22094
+ input.files,
22095
+ layout.multi ? targets : targets.map((target) => ({ ...target, path: "." }))
22096
+ ),
22097
+ moduleRoot,
22098
+ oneModule: input.oneModule,
22099
+ spriteKit: importsSpriteKit(input.files),
22100
+ distribution: distribution ?? void 0
22101
+ }) + moduleFiles
22102
+ );
22103
+ }
22104
+ syncSwiftTree(layout.root, files);
22105
+ }
22106
+ function streamText(value) {
22107
+ if (typeof value === "string") return value.trim();
22108
+ if (Buffer.isBuffer(value)) return value.toString("utf8").trim();
22109
+ return "";
22110
+ }
22111
+ function outputOf(error) {
22112
+ if (error && typeof error === "object") {
22113
+ const streams = [
22114
+ streamText(Reflect.get(error, "stdout")),
22115
+ streamText(Reflect.get(error, "stderr"))
22116
+ ].filter(Boolean);
22117
+ if (streams.length > 0) return streams.join("\n");
22118
+ }
22119
+ return error instanceof Error ? error.message : String(error);
22120
+ }
22121
+ function builtArtifact(layout) {
22122
+ const binDir = import_node_path7.default.join(layout.root, ".build", WASM_TRIPLE, "release");
22123
+ const manifest = (0, import_node_fs7.readFileSync)(import_node_path7.default.join(layout.root, "Package.swift"), "utf8");
22124
+ const executable = swiftManifestTargets(manifest).find((target) => target.executable);
22125
+ if (executable === void 0) {
22126
+ throw new Error("swift-compile: the written manifest names no executable target");
22127
+ }
22128
+ const file = import_node_path7.default.join(binDir, `${executable.name}.wasm`);
22129
+ if (!(0, import_node_fs7.existsSync)(file)) {
22130
+ const found = (0, import_node_fs7.existsSync)(binDir) ? (0, import_node_fs7.readdirSync)(binDir).filter((name2) => name2.endsWith(".wasm")).sort() : [];
22131
+ throw new Error(
22132
+ `swift-compile: the build produced no ${executable.name}.wasm (found: ${found.join(", ") || "none"})`
22133
+ );
22134
+ }
22135
+ return file;
22136
+ }
22137
+ function projectDiagnostic(output, layout) {
22138
+ const base = layout.multi ? layout.root : layout.sources;
22139
+ const prefix = `${base}${import_node_path7.default.sep}`;
22140
+ return output.split("\n").map((line) => line.startsWith(prefix) ? line.slice(prefix.length) : line).join("\n").trim();
22141
+ }
22142
+ function serialize(root, work) {
22143
+ const current = rootLocks.get(root) ?? Promise.resolve();
22144
+ const next = current.then(work, work);
22145
+ rootLocks.set(
22146
+ root,
22147
+ next.catch(() => {
22148
+ })
22149
+ );
22150
+ return next;
22151
+ }
22152
+ function compileSwiftProjectUnit(input, options) {
22153
+ (0, import_node_fs7.mkdirSync)(options.buildRoot, { recursive: true });
22154
+ const root = (0, import_node_fs7.realpathSync)(options.buildRoot);
22155
+ const moduleRoot = import_node_path7.default.resolve(options.moduleRoot);
22156
+ const layout = {
22157
+ root,
22158
+ sources: import_node_path7.default.join(root, "Sources", "App"),
22159
+ multi: compileTargets(input).length > 0
22160
+ };
22161
+ const hash = swiftArtifactHash(input, options.release, moduleRoot);
22162
+ return serialize(root, async () => {
22163
+ writeSwiftProject(layout, input, moduleRoot);
22164
+ const swift = import_node_path7.default.join(options.toolchainBin, "swift");
22165
+ if (!(0, import_node_fs7.existsSync)(swift)) {
22166
+ throw new Error(
22167
+ `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`
22168
+ );
22169
+ }
22170
+ const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin);
22171
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
22172
+ const icu = swiftIcuAsset(options.toolchainBin, sdk);
22173
+ try {
22174
+ await run2(
22175
+ swift,
22176
+ [
22177
+ "build",
22178
+ "-j",
22179
+ BUILD_JOBS,
22180
+ "--package-path",
22181
+ root,
22182
+ "--swift-sdk",
22183
+ sdk,
22184
+ "-c",
22185
+ "release",
22186
+ "-Xswiftc",
22187
+ "-Osize",
22188
+ ...macroPlugins.flatMap((plugin) => [
22189
+ "-Xswiftc",
22190
+ "-load-plugin-library",
22191
+ "-Xswiftc",
22192
+ plugin
22193
+ ])
22194
+ ],
22195
+ { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs }
22196
+ );
22197
+ } catch (error) {
22198
+ throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error });
22199
+ }
22200
+ return {
22201
+ hash,
22202
+ bytes: (0, import_node_fs7.readFileSync)(builtArtifact(layout)),
22203
+ icu: await icu
22204
+ };
22205
+ });
22206
+ }
22207
+ var import_node_child_process4, import_node_crypto3, import_node_fs7, import_node_os2, import_node_path7, import_node_util2, run2, WASM_TRIPLE, cores, BUILD_ENV, BUILD_JOBS, linkedModuleDigests, OPTIONAL_FRAMEWORK_DEPENDENCIES, OPTIONAL_FRAMEWORKS, ONE_PRODUCT, SPRITEKIT_PRODUCT, importsSpriteKit, FOUNDATION_IMPLICIT_FLAGS, ONE_IMPLICIT_FLAGS, MULTI_MANIFEST_VERSION, DIRECTIVE, OS_IOS, OBJC_ATTRIBUTE, SELECTOR, TYPE_AFTER_ATTRIBUTE, DELEGATE_CLASS, REUSABLE_INIT, REUSABLE_VIEW_BASES, CLASS_BASE, FRAME_INIT, APPLE_CLASS, EXTENSION_DECL, CLASS_DECL, MODIFIERS, OVERRIDE_FUNC, OVERRIDE_VAR, compiledSource, ROOT_LOCKS, host, rootLocks;
22208
+ var init_swift_compile = __esm({
22209
+ "src/swift-compile.ts"() {
22210
+ "use strict";
22211
+ import_node_child_process4 = require("node:child_process");
22212
+ import_node_crypto3 = require("node:crypto");
22213
+ import_node_fs7 = require("node:fs");
22214
+ import_node_os2 = __toESM(require("node:os"), 1);
22215
+ import_node_path7 = __toESM(require("node:path"), 1);
22216
+ import_node_util2 = require("node:util");
22217
+ init_swift_distribution_contract();
22218
+ init_swift_icu();
22219
+ init_swift_package();
22220
+ run2 = (0, import_node_util2.promisify)(import_node_child_process4.execFile);
22221
+ WASM_TRIPLE = "wasm32-unknown-wasip1";
22222
+ cores = import_node_os2.default.availableParallelism();
22223
+ BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) };
22224
+ BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)));
22225
+ linkedModuleDigests = /* @__PURE__ */ new Map();
22226
+ OPTIONAL_FRAMEWORK_DEPENDENCIES = {
22227
+ Accelerate: [],
22228
+ CryptoKit: [],
22229
+ Security: [],
22230
+ TikTokBusinessSDK: [],
22231
+ nSure: [],
22232
+ Statsig: [],
22233
+ DatadogCore: [],
22234
+ DatadogLogs: ["DatadogCore"],
22235
+ DatadogRUM: ["DatadogCore"],
22236
+ DatadogTrace: ["DatadogCore"]
22237
+ };
22238
+ OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
22239
+ ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
22240
+ SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
22241
+ importsSpriteKit = (files) => Object.entries(files).some(
22242
+ ([file, contents]) => file.endsWith(".swift") && /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
22243
+ contents
22244
+ )
22245
+ );
22246
+ FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
22247
+ ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
22248
+ MULTI_MANIFEST_VERSION = 10;
22249
+ DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/;
22250
+ OS_IOS = /\bos\(\s*iOS\s*\)/g;
22251
+ OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/;
22252
+ SELECTOR = /^#selector\b/;
22253
+ TYPE_AFTER_ATTRIBUTE = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|@\w+(?:\([^()]*\))?|\b(?:public|open|final|internal|fileprivate|private|package|nonisolated|indirect)\b)*\b(?:class(?!\s+(?:func|var|let|subscript)\b)|struct|enum|protocol|extension|actor)\b/;
22254
+ DELEGATE_CLASS = /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/;
22255
+ REUSABLE_INIT = /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/;
22256
+ REUSABLE_VIEW_BASES = [
22257
+ "UICollectionReusableView",
22258
+ "UICollectionViewCell",
22259
+ "UICollectionViewListCell"
22260
+ ];
22261
+ CLASS_BASE = /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/;
22262
+ FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/;
22263
+ APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/;
22264
+ EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/;
22265
+ CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/;
22266
+ MODIFIERS = /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g;
22267
+ OVERRIDE_FUNC = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/;
22268
+ OVERRIDE_VAR = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/;
22269
+ compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
22270
+ ROOT_LOCKS = Symbol.for("peachsim.swiftCompile.rootLocks");
22271
+ host = globalThis;
22272
+ rootLocks = host[ROOT_LOCKS] ??= /* @__PURE__ */ new Map();
22273
+ }
22274
+ });
22275
+
22276
+ // ../contrast-runtime-delivery/src/product.ts
22277
+ function isValidRuntimeVersion(value) {
22278
+ return value.length <= 100 && /^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value);
22279
+ }
22280
+ function listInstalledRuntimes(product) {
22281
+ try {
22282
+ return import_node_fs8.default.readdirSync(product.runtimesDir(), { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(compareSemver);
22283
+ } catch {
22284
+ return [];
22285
+ }
22286
+ }
22287
+ function runtimeTarballCacheName(product, version) {
22288
+ return import_node_path8.default.posix.basename(product.tarballPath(version));
22289
+ }
22290
+ function compareSemver(a, b) {
22291
+ const parse2 = (v) => {
22292
+ const hyphen = v.indexOf("-");
22293
+ const core = hyphen >= 0 ? v.slice(0, hyphen) : v;
22294
+ const pre = hyphen >= 0 ? v.slice(hyphen + 1) : "";
22295
+ const parts = core.split(".").map((n) => Number.parseInt(n, 10));
22296
+ if (parts.some((n) => !Number.isFinite(n))) return [[Number.POSITIVE_INFINITY], v];
22297
+ return [parts, pre];
22298
+ };
22299
+ const [an, ap] = parse2(a);
22300
+ const [bn, bp] = parse2(b);
22301
+ for (let i = 0; i < Math.max(an.length, bn.length); i++) {
22302
+ const av = an[i] ?? 0;
22303
+ const bv = bn[i] ?? 0;
22304
+ if (av !== bv) return av - bv;
22305
+ }
22306
+ if (ap === bp) return 0;
22307
+ if (!ap) return 1;
22308
+ if (!bp) return -1;
22309
+ return ap < bp ? -1 : 1;
22280
22310
  }
22281
- function swiftSourceAsIOS(original) {
22282
- const source = liftExtensionOverrides(original);
22283
- const { lineStarts, tokens } = swiftCodeScan(source);
22284
- let offset = 0;
22285
- const conditioned = source.split("\n").map((line) => {
22286
- const start = offset;
22287
- offset += line.length + 1;
22288
- if (!lineStarts.has(start) || !DIRECTIVE.test(line)) return line;
22289
- return line.replace(OS_IOS, (match) => "true".padEnd(match.length));
22290
- }).join("\n");
22291
- let out = "";
22292
- let copied = 0;
22293
- const reusableViews = new Set(REUSABLE_VIEW_BASES);
22294
- const reusableBodies = [];
22295
- let depth = 0;
22296
- let opensReusableBody = false;
22297
- for (const at of tokens) {
22298
- const rest = conditioned.slice(at, at + 400);
22299
- if (rest.startsWith("{")) {
22300
- depth++;
22301
- if (opensReusableBody) reusableBodies.push(depth);
22302
- opensReusableBody = false;
22303
- continue;
22304
- }
22305
- if (rest.startsWith("}")) {
22306
- if (reusableBodies.at(-1) === depth) reusableBodies.pop();
22307
- depth--;
22308
- continue;
22311
+ var import_node_fs8, import_node_path8;
22312
+ var init_product = __esm({
22313
+ "../contrast-runtime-delivery/src/product.ts"() {
22314
+ "use strict";
22315
+ import_node_fs8 = __toESM(require("node:fs"), 1);
22316
+ import_node_path8 = __toESM(require("node:path"), 1);
22317
+ }
22318
+ });
22319
+
22320
+ // ../contrast-runtime-delivery/src/index.ts
22321
+ function createRuntimeDelivery(product) {
22322
+ function readConfig() {
22323
+ try {
22324
+ const parsed = JSON.parse(
22325
+ import_node_fs9.default.readFileSync(product.configFile(), "utf8")
22326
+ );
22327
+ return parsed && typeof parsed === "object" ? parsed : {};
22328
+ } catch {
22329
+ return {};
22309
22330
  }
22310
- if (rest.startsWith("override")) {
22311
- if (REUSABLE_INIT.test(rest) || reusableBodies.at(-1) === depth && FRAME_INIT.test(rest)) {
22312
- out += `${conditioned.slice(copied, at)}required`;
22313
- copied = at + "override".length;
22314
- }
22315
- continue;
22331
+ }
22332
+ function resolveCdnOrigin(input) {
22333
+ const config = readConfig();
22334
+ const value = input || process.env[product.env.cdnOrigin] || config.cdnOrigin || product.defaultCdnOrigin;
22335
+ return value.replace(/\/+$/, "");
22336
+ }
22337
+ function resolveChannel(input) {
22338
+ const config = readConfig();
22339
+ return input || process.env[product.env.channel] || config.runtimeChannel || "stable";
22340
+ }
22341
+ function resolvePin() {
22342
+ if (!product.env.pin) return null;
22343
+ const env = process.env[product.env.pin];
22344
+ if (env && env.trim()) return env.trim();
22345
+ const config = readConfig();
22346
+ return typeof config.runtimeVersion === "string" && config.runtimeVersion.trim() ? config.runtimeVersion.trim() : null;
22347
+ }
22348
+ function manifestUrl(cdnOrigin) {
22349
+ const url = new URL(`${resolveCdnOrigin(cdnOrigin)}${product.manifestPath}`);
22350
+ url.searchParams.set("t", String(Date.now()));
22351
+ return url.toString();
22352
+ }
22353
+ function tarballUrl(version, cdnOrigin) {
22354
+ return `${resolveCdnOrigin(cdnOrigin)}${product.tarballPath(version)}`;
22355
+ }
22356
+ const UP_TO_DATE_CHECK_TIMEOUT_MS = 2e3;
22357
+ async function fetchManifest(cdnOrigin, timeoutMs) {
22358
+ const url = manifestUrl(cdnOrigin);
22359
+ const res = await fetch(url, {
22360
+ headers: { Accept: "application/json" },
22361
+ // an install is allowed to wait; a best-effort check is not. see
22362
+ // UP_TO_DATE_CHECK_TIMEOUT_MS.
22363
+ ...timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {}
22364
+ });
22365
+ if (!res.ok) {
22366
+ throw new Error(`manifest fetch failed: ${res.status} ${res.statusText} (${url})`);
22316
22367
  }
22317
- const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest);
22318
- if (imported) {
22319
- out += conditioned.slice(copied, at) + "import CoreImage".padEnd(imported[0].length);
22320
- copied = at + imported[0].length;
22321
- continue;
22368
+ return await res.json();
22369
+ }
22370
+ function resolveVersion(manifest, opts = {}) {
22371
+ const channel = resolveChannel(opts.channel);
22372
+ const version = opts.version || resolvePin() || manifest.channels[channel]?.latest;
22373
+ if (!version) {
22374
+ throw new Error(
22375
+ `no version specified and channel '${channel}' has no latest entry in the manifest`
22376
+ );
22322
22377
  }
22323
- if (/^NSClassFromString\b/.test(rest)) {
22324
- out += conditioned.slice(copied, at) + "_peachClassFromString";
22325
- copied = at + "NSClassFromString".length;
22326
- continue;
22378
+ if (!isValidRuntimeVersion(version)) {
22379
+ throw new Error(`invalid runtime version: ${version}`);
22327
22380
  }
22328
- if (rest.startsWith("class")) {
22329
- const declared = CLASS_BASE.exec(rest);
22330
- if (declared && reusableViews.has(declared[2].split(".").pop())) {
22331
- reusableViews.add(declared[1]);
22332
- opensReusableBody = true;
22333
- }
22334
- const modifiers = conditioned.slice(conditioned.lastIndexOf("\n", at - 1) + 1, at);
22335
- if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
22336
- out += `${conditioned.slice(copied, at)}final `;
22337
- copied = at;
22338
- }
22339
- continue;
22381
+ const entry = manifest.versions[version];
22382
+ if (!entry) {
22383
+ throw new Error(
22384
+ `version ${version} not found in manifest; available: ${Object.keys(manifest.versions).slice(-10).join(", ") || "(none)"}`
22385
+ );
22340
22386
  }
22341
- const selector = SELECTOR.exec(rest);
22342
- const match = selector ?? OBJC_ATTRIBUTE.exec(rest);
22343
- if (!match) continue;
22344
- let replacement = "@ObjC";
22345
- if (selector) replacement = "#Selector";
22346
- else if (match[0] === "@objcMembers") replacement = "@ObjCMembers";
22347
- else if (match[0] === "@IBAction") replacement = "@ObjC".padEnd(match[0].length);
22348
- else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
22349
- replacement = " ".repeat(match[0].length);
22350
- else if (match[2] !== void 0)
22351
- replacement = `@ObjC${match[1]}("${match[2].trim()}")`;
22352
- out += conditioned.slice(copied, at) + replacement;
22353
- copied = at + match[0].length;
22387
+ return { version, channel, entry };
22354
22388
  }
22355
- return out + conditioned.slice(copied);
22356
- }
22357
- function swiftCodeScan(source) {
22358
- const starts = /* @__PURE__ */ new Set();
22359
- const tokens = [];
22360
- const stack = [{ kind: "code", parens: 0 }];
22361
- const hashesAt = (at) => {
22362
- let end = at;
22363
- while (source[end] === "#") end++;
22364
- return end - at;
22365
- };
22366
- const closes = (at, hashes) => source.startsWith("#".repeat(hashes), at);
22367
- let i = 0;
22368
- while (i < source.length) {
22369
- const top = stack[stack.length - 1];
22370
- if ((i === 0 || source[i - 1] === "\n") && top.kind === "code" && stack.length === 1)
22371
- starts.add(i);
22372
- const char = source[i];
22373
- if (top.kind === "block") {
22374
- if (source.startsWith("/*", i)) {
22375
- top.depth++;
22376
- i += 2;
22377
- } else if (source.startsWith("*/", i)) {
22378
- if (--top.depth === 0) stack.pop();
22379
- i += 2;
22380
- } else i++;
22381
- continue;
22389
+ async function install(opts = {}) {
22390
+ product.ensureHome();
22391
+ const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
22392
+ const manifest = await fetchManifest(cdnOrigin);
22393
+ const { version, channel, entry } = resolveVersion(manifest, opts);
22394
+ const destDir = product.runtimeDir(version);
22395
+ const setActive = opts.setActive !== false;
22396
+ const protectVersions = [version, ...opts.protectVersions ?? []];
22397
+ pruneLocalRetention({ protectVersions });
22398
+ if (!opts.force && import_node_fs9.default.existsSync(import_node_path9.default.join(destDir, product.installedMarker))) {
22399
+ if (setActive) product.writeActiveRuntime(version);
22400
+ pruneLocalRetention({ protectVersions });
22401
+ return {
22402
+ version,
22403
+ channel,
22404
+ cdnOrigin,
22405
+ runtimeDir: destDir,
22406
+ installed: false,
22407
+ activated: setActive,
22408
+ manifest
22409
+ };
22382
22410
  }
22383
- if (top.kind === "string") {
22384
- if (char === "\\" && closes(i + 1, top.hashes)) {
22385
- const after = i + 1 + top.hashes;
22386
- if (source[after] === "(") {
22387
- stack.push({ kind: "code", parens: 0 });
22388
- i = after + 1;
22389
- } else i = after + 1;
22390
- continue;
22411
+ if (!opts.quiet)
22412
+ process.stderr.write(`${product.id}: downloading runtime ${version}\u2026
22413
+ `);
22414
+ await installVerifiedTarball({
22415
+ url: entry.tarball || tarballUrl(version, cdnOrigin),
22416
+ digest: { algorithm: "sha256", encoding: "hex", value: entry.sha256 },
22417
+ destDir,
22418
+ installedMarker: product.installedMarker,
22419
+ label: `runtime ${version}`
22420
+ });
22421
+ if (setActive) product.writeActiveRuntime(version);
22422
+ pruneLocalRetention({ protectVersions });
22423
+ return {
22424
+ version,
22425
+ channel,
22426
+ cdnOrigin,
22427
+ runtimeDir: destDir,
22428
+ installed: true,
22429
+ activated: setActive,
22430
+ manifest
22431
+ };
22432
+ }
22433
+ async function updateToLatest(opts = {}) {
22434
+ product.ensureHome();
22435
+ pruneLocalRetention({ protectVersions: opts.protectVersions });
22436
+ const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
22437
+ const channel = resolveChannel(opts.channel);
22438
+ const pin = resolvePin();
22439
+ if (pin) {
22440
+ const activeVersion2 = product.readActiveRuntime();
22441
+ const pinInstalled = import_node_fs9.default.existsSync(
22442
+ import_node_path9.default.join(product.runtimeDir(pin), product.installedMarker)
22443
+ );
22444
+ if (activeVersion2 === pin && pinInstalled) {
22445
+ return {
22446
+ checked: true,
22447
+ updated: false,
22448
+ reason: `runtime is pinned to ${pin}`,
22449
+ activeVersion: activeVersion2,
22450
+ latestVersion: pin
22451
+ };
22391
22452
  }
22392
- const quote = top.multiline ? '"""' : '"';
22393
- if (source.startsWith(quote, i) && closes(i + quote.length, top.hashes)) {
22394
- stack.pop();
22395
- i += quote.length + top.hashes;
22396
- } else i++;
22397
- continue;
22453
+ const installed3 = await install({
22454
+ version: pin,
22455
+ channel,
22456
+ cdnOrigin,
22457
+ setActive: false,
22458
+ protectVersions: opts.protectVersions
22459
+ });
22460
+ return {
22461
+ checked: true,
22462
+ updated: true,
22463
+ reason: `runtime is pinned to ${pin}`,
22464
+ activeVersion: pin,
22465
+ latestVersion: pin,
22466
+ install: installed3
22467
+ };
22398
22468
  }
22399
- if (top.kind === "regex") {
22400
- if (char === "/" && closes(i + 1, top.hashes)) {
22401
- stack.pop();
22402
- i += 1 + top.hashes;
22403
- } else i++;
22404
- continue;
22469
+ const manifest = await fetchManifest(cdnOrigin);
22470
+ const latestVersion = manifest.channels[channel]?.latest;
22471
+ if (!latestVersion) {
22472
+ return {
22473
+ checked: true,
22474
+ updated: false,
22475
+ reason: `channel '${channel}' has no latest runtime`,
22476
+ activeVersion: product.readActiveRuntime()
22477
+ };
22405
22478
  }
22406
- if (source.startsWith("//", i)) {
22407
- const end = source.indexOf("\n", i);
22408
- i = end === -1 ? source.length : end;
22409
- } else if (source.startsWith("/*", i)) {
22410
- stack.push({ kind: "block", depth: 1 });
22411
- i += 2;
22412
- } else if (char === '"' || char === "#") {
22413
- const hashes = hashesAt(i);
22414
- const at = i + hashes;
22415
- if (source.startsWith('"""', at)) {
22416
- stack.push({ kind: "string", hashes, multiline: true });
22417
- i = at + 3;
22418
- } else if (source[at] === '"') {
22419
- stack.push({ kind: "string", hashes, multiline: false });
22420
- i = at + 1;
22421
- } else if (hashes > 0 && source[at] === "/") {
22422
- stack.push({ kind: "regex", hashes });
22423
- i = at + 1;
22424
- } else {
22425
- if (hashes > 0) tokens.push(at - 1);
22426
- i = Math.max(at, i + 1);
22427
- }
22428
- } else if (char === "{" || char === "}") {
22429
- tokens.push(i);
22430
- i++;
22431
- } else if (char === "(") {
22432
- top.parens++;
22433
- i++;
22434
- } else if (char === ")") {
22435
- if (top.parens === 0 && stack.length > 1) stack.pop();
22436
- else top.parens--;
22437
- i++;
22438
- } else {
22439
- const keyword = source.startsWith("class", i) ? "class" : source.startsWith("extension", i) ? "extension" : source.startsWith("override", i) ? "override" : source.startsWith("import", i) ? "import" : source.startsWith("NSClassFromString", i) ? "NSClassFromString" : null;
22440
- if (keyword && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
22441
- tokens.push(i);
22442
- i += keyword.length;
22443
- } else {
22444
- if (char === "@") tokens.push(i);
22445
- i++;
22446
- }
22479
+ const entry = manifest.versions[latestVersion];
22480
+ if (!entry) {
22481
+ return {
22482
+ checked: true,
22483
+ updated: false,
22484
+ reason: `manifest is missing version ${latestVersion}`,
22485
+ activeVersion: product.readActiveRuntime(),
22486
+ latestVersion
22487
+ };
22447
22488
  }
22448
- }
22449
- return { lineStarts: starts, tokens };
22450
- }
22451
- function writeSwiftProject(layout, input, moduleRoot) {
22452
- const distribution = swiftDistributionAt(moduleRoot);
22453
- const targets = distribution && compileTargets(input).length === 0 ? [
22454
- {
22455
- name: "App",
22456
- path: import_node_path9.default.relative(layout.root, layout.sources),
22457
- executable: true,
22458
- languageMode: 5,
22459
- mainActorIsolation: false,
22460
- resources: false
22489
+ const activeVersion = product.readActiveRuntime();
22490
+ const activeDir = activeVersion ? product.runtimeDir(activeVersion) : null;
22491
+ const activeInstalled = activeDir ? import_node_fs9.default.existsSync(import_node_path9.default.join(activeDir, product.installedMarker)) : false;
22492
+ const shouldInstall = !activeVersion || !activeInstalled || compareSemver(latestVersion, activeVersion) > 0;
22493
+ if (!shouldInstall) {
22494
+ return {
22495
+ checked: true,
22496
+ updated: false,
22497
+ reason: "active runtime is current",
22498
+ activeVersion,
22499
+ latestVersion
22500
+ };
22461
22501
  }
22462
- ] : compileTargets(input);
22463
- const files = /* @__PURE__ */ new Map();
22464
- const moduleFiles = `
22465
- // sootsim-swift files ${(0, import_node_crypto4.createHash)("sha256").update(swiftModuleInputFiles(moduleRoot).join("\n")).digest("hex").slice(0, 16)}
22466
- `;
22467
- if (targets.length === 0) {
22468
- for (const [file, contents] of Object.entries(input.files)) {
22469
- if (file === "Package.swift") continue;
22470
- files.set(import_node_path9.default.join(layout.sources, file), compiledSource(file, contents));
22502
+ const installed2 = await install({
22503
+ version: latestVersion,
22504
+ channel,
22505
+ cdnOrigin,
22506
+ setActive: false,
22507
+ protectVersions: opts.protectVersions
22508
+ });
22509
+ return {
22510
+ checked: true,
22511
+ updated: true,
22512
+ activeVersion: latestVersion,
22513
+ latestVersion,
22514
+ install: installed2
22515
+ };
22516
+ }
22517
+ async function checkUpToDate(opts = {}) {
22518
+ const active = product.readActiveRuntime();
22519
+ const pinned = resolvePin();
22520
+ if (pinned) {
22521
+ return { active, latest: pinned, pinned, outdated: active !== pinned };
22471
22522
  }
22472
- let manifest = (0, import_node_fs9.readFileSync)(
22473
- import_node_path9.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
22474
- "utf8"
22475
- ).replaceAll("__SOOTSIM_SWIFT_PACKAGE__", moduleRoot);
22476
- const optionalProducts = swiftTargetDependencies(input.files, [{ name: "App", path: "." }]).get("App") ?? [];
22477
- if (optionalProducts.length > 0) {
22478
- const product = '.product(name: "SwiftUI", package: "sootsim-swift"),';
22479
- if (!manifest.includes(product))
22480
- throw new Error("Swift app template lost its framework dependency anchor");
22481
- manifest = manifest.replace(
22482
- product,
22483
- [
22484
- product,
22485
- ...optionalProducts.map(
22486
- (name2) => `.product(name: "${name2}", package: "sootsim-swift"),`
22487
- )
22488
- ].join("\n ")
22523
+ try {
22524
+ const manifest = await fetchManifest(
22525
+ resolveCdnOrigin(opts.cdnOrigin),
22526
+ UP_TO_DATE_CHECK_TIMEOUT_MS
22489
22527
  );
22528
+ const channel = resolveChannel(opts.channel);
22529
+ const latest = manifest.channels[channel]?.latest ?? null;
22530
+ const outdated = !!(latest && (!active || compareSemver(latest, active) > 0));
22531
+ return { active, latest, pinned: null, outdated };
22532
+ } catch {
22533
+ return { active, latest: null, pinned: null, outdated: false };
22490
22534
  }
22491
- if (input.oneModule) {
22492
- const product = '.product(name: "CoreLocation", package: "sootsim-swift"),';
22493
- const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`;
22494
- if (!manifest.includes(product) || !manifest.includes(flags)) {
22495
- throw new Error(
22496
- "scripts/contrast-app-Package.swift lost the lines the One module links at"
22497
- );
22535
+ }
22536
+ function planLocalRetention(opts = {}) {
22537
+ product.ensureHome();
22538
+ const retainVersions = Math.max(
22539
+ 1,
22540
+ Math.floor(opts.retainVersions ?? DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT)
22541
+ );
22542
+ const installed2 = listInstalledRuntimes(product);
22543
+ const installedSet = new Set(installed2);
22544
+ const activeVersion = product.readActiveRuntime();
22545
+ const pinnedVersion = resolvePin();
22546
+ const keep = /* @__PURE__ */ new Set();
22547
+ for (const version of [
22548
+ activeVersion,
22549
+ pinnedVersion,
22550
+ ...opts.protectVersions ?? []
22551
+ ]) {
22552
+ if (version && installedSet.has(version)) keep.add(version);
22553
+ }
22554
+ for (const version of [...installed2].reverse()) {
22555
+ if (keep.size >= retainVersions) break;
22556
+ keep.add(version);
22557
+ }
22558
+ const cacheTemplateMarker = "__RUNTIME_VERSION__";
22559
+ const cacheTemplate = runtimeTarballCacheName(product, cacheTemplateMarker);
22560
+ const markerOffset = cacheTemplate.indexOf(cacheTemplateMarker);
22561
+ const cachePrefix = cacheTemplate.slice(0, markerOffset);
22562
+ const cacheSuffix = cacheTemplate.slice(markerOffset + cacheTemplateMarker.length);
22563
+ let removeCacheFiles = [];
22564
+ if (markerOffset >= 0) {
22565
+ try {
22566
+ removeCacheFiles = import_node_fs9.default.readdirSync(product.cacheDir(), { withFileTypes: true }).filter((entry) => {
22567
+ if (!entry.isFile()) return false;
22568
+ const complete = entry.name.startsWith(cachePrefix) && entry.name.endsWith(cacheSuffix);
22569
+ const partial = entry.name.startsWith(cachePrefix) && entry.name.endsWith(`${cacheSuffix}.partial`);
22570
+ return complete || partial;
22571
+ }).map((entry) => import_node_path9.default.join(product.cacheDir(), entry.name)).sort();
22572
+ } catch {
22498
22573
  }
22499
- manifest = manifest.replace(product, `${product}
22500
- ${ONE_PRODUCT},`).replace(flags, `${flags}${ONE_IMPLICIT_FLAGS}`);
22501
22574
  }
22502
- if (importsSpriteKit(input.files)) {
22503
- const anchor = '.product(name: "CoreLocation", package: "sootsim-swift"),';
22504
- if (!manifest.includes(anchor))
22505
- throw new Error(
22506
- "scripts/contrast-app-Package.swift lost the line the SpriteKit product links at"
22507
- );
22508
- manifest = manifest.replace(anchor, `${anchor}
22509
- ${SPRITEKIT_PRODUCT},`);
22575
+ return {
22576
+ activeVersion,
22577
+ pinnedVersion,
22578
+ keepVersions: installed2.filter((version) => keep.has(version)),
22579
+ removeVersions: installed2.filter((version) => !keep.has(version)),
22580
+ removeCacheFiles
22581
+ };
22582
+ }
22583
+ function pruneLocalRetention(opts = {}) {
22584
+ const plan = planLocalRetention(opts);
22585
+ for (const version of plan.removeVersions) {
22586
+ import_node_fs9.default.rmSync(product.runtimeDir(version), { recursive: true, force: true });
22510
22587
  }
22511
- files.set(import_node_path9.default.join(layout.root, "Package.swift"), manifest + moduleFiles);
22512
- } else {
22513
- const base = layout.multi ? layout.root : layout.sources;
22514
- for (const [file, contents] of Object.entries(input.files)) {
22515
- if (file === "Package.swift") continue;
22516
- files.set(import_node_path9.default.join(base, file), compiledSource(file, contents));
22588
+ for (const cacheFile of plan.removeCacheFiles) {
22589
+ import_node_fs9.default.rmSync(cacheFile, { force: true });
22517
22590
  }
22518
- for (const target of targets) {
22519
- if (!target.resources) continue;
22520
- files.set(
22521
- import_node_path9.default.join(layout.root, target.path, "ResourceBundleAccessor.generated.swift"),
22522
- [
22523
- "import Foundation",
22524
- "",
22525
- "extension Foundation.Bundle {",
22526
- " static let module: Bundle = Bundle.main",
22527
- "}",
22528
- ""
22529
- ].join("\n")
22591
+ return plan;
22592
+ }
22593
+ return {
22594
+ product,
22595
+ resolveCdnOrigin,
22596
+ resolveChannel,
22597
+ resolvePin,
22598
+ manifestUrl,
22599
+ tarballUrl,
22600
+ fetchManifest,
22601
+ resolveVersion,
22602
+ install,
22603
+ updateToLatest,
22604
+ checkUpToDate,
22605
+ planLocalRetention,
22606
+ pruneLocalRetention,
22607
+ listInstalled: () => listInstalledRuntimes(product)
22608
+ };
22609
+ }
22610
+ async function installVerifiedTarball(tarball) {
22611
+ const { url, digest, destDir, installedMarker, label } = tarball;
22612
+ const downloadDir = import_node_fs9.default.mkdtempSync(import_node_path9.default.join(import_node_os3.default.tmpdir(), "runtime-delivery-download-"));
22613
+ const archivePath = import_node_path9.default.join(downloadDir, "archive.tar.gz");
22614
+ import_node_fs9.default.mkdirSync(import_node_path9.default.dirname(destDir), { recursive: true });
22615
+ const tmpDir = import_node_fs9.default.mkdtempSync(
22616
+ import_node_path9.default.join(import_node_path9.default.dirname(destDir), `.installing-${import_node_path9.default.basename(destDir)}-`)
22617
+ );
22618
+ try {
22619
+ await downloadToFile(url, archivePath);
22620
+ const actual = await digestFile(archivePath, digest.algorithm, digest.encoding);
22621
+ if (actual !== digest.value) {
22622
+ throw new Error(
22623
+ `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
22530
22624
  );
22531
22625
  }
22532
- files.set(
22533
- import_node_path9.default.join(layout.root, "Package.swift"),
22534
- emitSwiftPackageManifest({
22535
- targets,
22536
- siblings: swiftTargetDependencies(
22537
- input.files,
22538
- layout.multi ? targets : targets.map((target) => ({ ...target, path: "." }))
22539
- ),
22540
- moduleRoot,
22541
- oneModule: input.oneModule,
22542
- spriteKit: importsSpriteKit(input.files),
22543
- distribution: distribution ?? void 0
22544
- }) + moduleFiles
22545
- );
22626
+ await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
22627
+ if (!import_node_fs9.default.existsSync(import_node_path9.default.join(tmpDir, installedMarker))) {
22628
+ throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
22629
+ }
22630
+ try {
22631
+ import_node_fs9.default.renameSync(tmpDir, destDir);
22632
+ } catch (err) {
22633
+ if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
22634
+ const aside = `${tmpDir}-replaced`;
22635
+ try {
22636
+ import_node_fs9.default.renameSync(destDir, aside);
22637
+ } catch (moveErr) {
22638
+ if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
22639
+ }
22640
+ try {
22641
+ import_node_fs9.default.renameSync(tmpDir, destDir);
22642
+ } catch (landErr) {
22643
+ if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs9.default.existsSync(import_node_path9.default.join(destDir, installedMarker))) {
22644
+ throw landErr;
22645
+ }
22646
+ } finally {
22647
+ import_node_fs9.default.rmSync(aside, { recursive: true, force: true });
22648
+ }
22649
+ }
22650
+ } finally {
22651
+ import_node_fs9.default.rmSync(tmpDir, { recursive: true, force: true });
22652
+ import_node_fs9.default.rmSync(downloadDir, { recursive: true, force: true });
22546
22653
  }
22547
- syncSwiftTree(layout.root, files);
22548
- }
22549
- function streamText(value) {
22550
- if (typeof value === "string") return value.trim();
22551
- if (Buffer.isBuffer(value)) return value.toString("utf8").trim();
22552
- return "";
22553
22654
  }
22554
- function outputOf(error) {
22555
- if (error && typeof error === "object") {
22556
- const streams = [
22557
- streamText(Reflect.get(error, "stdout")),
22558
- streamText(Reflect.get(error, "stderr"))
22559
- ].filter(Boolean);
22560
- if (streams.length > 0) return streams.join("\n");
22561
- }
22562
- return error instanceof Error ? error.message : String(error);
22655
+ function isErrnoCode(err, ...codes) {
22656
+ return err instanceof Error && "code" in err && codes.includes(String(err.code));
22563
22657
  }
22564
- function builtArtifact(layout) {
22565
- const binDir = import_node_path9.default.join(layout.root, ".build", WASM_TRIPLE, "release");
22566
- const manifest = (0, import_node_fs9.readFileSync)(import_node_path9.default.join(layout.root, "Package.swift"), "utf8");
22567
- const executable = swiftManifestTargets(manifest).find((target) => target.executable);
22568
- if (executable === void 0) {
22569
- throw new Error("swift-compile: the written manifest names no executable target");
22658
+ async function downloadToFile(url, destPath) {
22659
+ const res = await fetch(url);
22660
+ if (!res.ok || !res.body) {
22661
+ throw new Error(`download failed: ${res.status} ${res.statusText} (${url})`);
22570
22662
  }
22571
- const file = import_node_path9.default.join(binDir, `${executable.name}.wasm`);
22572
- if (!(0, import_node_fs9.existsSync)(file)) {
22573
- const found = (0, import_node_fs9.existsSync)(binDir) ? (0, import_node_fs9.readdirSync)(binDir).filter((name2) => name2.endsWith(".wasm")).sort() : [];
22574
- throw new Error(
22575
- `swift-compile: the build produced no ${executable.name}.wasm (found: ${found.join(", ") || "none"})`
22663
+ import_node_fs9.default.mkdirSync(import_node_path9.default.dirname(destPath), { recursive: true });
22664
+ const tmp = `${destPath}.partial`;
22665
+ try {
22666
+ await (0, import_promises3.pipeline)(
22667
+ import_node_stream.Readable.fromWeb(res.body),
22668
+ import_node_fs9.default.createWriteStream(tmp)
22576
22669
  );
22670
+ import_node_fs9.default.renameSync(tmp, destPath);
22671
+ } catch (err) {
22672
+ try {
22673
+ import_node_fs9.default.unlinkSync(tmp);
22674
+ } catch {
22675
+ }
22676
+ throw err;
22577
22677
  }
22578
- return file;
22579
- }
22580
- function projectDiagnostic(output, layout) {
22581
- const base = layout.multi ? layout.root : layout.sources;
22582
- const prefix = `${base}${import_node_path9.default.sep}`;
22583
- return output.split("\n").map((line) => line.startsWith(prefix) ? line.slice(prefix.length) : line).join("\n").trim();
22584
22678
  }
22585
- function serialize(root, work) {
22586
- const current = rootLocks.get(root) ?? Promise.resolve();
22587
- const next = current.then(work, work);
22588
- rootLocks.set(
22589
- root,
22590
- next.catch(() => {
22591
- })
22592
- );
22593
- return next;
22679
+ function digestFile(filePath, algorithm, encoding) {
22680
+ return new Promise((resolve10, reject) => {
22681
+ const hash = import_node_crypto4.default.createHash(algorithm);
22682
+ const stream = import_node_fs9.default.createReadStream(filePath);
22683
+ stream.on("data", (chunk) => hash.update(chunk));
22684
+ stream.on("error", reject);
22685
+ stream.on("end", () => resolve10(hash.digest(encoding)));
22686
+ });
22594
22687
  }
22595
- function compileSwiftProjectUnit(input, options) {
22596
- (0, import_node_fs9.mkdirSync)(options.buildRoot, { recursive: true });
22597
- const root = (0, import_node_fs9.realpathSync)(options.buildRoot);
22598
- const moduleRoot = import_node_path9.default.resolve(options.moduleRoot);
22599
- const layout = {
22600
- root,
22601
- sources: import_node_path9.default.join(root, "Sources", "App"),
22602
- multi: compileTargets(input).length > 0
22603
- };
22604
- const hash = swiftArtifactHash(input, options.release, moduleRoot);
22605
- return serialize(root, async () => {
22606
- writeSwiftProject(layout, input, moduleRoot);
22607
- const swift = import_node_path9.default.join(options.toolchainBin, "swift");
22608
- if (!(0, import_node_fs9.existsSync)(swift)) {
22609
- throw new Error(
22610
- `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`
22611
- );
22612
- }
22613
- const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin);
22614
- const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
22615
- const icu = swiftIcuAsset(options.toolchainBin, sdk);
22616
- try {
22617
- await run2(
22618
- swift,
22619
- [
22620
- "build",
22621
- "-j",
22622
- BUILD_JOBS,
22623
- "--package-path",
22624
- root,
22625
- "--swift-sdk",
22626
- sdk,
22627
- "-c",
22628
- "release",
22629
- "-Xswiftc",
22630
- "-Osize",
22631
- ...macroPlugins.flatMap((plugin) => [
22632
- "-Xswiftc",
22633
- "-load-plugin-library",
22634
- "-Xswiftc",
22635
- plugin
22636
- ])
22637
- ],
22638
- { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs }
22639
- );
22640
- } catch (error) {
22641
- throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error });
22642
- }
22643
- return {
22644
- hash,
22645
- bytes: (0, import_node_fs9.readFileSync)(builtArtifact(layout)),
22646
- icu: await icu
22647
- };
22688
+ function extractTarball(tarPath, destDir, stripComponents) {
22689
+ return new Promise((resolve10, reject) => {
22690
+ const args = ["-xzf", tarPath, "-C", destDir];
22691
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
22692
+ const child = (0, import_node_child_process5.spawn)("tar", args, {
22693
+ stdio: ["ignore", "inherit", "inherit"]
22694
+ });
22695
+ child.on("error", reject);
22696
+ child.on("exit", (code) => {
22697
+ if (code === 0) resolve10();
22698
+ else reject(new Error(`tar exited with code ${code}`));
22699
+ });
22648
22700
  });
22649
22701
  }
22650
- var import_node_child_process5, import_node_crypto4, import_node_fs9, import_node_os3, import_node_path9, import_node_util2, run2, WASM_TRIPLE, cores, BUILD_ENV, BUILD_JOBS, linkedModuleDigests, OPTIONAL_FRAMEWORK_DEPENDENCIES, OPTIONAL_FRAMEWORKS, ONE_PRODUCT, SPRITEKIT_PRODUCT, importsSpriteKit, FOUNDATION_IMPLICIT_FLAGS, ONE_IMPLICIT_FLAGS, MULTI_MANIFEST_VERSION, DIRECTIVE, OS_IOS, OBJC_ATTRIBUTE, SELECTOR, TYPE_AFTER_ATTRIBUTE, DELEGATE_CLASS, REUSABLE_INIT, REUSABLE_VIEW_BASES, CLASS_BASE, FRAME_INIT, APPLE_CLASS, EXTENSION_DECL, CLASS_DECL, MODIFIERS, OVERRIDE_FUNC, OVERRIDE_VAR, compiledSource, ROOT_LOCKS, host, rootLocks;
22651
- var init_swift_compile = __esm({
22652
- "src/swift-compile.ts"() {
22702
+ var import_node_child_process5, import_node_crypto4, import_node_fs9, import_node_os3, import_node_path9, import_node_stream, import_promises3, DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT;
22703
+ var init_src = __esm({
22704
+ "../contrast-runtime-delivery/src/index.ts"() {
22653
22705
  "use strict";
22654
22706
  import_node_child_process5 = require("node:child_process");
22655
- import_node_crypto4 = require("node:crypto");
22656
- import_node_fs9 = require("node:fs");
22707
+ import_node_crypto4 = __toESM(require("node:crypto"), 1);
22708
+ import_node_fs9 = __toESM(require("node:fs"), 1);
22657
22709
  import_node_os3 = __toESM(require("node:os"), 1);
22658
22710
  import_node_path9 = __toESM(require("node:path"), 1);
22659
- import_node_util2 = require("node:util");
22660
- init_swift_distribution_contract();
22661
- init_swift_icu();
22662
- init_swift_package();
22663
- run2 = (0, import_node_util2.promisify)(import_node_child_process5.execFile);
22664
- WASM_TRIPLE = "wasm32-unknown-wasip1";
22665
- cores = import_node_os3.default.availableParallelism();
22666
- BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) };
22667
- BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)));
22668
- linkedModuleDigests = /* @__PURE__ */ new Map();
22669
- OPTIONAL_FRAMEWORK_DEPENDENCIES = {
22670
- Accelerate: [],
22671
- CryptoKit: [],
22672
- Security: [],
22673
- TikTokBusinessSDK: [],
22674
- nSure: [],
22675
- Statsig: [],
22676
- DatadogCore: [],
22677
- DatadogLogs: ["DatadogCore"],
22678
- DatadogRUM: ["DatadogCore"],
22679
- DatadogTrace: ["DatadogCore"]
22680
- };
22681
- OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
22682
- ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
22683
- SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
22684
- importsSpriteKit = (files) => Object.entries(files).some(
22685
- ([file, contents]) => file.endsWith(".swift") && /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
22686
- contents
22687
- )
22688
- );
22689
- FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
22690
- ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
22691
- MULTI_MANIFEST_VERSION = 10;
22692
- DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/;
22693
- OS_IOS = /\bos\(\s*iOS\s*\)/g;
22694
- OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/;
22695
- SELECTOR = /^#selector\b/;
22696
- TYPE_AFTER_ATTRIBUTE = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|@\w+(?:\([^()]*\))?|\b(?:public|open|final|internal|fileprivate|private|package|nonisolated|indirect)\b)*\b(?:class(?!\s+(?:func|var|let|subscript)\b)|struct|enum|protocol|extension|actor)\b/;
22697
- DELEGATE_CLASS = /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/;
22698
- REUSABLE_INIT = /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/;
22699
- REUSABLE_VIEW_BASES = [
22700
- "UICollectionReusableView",
22701
- "UICollectionViewCell",
22702
- "UICollectionViewListCell"
22703
- ];
22704
- CLASS_BASE = /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/;
22705
- FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/;
22706
- APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/;
22707
- EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/;
22708
- CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/;
22709
- MODIFIERS = /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g;
22710
- OVERRIDE_FUNC = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/;
22711
- OVERRIDE_VAR = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/;
22712
- compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
22713
- ROOT_LOCKS = Symbol.for("peachsim.swiftCompile.rootLocks");
22714
- host = globalThis;
22715
- rootLocks = host[ROOT_LOCKS] ??= /* @__PURE__ */ new Map();
22711
+ import_node_stream = require("node:stream");
22712
+ import_promises3 = require("node:stream/promises");
22713
+ init_product();
22714
+ init_product();
22715
+ DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT = 2;
22716
22716
  }
22717
22717
  });
22718
22718
 
@@ -23546,7 +23546,7 @@ var init_swift_submit = __esm({
23546
23546
  MAX_SWIFT_COMPILE_IMAGES = 128;
23547
23547
  MAX_SWIFT_COMPILE_IMAGE_BYTES = 4 * 1024 * 1024;
23548
23548
  MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES = 16 * 1024 * 1024;
23549
- SWIFT_HOST_ABI = 15;
23549
+ SWIFT_HOST_ABI = 16;
23550
23550
  POLL_INTERVAL_MS = 1500;
23551
23551
  }
23552
23552
  });
@@ -24130,10 +24130,10 @@ async function collectExpoSwiftSources(appRoot) {
24130
24130
  const resolved = JSON.parse(resolvedText);
24131
24131
  const resolutions = resolved && typeof resolved === "object" ? Reflect.get(resolved, "modules") : null;
24132
24132
  if (!Array.isArray(resolutions)) throw new Error("invalid Expo Apple resolution");
24133
- const files = {};
24134
- const targets = [];
24135
- const classes = [];
24133
+ const units = [];
24134
+ const namespacesSeen = /* @__PURE__ */ new Set();
24136
24135
  let bytes = 0;
24136
+ let fileCount = 0;
24137
24137
  for (const entry of Object.values(search)) {
24138
24138
  if (!entry || typeof entry !== "object")
24139
24139
  throw new Error("invalid Expo autolinking entry");
@@ -24153,9 +24153,11 @@ async function collectExpoSwiftSources(appRoot) {
24153
24153
  `${sourceRoot}: local Expo Swift modules need one Apple Swift module`
24154
24154
  );
24155
24155
  const namespace = namespaces[0];
24156
- if (targets.includes(namespace))
24156
+ if (namespacesSeen.has(namespace))
24157
24157
  throw new Error(`duplicate local Expo Swift module ${namespace}`);
24158
- targets.push(namespace);
24158
+ namespacesSeen.add(namespace);
24159
+ const files = {};
24160
+ const classes = [];
24159
24161
  for (const module2 of modules) {
24160
24162
  const className = module2 && typeof module2 === "object" ? Reflect.get(module2, "class") : null;
24161
24163
  const name2 = module2 && typeof module2 === "object" ? Reflect.get(module2, "name") : null;
@@ -24180,25 +24182,61 @@ async function collectExpoSwiftSources(appRoot) {
24180
24182
  if (!child.name.endsWith(".swift")) continue;
24181
24183
  const size = import_node_fs14.default.statSync(file).size;
24182
24184
  bytes += size;
24183
- if (Object.keys(files).length + 1 > MAX_SWIFT_COMPILE_FILES - 2 || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES)
24185
+ fileCount++;
24186
+ if (fileCount > MAX_SWIFT_COMPILE_FILES - 2 || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES)
24184
24187
  throw new Error("Expo Swift sources exceed compile service caps");
24185
24188
  files[`Sources/${namespace}/${import_node_path14.default.relative(ios, file).split(import_node_path14.default.sep).join("/")}`] = `#sourceLocation(file: ${JSON.stringify(file)}, line: 1)
24186
24189
  ${import_node_fs14.default.readFileSync(file, "utf8")}`;
24187
24190
  }
24188
24191
  };
24189
24192
  walk(ios);
24190
- }
24191
- if (classes.length === 0) return null;
24192
- files["Package.swift"] = `// swift-tools-version: 6.0
24193
+ const unit = { namespace, classes, files };
24194
+ files[EXPO_SWIFT_ENTRY] = expoEntry([unit]);
24195
+ units.push(unit);
24196
+ }
24197
+ if (units.length === 0) return null;
24198
+ const allFiles = Object.assign(
24199
+ {},
24200
+ ...units.map((unit) => unit.files)
24201
+ );
24202
+ const targets = units.map((unit) => ({
24203
+ name: unit.namespace,
24204
+ path: `Sources/${unit.namespace}`
24205
+ }));
24206
+ const dependencies = swiftTargetDependencies(allFiles, targets);
24207
+ const byNamespace = new Map(units.map((unit) => [unit.namespace, unit]));
24208
+ for (const unit of units) {
24209
+ const included = /* @__PURE__ */ new Set([unit.namespace]);
24210
+ const visit = (namespace) => {
24211
+ for (const dependency of dependencies.get(namespace) ?? []) {
24212
+ if (!byNamespace.has(dependency) || included.has(dependency)) continue;
24213
+ included.add(dependency);
24214
+ visit(dependency);
24215
+ }
24216
+ };
24217
+ visit(unit.namespace);
24218
+ for (const namespace of included) {
24219
+ if (namespace === unit.namespace) continue;
24220
+ const dependency = byNamespace.get(namespace);
24221
+ if (!dependency) throw new Error(`missing local Swift namespace ${namespace}`);
24222
+ for (const [name2, source] of Object.entries(allFiles)) {
24223
+ if (name2.startsWith(`Sources/${namespace}/`)) unit.files[name2] = source;
24224
+ }
24225
+ }
24226
+ unit.files["Package.swift"] = `// swift-tools-version: 6.0
24193
24227
  import PackageDescription
24194
- let package = Package(name: "PeachExpo", targets: [${targets.map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
24228
+ let package = Package(name: "PeachExpo", targets: [${[...included].map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
24195
24229
  `;
24196
- files[EXPO_SWIFT_ENTRY] = `import SwiftUI
24230
+ }
24231
+ return units;
24232
+ }
24233
+ function expoEntry(units) {
24234
+ return `import SwiftUI
24197
24235
  import ExpoModulesCore
24198
- ${targets.map((name2) => `import ${name2}
24199
- `).join("")}
24236
+ ${units.map((unit) => `import ${unit.namespace}`).join("\n")}
24237
+
24200
24238
  @main struct PeachExpoApp: RNXPackage {
24201
- init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${classes.join(", ")}]) } }
24239
+ init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${units.flatMap((unit) => unit.classes).join(", ")}]) } }
24202
24240
  func view(props: JSON) -> PeachExpoNativeView { PeachExpoNativeView(props: props) }
24203
24241
  }
24204
24242
 
@@ -24208,7 +24246,6 @@ ${targets.map((name2) => `import ${name2}
24208
24246
  PeachExpoRuntime.dispatch(payload, length)
24209
24247
  }
24210
24248
  `;
24211
- return files;
24212
24249
  }
24213
24250
  async function handleExpoSwiftRequest(req, res) {
24214
24251
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -24241,34 +24278,118 @@ async function handleExpoSwiftRequest(req, res) {
24241
24278
  let pending = compiling.get(root);
24242
24279
  if (!pending) {
24243
24280
  pending = (async () => {
24244
- const files = await collectExpoSwiftSources(root);
24245
- if (!files) return null;
24281
+ const units = await collectExpoSwiftSources(root);
24282
+ if (!units) return null;
24246
24283
  const module2 = await resolveSwiftModule();
24247
- if (!module2) return null;
24284
+ const result = {
24285
+ namespaces: units.map((unit) => unit.namespace),
24286
+ modules: [],
24287
+ failures: []
24288
+ };
24248
24289
  const key = (0, import_node_crypto6.createHash)("sha256").update(import_node_fs14.default.realpathSync(root)).digest("hex");
24249
- const packagePath = import_node_path14.default.join(import_node_os6.default.tmpdir(), "peach-expo-swift", key);
24250
- const sources = import_node_path14.default.join(packagePath, "Sources");
24251
- import_node_fs14.default.rmSync(sources, { recursive: true, force: true });
24252
- import_node_fs14.default.mkdirSync(sources, { recursive: true });
24253
- for (const [name2, content] of Object.entries(files)) {
24254
- const target = import_node_path14.default.join(packagePath, name2);
24255
- import_node_fs14.default.mkdirSync(import_node_path14.default.dirname(target), { recursive: true });
24256
- import_node_fs14.default.writeFileSync(target, content);
24257
- }
24258
- const artifact = await artifactFor(
24259
- projectFor(packagePath),
24260
- EXPO_SWIFT_ENTRY,
24261
- module2.root
24262
- );
24263
24290
  const host2 = req.headers.host;
24264
24291
  if (!host2) throw new Error("Expo Swift request has no host");
24265
24292
  const base = `http://${host2}`;
24266
- return {
24267
- url: `${base}/__peach/swift/${artifact.hash}.wasm`,
24268
- hash: artifact.hash,
24269
- icuUrl: icuUrl(base, artifact),
24270
- rootId: `${key}/Expo`
24271
- };
24293
+ const linked = [];
24294
+ for (const unit of units) {
24295
+ if (!module2) {
24296
+ result.failures.push({
24297
+ namespace: unit.namespace,
24298
+ diagnostic: "No local Swift toolchain or distribution is available"
24299
+ });
24300
+ continue;
24301
+ }
24302
+ try {
24303
+ const packagePath = import_node_path14.default.join(
24304
+ import_node_os6.default.tmpdir(),
24305
+ "peach-expo-swift",
24306
+ key,
24307
+ unit.namespace
24308
+ );
24309
+ syncSwiftTree(
24310
+ packagePath,
24311
+ new Map(
24312
+ Object.entries(unit.files).map(([name2, source]) => [
24313
+ import_node_path14.default.join(packagePath, name2),
24314
+ source
24315
+ ])
24316
+ )
24317
+ );
24318
+ const stamp = sourceStamp(packagePath, module2.root);
24319
+ const failed = failedCompilations.get(packagePath);
24320
+ if (failed?.stamp === stamp) {
24321
+ result.failures.push({
24322
+ namespace: unit.namespace,
24323
+ diagnostic: failed.diagnostic
24324
+ });
24325
+ continue;
24326
+ }
24327
+ failedCompilations.delete(packagePath);
24328
+ await artifactFor(
24329
+ projectFor(packagePath),
24330
+ EXPO_SWIFT_ENTRY,
24331
+ module2.root
24332
+ ).catch((error) => {
24333
+ const diagnostic = error instanceof Error ? error.message : String(error);
24334
+ if (/^.+:\d+(?::\d+)?: error:/m.test(diagnostic) && sourceStamp(packagePath, module2.root) === stamp)
24335
+ failedCompilations.set(packagePath, { stamp, diagnostic });
24336
+ throw error;
24337
+ });
24338
+ linked.push(unit);
24339
+ } catch (error) {
24340
+ result.failures.push({
24341
+ namespace: unit.namespace,
24342
+ diagnostic: error instanceof Error ? error.message : String(error)
24343
+ });
24344
+ }
24345
+ }
24346
+ if (module2 && linked.length) {
24347
+ const files = Object.assign(
24348
+ {},
24349
+ ...linked.map((unit) => unit.files)
24350
+ );
24351
+ files[EXPO_SWIFT_ENTRY] = expoEntry(linked);
24352
+ const targets = [
24353
+ ...new Set(
24354
+ Object.keys(files).flatMap((name2) => {
24355
+ const match = /^Sources\/([^/]+)\//.exec(name2);
24356
+ return match && match[1] !== "PeachExpoApp" ? [match[1]] : [];
24357
+ })
24358
+ )
24359
+ ];
24360
+ files["Package.swift"] = `// swift-tools-version: 6.0
24361
+ import PackageDescription
24362
+ let package = Package(name: "PeachExpo", targets: [${targets.map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
24363
+ `;
24364
+ const packagePath = import_node_path14.default.join(
24365
+ import_node_os6.default.tmpdir(),
24366
+ "peach-expo-swift",
24367
+ key,
24368
+ "linked-app"
24369
+ );
24370
+ syncSwiftTree(
24371
+ packagePath,
24372
+ new Map(
24373
+ Object.entries(files).map(([name2, source]) => [
24374
+ import_node_path14.default.join(packagePath, name2),
24375
+ source
24376
+ ])
24377
+ )
24378
+ );
24379
+ const artifact = await artifactFor(
24380
+ projectFor(packagePath),
24381
+ EXPO_SWIFT_ENTRY,
24382
+ module2.root
24383
+ );
24384
+ result.modules.push({
24385
+ namespaces: linked.map((unit) => unit.namespace),
24386
+ url: `${base}/__peach/swift/${artifact.hash}.wasm`,
24387
+ hash: artifact.hash,
24388
+ icuUrl: icuUrl(base, artifact),
24389
+ rootId: `${key}/Expo`
24390
+ });
24391
+ }
24392
+ return result;
24272
24393
  })();
24273
24394
  compiling.set(root, pending);
24274
24395
  }
@@ -24286,7 +24407,7 @@ async function handleExpoSwiftRequest(req, res) {
24286
24407
  }
24287
24408
  return true;
24288
24409
  }
24289
- var import_node_child_process7, import_node_crypto6, import_node_fs14, import_node_module, import_node_os6, import_node_path14, import_node_util3, run3, scriptEnv, EXPO_SWIFT_ROUTE, EXPO_SWIFT_ENTRY, compiling;
24410
+ var import_node_child_process7, import_node_crypto6, import_node_fs14, import_node_module, import_node_os6, import_node_path14, import_node_util3, run3, scriptEnv, EXPO_SWIFT_ROUTE, EXPO_SWIFT_ENTRY, compiling, failedCompilations;
24290
24411
  var init_expo_swift_host = __esm({
24291
24412
  "src/expo-swift-host.ts"() {
24292
24413
  "use strict";
@@ -24299,6 +24420,7 @@ var init_expo_swift_host = __esm({
24299
24420
  import_node_util3 = require("node:util");
24300
24421
  init_internal_child();
24301
24422
  init_backend_origin();
24423
+ init_swift_compile();
24302
24424
  init_swift_distribution();
24303
24425
  init_swift_host();
24304
24426
  init_swift_submit();
@@ -24307,6 +24429,7 @@ var init_expo_swift_host = __esm({
24307
24429
  EXPO_SWIFT_ROUTE = "/__peach/expo-swift";
24308
24430
  EXPO_SWIFT_ENTRY = "Sources/PeachExpoApp/PeachExpoEntry.swift";
24309
24431
  compiling = /* @__PURE__ */ new Map();
24432
+ failedCompilations = /* @__PURE__ */ new Map();
24310
24433
  }
24311
24434
  });
24312
24435