peachsim 0.1.2633 → 0.1.2634

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 (130) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +1027 -900
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-G52HY6SM.mjs → acorn-E7YS7T7M.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-JXGUFZNW.mjs → chunk-2SB3P7CJ.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-IYR6EA7F.mjs → chunk-2VYVW3RF.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-6QNPQ4SG.mjs → chunk-4SRXXXOC.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-GOOWNGNO.mjs → chunk-6EG4II5F.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-AF22LKX3.mjs → chunk-6YZJ2GYO.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-QG5X4QGH.mjs → chunk-CXDXPI7W.mjs} +5 -5
  33. package/dist-lib/esm-chunks/{chunk-YX3KDBUQ.mjs → chunk-ERQZXSHP.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-JXAUTMVF.mjs → chunk-H223T2KC.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-UIWCC5CL.mjs → chunk-N2XQ3OUI.mjs} +2 -2
  36. package/dist-lib/esm-chunks/{chunk-RMO7B3V3.mjs → chunk-NPVYXBWM.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-F3YEDOHY.mjs → chunk-P4JHWOEI.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-QNJWVYGV.mjs → chunk-PCY75YWE.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-YGGDE6F4.mjs → chunk-PXOH2HF6.mjs} +4 -4
  40. package/dist-lib/esm-chunks/{chunk-53O5O5G3.mjs → chunk-RN4YJUYM.mjs} +6 -6
  41. package/dist-lib/esm-chunks/{chunk-2HONUZR5.mjs → chunk-S4CJUCCF.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-5G5JC3BO.mjs → chunk-TPIVMDXH.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-FMPZXHCH.mjs → chunk-VPM63Q6Z.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-RDKGAR7Q.mjs → chunk-WH5NWS6Z.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-OOH2FHFR.mjs → chunk-WWO6KGXH.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-RK7OADCF.mjs → chunk-X2TVSD4W.mjs} +42 -32
  47. package/dist-lib/esm-chunks/{chunk-QRIQ2Z7A.mjs → chunk-X726CWSL.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-GFBC7EHF.mjs → chunk-XOL6DFMM.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-RFOIAO3R.mjs → chunk-Y4EG7XXB.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{chunk-XIIMFZNV.mjs → chunk-YLD4VKUR.mjs} +6 -6
  51. package/dist-lib/esm-chunks/{metro-layout-parser-PQYC5COZ.mjs → metro-layout-parser-I7JGQQV2.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-5XWQHVOU.mjs → swift-package-prebuilt-CXXM7OME.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-ICX3VS5Z.mjs → swift-sdk-app-module-XKY52BHH.mjs} +16 -16
  54. package/dist-lib/esm-chunks/{swift-sdk-image-KI37XSBI.mjs → swift-sdk-image-EUTGX6FL.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-G5HVINR2.mjs → swift-sdk-image-producer-JVAFRRME.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +31 -21
  57. package/dist-lib/expo-swift-metadata.cjs +1 -1
  58. package/dist-lib/expo-swift-metadata.mjs +7 -7
  59. package/dist-lib/home-paths.cjs +1 -1
  60. package/dist-lib/host/bridge-host.cjs +7575 -7354
  61. package/dist-lib/host/fetch-proxy-handler.cjs +3 -3
  62. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  63. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  64. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  65. package/dist-lib/host/websocket-proxy.cjs +1 -1
  66. package/dist-lib/index.cjs +1 -1
  67. package/dist-lib/kotlin-host.cjs +1 -1
  68. package/dist-lib/menu.cjs +1 -1
  69. package/dist-lib/menu.mjs +3 -3
  70. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  71. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  72. package/dist-lib/metro-production-bundle.cjs +1 -1
  73. package/dist-lib/metro-production-bundle.mjs +4 -4
  74. package/dist-lib/native-app-identity-project.cjs +1 -1
  75. package/dist-lib/native-app-identity-project.mjs +15 -15
  76. package/dist-lib/native-app-identity.cjs +1 -1
  77. package/dist-lib/native-app-identity.mjs +6 -6
  78. package/dist-lib/native-firebase-metadata.cjs +1 -1
  79. package/dist-lib/native-firebase-metadata.mjs +3 -3
  80. package/dist-lib/pdfium-raster.cjs +1 -1
  81. package/dist-lib/pdfium-raster.mjs +2 -2
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +3 -3
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +85 -85
  87. package/dist-lib/public-origins-lib.json +89 -82
  88. package/dist-lib/react-native-host-modules.cjs +1 -1
  89. package/dist-lib/react-native-host-modules.mjs +2 -2
  90. package/dist-lib/reap-browser.cjs +1 -1
  91. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  92. package/dist-lib/sdk.cjs +1 -1
  93. package/dist-lib/sdk.mjs +8 -8
  94. package/dist-lib/skills.cjs +8181 -7950
  95. package/dist-lib/swift-compile.cjs +29 -19
  96. package/dist-lib/swift-compile.mjs +12 -12
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +3 -3
  99. package/dist-lib/swift-submit.cjs +1 -1
  100. package/dist-lib/swift-submit.mjs +6 -6
  101. package/dist-lib/swift-svg-raster.cjs +1 -1
  102. package/dist-lib/swift-svg-raster.mjs +2 -2
  103. package/dist-lib/swift-toolchain.cjs +1 -1
  104. package/dist-lib/swift.cjs +1 -1
  105. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/magic-string.cjs +1 -1
  110. package/dist-lib/vendor/stream-json.cjs +1 -1
  111. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase.cjs +1 -1
  116. package/dist-lib/vendor/terser.cjs +1 -1
  117. package/dist-lib/vendor/valibot.cjs +1 -1
  118. package/dist-lib/vendor/ws.cjs +1 -1
  119. package/dist-lib/vendor/zod.cjs +1 -1
  120. package/dist-lib/worklet-executable.cjs +1 -1
  121. package/dist-lib/worklet-executable.mjs +3 -3
  122. package/dist-types/packages/peach-engine/src/engine/native-node-queries.d.ts +1 -0
  123. package/package.json +1 -1
  124. package/src/host/bridge-host.ts +42 -20
  125. package/src/native-package-slice-build.ts +44 -31
  126. package/src/one-native-controls-package.ts +80 -14
  127. package/src/one-native-controls-release.ts +69 -0
  128. package/src/one-sdk/shard.ts +382 -0
  129. package/src/one-sdk-bundle.ts +4 -208
  130. package/src/swift-compile.ts +44 -19
@@ -1,11 +1,16 @@
1
1
  // builds the Peach Swift package that compiles One v3's unchanged SwiftUI
2
2
  // controls against Peach's Swift SDK and exposes them through PeachTypedViews.
3
- import { createHash } from 'node:crypto'
3
+ import { createHash, randomUUID } from 'node:crypto'
4
4
  import fs from 'node:fs'
5
5
  import { createRequire } from 'node:module'
6
6
  import path from 'node:path'
7
7
  import { fileURLToPath } from 'node:url'
8
8
  import { swiftGuestControls } from '../../peach-globals/build/one-swift-control-source'
9
+ import {
10
+ shardOneSDKBindingSource,
11
+ translateShardedOneSDKDiagnostic,
12
+ type ShardedBindingFile,
13
+ } from './one-sdk/shard'
9
14
  import { oneSDKHost, oneSDKModule, oneSDKTransport } from './one-sdk/source'
10
15
  import {
11
16
  ONE_NATIVE_CONTROLS_CONTAINER_VIEWS,
@@ -17,7 +22,9 @@ import {
17
22
  ONE_NATIVE_CONTROLS_VISUAL_VIEWS,
18
23
  } from './oneNativeControlsContract'
19
24
  import { swiftCodeMask, syncSwiftTree } from './swift-compile'
25
+ import { swiftDistributionRoot } from './swift-distribution'
20
26
  import { projectFor, swiftPackageMetadata, swiftPackageReleaseFiles } from './swift-host'
27
+ import { swiftModuleDigest } from './swift-sdk-surface'
21
28
  import { collectSwiftSourceClosure } from './swift-source-closure'
22
29
  import { SWIFT_PACKAGE_PATH } from './swift-submit'
23
30
  import { privateSwiftDistributionRoot, swiftCacheDir } from './swift-toolchain'
@@ -1133,6 +1140,28 @@ export interface OneNativeControlsPackage {
1133
1140
  packagePath: string
1134
1141
  watched: string[]
1135
1142
  oneSDKModules?: string[]
1143
+ oneSDKShards?: ReadonlyMap<string, ShardedBindingFile>
1144
+ }
1145
+
1146
+ function cachedWasiBindings(file: string, base: ReadonlyMap<string, string>) {
1147
+ let record: unknown
1148
+ try {
1149
+ record = JSON.parse(fs.readFileSync(file, 'utf8'))
1150
+ } catch (error) {
1151
+ if (
1152
+ error instanceof SyntaxError ||
1153
+ (error instanceof Error && 'code' in error && error.code === 'ENOENT')
1154
+ )
1155
+ return
1156
+ throw error
1157
+ }
1158
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return
1159
+ const files = new Map(base)
1160
+ for (const [name, source] of Object.entries(record)) {
1161
+ if (!base.has(name) || typeof source !== 'string') return
1162
+ files.set(name, source)
1163
+ }
1164
+ return files
1136
1165
  }
1137
1166
 
1138
1167
  function excludedGroupSource(source: string, defines: ReadonlySet<string>): boolean {
@@ -1236,6 +1265,7 @@ export async function oneNativeControlsPackage(
1236
1265
  if (full) watched.add(full)
1237
1266
  }
1238
1267
 
1268
+ const oneSDKShards = new Map<string, ShardedBindingFile>()
1239
1269
  if (bindings) {
1240
1270
  files.set('Sources/One/One.swift', oneSDKModule)
1241
1271
  for (const relative of ONE_SDK_RUNTIME_SOURCES) {
@@ -1246,10 +1276,14 @@ export async function oneNativeControlsPackage(
1246
1276
  for (const [name, content] of [...bindings.files].sort(([a], [b]) =>
1247
1277
  a.localeCompare(b),
1248
1278
  )) {
1249
- const relative = 'Sources/OneSDKBindings/' + path.basename(name)
1250
- if (files.has(relative))
1251
- throw new Error('duplicate Swift filename in OneSDKBindings: ' + relative)
1252
- files.set(relative, content)
1279
+ const baseName = path.basename(name)
1280
+ for (const shard of shardOneSDKBindingSource(baseName, content)) {
1281
+ const relative = 'Sources/OneSDKBindings/' + shard.name
1282
+ if (files.has(relative))
1283
+ throw new Error('duplicate Swift filename in OneSDKBindings: ' + relative)
1284
+ files.set(relative, shard.source)
1285
+ if (shard.name !== shard.originalName) oneSDKShards.set(shard.name, shard)
1286
+ }
1253
1287
  }
1254
1288
  files.set('Sources/Controls/OneSDKHost.swift', oneSDKHost)
1255
1289
  files.set('Sources/Controls/OneSDKTransport.swift', oneSDKTransport)
@@ -1314,6 +1348,7 @@ export async function oneNativeControlsPackage(
1314
1348
  packagePath,
1315
1349
  watched: [...watched],
1316
1350
  oneSDKModules: bindings && [...bindings.modules],
1351
+ ...(oneSDKShards.size ? { oneSDKShards } : {}),
1317
1352
  }
1318
1353
  }
1319
1354
 
@@ -1331,15 +1366,32 @@ export async function stageOneNativeControlsRelease(
1331
1366
  files: Map<string, Blob>
1332
1367
  oneSDKModules?: string[]
1333
1368
  }> {
1334
- const moduleRoot = options?.moduleRoot ?? defaultSwiftModuleRoot()
1335
- let sdk = options?.sdk
1369
+ const original = options?.sdk
1370
+ const moduleRoot =
1371
+ options?.moduleRoot ??
1372
+ defaultSwiftModuleRoot() ??
1373
+ (original?.reemitForWasi ? await swiftDistributionRoot() : undefined)
1374
+ let sdk = original
1375
+ let prepared = await oneNativeControlsPackage(appRoot, linkedGroups, sdk)
1376
+ let receipt: string | undefined
1377
+ let restored = false
1378
+ if (sdk?.reemitForWasi && moduleRoot) {
1379
+ // the package digest covers the full binding and control sources and flags.
1380
+ const target = swiftModuleDigest(moduleRoot).toString('hex')
1381
+ receipt = path.join(
1382
+ path.dirname(prepared.packagePath),
1383
+ `wasi-bindings-${target}.json`,
1384
+ )
1385
+ const cached = cachedWasiBindings(receipt, sdk.files)
1386
+ if (cached) {
1387
+ sdk = { ...sdk, files: cached }
1388
+ prepared = await oneNativeControlsPackage(appRoot, linkedGroups, sdk)
1389
+ restored = true
1390
+ }
1391
+ }
1336
1392
  const compile = async () => {
1337
1393
  for (;;) {
1338
- const { packagePath, oneSDKModules } = await oneNativeControlsPackage(
1339
- appRoot,
1340
- linkedGroups,
1341
- sdk,
1342
- )
1394
+ const { packagePath, oneSDKModules, oneSDKShards } = prepared
1343
1395
  if (oneSDKModules?.length)
1344
1396
  projectFor(fs.realpathSync(packagePath)).oneModule = false
1345
1397
  try {
@@ -1355,10 +1407,12 @@ export async function stageOneNativeControlsRelease(
1355
1407
  )
1356
1408
  return { packagePath, oneSDKModules, metadata }
1357
1409
  } catch (error) {
1358
- if (!sdk?.reemitForWasi || !(error instanceof Error)) throw error
1359
- const files = await sdk.reemitForWasi(error.message)
1410
+ if (restored || !sdk?.reemitForWasi || !(error instanceof Error)) throw error
1411
+ const diagnostic = translateShardedOneSDKDiagnostic(error.message, oneSDKShards)
1412
+ const files = await sdk.reemitForWasi(diagnostic)
1360
1413
  if (!files) throw error
1361
1414
  sdk = { ...sdk, files }
1415
+ prepared = await oneNativeControlsPackage(appRoot, linkedGroups, sdk)
1362
1416
  }
1363
1417
  }
1364
1418
  }
@@ -1369,5 +1423,17 @@ export async function stageOneNativeControlsRelease(
1369
1423
  ONE_NATIVE_CONTROLS_PACKAGE,
1370
1424
  metadata,
1371
1425
  )
1426
+ if (receipt && original && sdk && sdk !== original && !restored) {
1427
+ const revised = Object.fromEntries(
1428
+ [...sdk.files].filter(([name, source]) => original.files.get(name) !== source),
1429
+ )
1430
+ const partial = `${receipt}.${process.pid}.${randomUUID()}.tmp`
1431
+ try {
1432
+ fs.writeFileSync(partial, JSON.stringify(revised))
1433
+ fs.renameSync(partial, receipt)
1434
+ } finally {
1435
+ fs.rmSync(partial, { force: true })
1436
+ }
1437
+ }
1372
1438
  return { metadataPath, metadata, files, oneSDKModules }
1373
1439
  }
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { installVerifiedTarball } from '@contrast/runtime-delivery'
4
+ import {
5
+ ONE_NATIVE_CONTROLS_RELEASE_PIN,
6
+ ONE_NATIVE_CONTROLS_STAGED_BUNDLE,
7
+ oneNativeControlsReleaseObject,
8
+ parseOneNativeControlsReleasePin,
9
+ } from '../../peach-globals/src/oneNativeControlsReleaseContract'
10
+ import { cacheDir } from './home-paths'
11
+ import { NATIVE_PREBUILT_ORIGIN } from './native-prebuilt'
12
+ import { ONE_NATIVE_CONTROLS_PACKAGE } from './oneNativeControlsContract'
13
+ import {
14
+ resolveRuntimeFilePath,
15
+ runtimeFileHeaders,
16
+ sendFileWithRanges,
17
+ } from './runtime-assets'
18
+ import { SWIFT_PACKAGE_PATH } from './swift-submit'
19
+ import type { IncomingMessage, ServerResponse } from 'node:http'
20
+
21
+ export const ONE_NATIVE_CONTROLS_METADATA_PATH = `${SWIFT_PACKAGE_PATH}${ONE_NATIVE_CONTROLS_PACKAGE}`
22
+
23
+ const PACKAGE_PREFIX = '/__peach/'
24
+ const METADATA_FILE = ONE_NATIVE_CONTROLS_METADATA_PATH.slice(PACKAGE_PREFIX.length)
25
+ const RELEASE_ASSET = /^\/__peach\/swift(?:-(?:icu|res|sdk|sdk-bindings))?\//
26
+ const installing = new Map<string, Promise<void>>()
27
+
28
+ export function isOneNativeControlsReleaseAsset(pathname: string): boolean {
29
+ return RELEASE_ASSET.test(pathname)
30
+ }
31
+
32
+ export async function serveOneNativeControlsRelease(
33
+ req: IncomingMessage,
34
+ res: ServerResponse,
35
+ pathname: string,
36
+ runtime: string,
37
+ ): Promise<boolean> {
38
+ const pin = path.join(runtime, ONE_NATIVE_CONTROLS_RELEASE_PIN)
39
+ if (!fs.existsSync(pin)) return false
40
+ const sha256 = parseOneNativeControlsReleasePin(fs.readFileSync(pin, 'utf8'), pin)
41
+ const destDir = path.join(cacheDir(), 'one-native-controls', sha256)
42
+ const metadata = pathname === ONE_NATIVE_CONTROLS_METADATA_PATH
43
+ if (metadata && !fs.existsSync(path.join(destDir, METADATA_FILE))) {
44
+ let pending = installing.get(sha256)
45
+ if (!pending) {
46
+ const staged = path.join(runtime, ONE_NATIVE_CONTROLS_STAGED_BUNDLE)
47
+ pending = installVerifiedTarball({
48
+ url: `${NATIVE_PREBUILT_ORIGIN}/${oneNativeControlsReleaseObject(sha256)}`,
49
+ localPath: fs.existsSync(staged) ? staged : undefined,
50
+ digest: { algorithm: 'sha256', encoding: 'hex', value: sha256 },
51
+ destDir,
52
+ installedMarker: METADATA_FILE,
53
+ label: ONE_NATIVE_CONTROLS_PACKAGE,
54
+ }).finally(() => installing.delete(sha256))
55
+ installing.set(sha256, pending)
56
+ }
57
+ await pending
58
+ }
59
+ const file = resolveRuntimeFilePath(destDir, pathname.slice(PACKAGE_PREFIX.length - 1))
60
+ if (!file) return false
61
+ const stat = fs.statSync(file)
62
+ sendFileWithRanges(req, res, file, stat.size, {
63
+ ...runtimeFileHeaders(file, req.url ?? '', stat.mtime.toUTCString()),
64
+ 'access-control-allow-origin': '*',
65
+ 'cache-control': metadata ? 'no-store' : 'public, max-age=31536000, immutable',
66
+ ...(metadata ? { 'content-type': 'application/json' } : {}),
67
+ })
68
+ return true
69
+ }
@@ -0,0 +1,382 @@
1
+ import { createHash } from 'node:crypto'
2
+ import path from 'node:path'
3
+ import { swiftCodeMask } from '../swift-compile'
4
+
5
+ export const ONE_SDK_BINDING_SHARDS = 8
6
+ export const ONE_SDK_BINDING_SHARD_MIN_BYTES = 256 * 1024
7
+
8
+ interface SourceLine {
9
+ text: string
10
+ line: number
11
+ }
12
+
13
+ type BindingChunk =
14
+ | { kind: 'enumDecl'; enumName: string; lines: SourceLine[] }
15
+ | { kind: 'top'; key: string; lines: SourceLine[] }
16
+ | { kind: 'enumMember'; enumName: string; key: string; lines: SourceLine[] }
17
+
18
+ export interface ShardedBindingFile {
19
+ name: string
20
+ source: string
21
+ originalName: string
22
+ // 1-based original source line for each 0-based line in `source` (0 for synthetic lines)
23
+ lineMap: number[]
24
+ }
25
+
26
+ function unsharded(name: string, source: string): ShardedBindingFile[] {
27
+ const lineCount = source.split('\n').length
28
+ return [
29
+ {
30
+ name,
31
+ source,
32
+ originalName: name,
33
+ lineMap: Array.from({ length: lineCount }, (_, index) => index + 1),
34
+ },
35
+ ]
36
+ }
37
+
38
+ function chunkKey(lines: readonly SourceLine[]): string {
39
+ for (const { text } of lines) {
40
+ const trimmed = text.trim()
41
+ if (trimmed !== '' && !trimmed.startsWith('//')) return trimmed
42
+ }
43
+ return lines.map((item) => item.text).join('\n')
44
+ }
45
+
46
+ function stableShardIndex(key: string, shardCount: number): number {
47
+ return createHash('sha256').update(key).digest().readUInt32BE(0) % shardCount
48
+ }
49
+
50
+ // split large generated binding files across compilation units so swiftc can
51
+ // compile OneSDKBindings in parallel under -no-whole-module-optimization and
52
+ // incremental rebuilds recompile only changed shards.
53
+ export function shardOneSDKBindingSource(
54
+ name: string,
55
+ source: string,
56
+ shardCount = ONE_SDK_BINDING_SHARDS,
57
+ ): ShardedBindingFile[] {
58
+ if (
59
+ shardCount <= 1 ||
60
+ !name.endsWith('.swift') ||
61
+ name.endsWith('.types.swift') ||
62
+ source.length < ONE_SDK_BINDING_SHARD_MIN_BYTES
63
+ ) {
64
+ return unsharded(name, source)
65
+ }
66
+ const masked = swiftCodeMask(source)
67
+ if (/\bfileprivate\b/.test(masked)) return unsharded(name, source)
68
+ const lines = source.split('\n')
69
+ const maskedLines = masked.split('\n')
70
+ if (lines.length !== maskedLines.length) return unsharded(name, source)
71
+
72
+ const headerLines: SourceLine[] = []
73
+ let index = 0
74
+ let headerIfDepth = 0
75
+ while (index < lines.length) {
76
+ const text = lines[index]!
77
+ const trimmed = text.trim()
78
+ if (
79
+ trimmed === '' ||
80
+ trimmed.startsWith('// generated ') ||
81
+ trimmed.startsWith('import ')
82
+ ) {
83
+ headerLines.push({ text, line: index + 1 })
84
+ index++
85
+ continue
86
+ }
87
+ if (trimmed.startsWith('#if ')) {
88
+ headerIfDepth++
89
+ headerLines.push({ text, line: index + 1 })
90
+ index++
91
+ continue
92
+ }
93
+ if (
94
+ headerIfDepth > 0 &&
95
+ (trimmed.startsWith('#elseif ') || trimmed === '#else' || trimmed === '#endif')
96
+ ) {
97
+ if (trimmed === '#endif') headerIfDepth--
98
+ headerLines.push({ text, line: index + 1 })
99
+ index++
100
+ continue
101
+ }
102
+ break
103
+ }
104
+ if (headerIfDepth !== 0) return unsharded(name, source)
105
+ while (headerLines.length > 0 && headerLines.at(-1)!.text.trim() === '') {
106
+ headerLines.pop()
107
+ }
108
+
109
+ const chunks: BindingChunk[] = []
110
+ let depth = 0
111
+ let pending: SourceLine[] = []
112
+ let hadBrace = false
113
+ let inImplementation = false
114
+ let inOpen = false
115
+ let openDeclarations = 0
116
+ let activeEnum: string | null = null
117
+ let enumDeclLine = 0
118
+ let memberLines: SourceLine[] = []
119
+ let memberHadBrace = false
120
+
121
+ for (; index < lines.length; index++) {
122
+ const text = lines[index]!
123
+ const lineNo = index + 1
124
+ const maskedLine = maskedLines[index]!
125
+ if (depth <= 1 && /^\s*#/.test(maskedLine)) return unsharded(name, source)
126
+ let delta = 0
127
+ for (let i = 0; i < maskedLine.length; i++) {
128
+ const ch = maskedLine[i]
129
+ if (ch === '{') delta++
130
+ else if (ch === '}') delta--
131
+ }
132
+ if (activeEnum === null) {
133
+ if (
134
+ depth === 0 &&
135
+ !hadBrace &&
136
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*private\b/.test(maskedLine)
137
+ ) {
138
+ return unsharded(name, source)
139
+ }
140
+ if (
141
+ depth === 0 &&
142
+ !hadBrace &&
143
+ !inImplementation &&
144
+ text.startsWith('// implementation ')
145
+ ) {
146
+ inImplementation = true
147
+ pending.push({ text, line: lineNo })
148
+ continue
149
+ }
150
+ if (inImplementation) {
151
+ pending.push({ text, line: lineNo })
152
+ depth += delta
153
+ if (depth < 0) return unsharded(name, source)
154
+ if (depth === 0 && text === '// end implementation') {
155
+ chunks.push({ kind: 'top', key: chunkKey(pending), lines: pending })
156
+ pending = []
157
+ hadBrace = false
158
+ inImplementation = false
159
+ }
160
+ continue
161
+ }
162
+ if (depth === 0 && !hadBrace && !inOpen && text.startsWith('// open ')) {
163
+ inOpen = true
164
+ openDeclarations = 0
165
+ pending.push({ text, line: lineNo })
166
+ continue
167
+ }
168
+ if (inOpen) {
169
+ pending.push({ text, line: lineNo })
170
+ if (delta !== 0 || depth > 0) hadBrace = true
171
+ depth += delta
172
+ if (depth < 0) return unsharded(name, source)
173
+ if (hadBrace && depth === 0) {
174
+ openDeclarations++
175
+ hadBrace = false
176
+ // each `// open` block emits a protocol followed by its conforming extension
177
+ if (openDeclarations === 2) {
178
+ chunks.push({ kind: 'top', key: chunkKey(pending), lines: pending })
179
+ pending = []
180
+ inOpen = false
181
+ openDeclarations = 0
182
+ }
183
+ }
184
+ continue
185
+ }
186
+ const enumMatch =
187
+ depth === 0 &&
188
+ !hadBrace &&
189
+ pending.every(
190
+ (item) => item.text.trim() === '' || item.text.trim().startsWith('//'),
191
+ )
192
+ ? /^enum (OneSDK_\w+)\s*\{\s*$/.exec(maskedLine)
193
+ : null
194
+ if (enumMatch && delta === 1) {
195
+ const enumName = enumMatch[1]!
196
+ const prefix = pending.filter((item) => item.text.trim() !== '')
197
+ enumDeclLine = lineNo
198
+ chunks.push({
199
+ kind: 'enumDecl',
200
+ enumName,
201
+ lines: [...prefix, { text: `enum ${enumName} {}`, line: lineNo }],
202
+ })
203
+ pending = []
204
+ activeEnum = enumName
205
+ depth = 1
206
+ continue
207
+ }
208
+ if (depth === 0 && !hadBrace && text.trim() === '' && pending.length === 0) {
209
+ continue
210
+ }
211
+ pending.push({ text, line: lineNo })
212
+ if (delta !== 0 || depth > 0) hadBrace = true
213
+ depth += delta
214
+ if (depth < 0) return unsharded(name, source)
215
+ if (hadBrace && depth === 0) {
216
+ chunks.push({ kind: 'top', key: chunkKey(pending), lines: pending })
217
+ pending = []
218
+ hadBrace = false
219
+ }
220
+ } else {
221
+ const nextDepth = depth + delta
222
+ if (nextDepth < 0) return unsharded(name, source)
223
+ if (depth === 1 && nextDepth === 0) {
224
+ if (memberHadBrace || maskedLine.trim() !== '}') return unsharded(name, source)
225
+ if (
226
+ memberLines.some(
227
+ (item) => item.text.trim() !== '' && !item.text.trim().startsWith('//'),
228
+ )
229
+ ) {
230
+ chunks.push({
231
+ kind: 'enumMember',
232
+ enumName: activeEnum,
233
+ key: chunkKey(memberLines),
234
+ lines: memberLines,
235
+ })
236
+ }
237
+ activeEnum = null
238
+ depth = 0
239
+ memberLines = []
240
+ continue
241
+ }
242
+ if (
243
+ depth === 1 &&
244
+ !memberHadBrace &&
245
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*private\b/.test(maskedLine)
246
+ ) {
247
+ return unsharded(name, source)
248
+ }
249
+ if (depth === 1 && !memberHadBrace && text.trim() === '') {
250
+ depth = nextDepth
251
+ continue
252
+ }
253
+ memberLines.push({ text, line: lineNo })
254
+ if (nextDepth > 1 || delta !== 0) memberHadBrace = true
255
+ depth = nextDepth
256
+ if (
257
+ (memberHadBrace && depth === 1) ||
258
+ (!memberHadBrace &&
259
+ depth === 1 &&
260
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*static\s+let\b/.test(maskedLine))
261
+ ) {
262
+ chunks.push({
263
+ kind: 'enumMember',
264
+ enumName: activeEnum,
265
+ key: chunkKey(memberLines),
266
+ lines: memberLines,
267
+ })
268
+ memberLines = []
269
+ memberHadBrace = false
270
+ }
271
+ }
272
+ }
273
+
274
+ if (
275
+ depth !== 0 ||
276
+ activeEnum !== null ||
277
+ inImplementation ||
278
+ inOpen ||
279
+ pending.some(
280
+ (item) => item.text.trim() !== '' && !item.text.trim().startsWith('//'),
281
+ ) ||
282
+ chunks.length < shardCount
283
+ ) {
284
+ return unsharded(name, source)
285
+ }
286
+
287
+ const buckets: BindingChunk[][] = Array.from({ length: shardCount }, () => [])
288
+ for (const chunk of chunks) {
289
+ if (chunk.kind === 'enumDecl') {
290
+ buckets[0]!.push(chunk)
291
+ } else {
292
+ buckets[stableShardIndex(chunk.key, shardCount)]!.push(chunk)
293
+ }
294
+ }
295
+ const nonEmpty = buckets
296
+ .map((bucket, index) => ({ bucket, index }))
297
+ .filter(({ bucket }) => bucket.length > 0)
298
+ if (nonEmpty.length < 2) return unsharded(name, source)
299
+
300
+ const stem = name.slice(0, -'.swift'.length)
301
+ return nonEmpty.map(({ bucket, index: shardIndex }) => {
302
+ const outLines: string[] = []
303
+ const lineMap: number[] = []
304
+ const pushLine = (text: string, origLine: number) => {
305
+ outLines.push(text)
306
+ lineMap.push(origLine)
307
+ }
308
+ for (const item of headerLines) pushLine(item.text, item.line)
309
+ pushLine('', 0)
310
+
311
+ let openEnum: string | null = null
312
+ let enumBody: SourceLine[][] = []
313
+ let hasPart = false
314
+ const startPart = () => {
315
+ if (hasPart) pushLine('', 0)
316
+ hasPart = true
317
+ }
318
+ const flushEnum = () => {
319
+ if (!openEnum) return
320
+ startPart()
321
+ pushLine(`extension ${openEnum} {`, enumDeclLine)
322
+ for (let i = 0; i < enumBody.length; i++) {
323
+ if (i > 0) pushLine('', 0)
324
+ for (const item of enumBody[i]!) pushLine(item.text, item.line)
325
+ }
326
+ pushLine('}', enumDeclLine)
327
+ openEnum = null
328
+ enumBody = []
329
+ }
330
+ for (const chunk of bucket) {
331
+ if (chunk.kind === 'enumMember') {
332
+ if (openEnum !== chunk.enumName) {
333
+ flushEnum()
334
+ openEnum = chunk.enumName
335
+ }
336
+ enumBody.push(chunk.lines)
337
+ } else {
338
+ flushEnum()
339
+ startPart()
340
+ for (const item of chunk.lines) pushLine(item.text, item.line)
341
+ }
342
+ }
343
+ flushEnum()
344
+ pushLine('', 0)
345
+ return {
346
+ name: `${stem}_${shardIndex}.swift`,
347
+ source: outLines.join('\n'),
348
+ originalName: name,
349
+ lineMap,
350
+ }
351
+ })
352
+ }
353
+
354
+ // maps sharded OneSDKBindings diagnostics (swiftc line errors and wasm-ld
355
+ // object filenames) back to the unsharded source filename and line numbers so
356
+ // sdk-generator's reemitForWasi matches entries against its unsharded output.
357
+ export function translateShardedOneSDKDiagnostic(
358
+ diagnostic: string,
359
+ shards: ReadonlyMap<string, ShardedBindingFile> | undefined,
360
+ ): string {
361
+ if (!shards?.size) return diagnostic
362
+ return diagnostic
363
+ .split('\n')
364
+ .map((line) => {
365
+ const source = /^(.*?)([^/:\s]+_\d+\.swift):(\d+):(\d+)(:.*)$/.exec(line)
366
+ if (source) {
367
+ const shard = shards.get(source[2]!)
368
+ if (shard) {
369
+ const lineNumber = Number(source[3])
370
+ const originalLine = shard.lineMap[lineNumber - 1]
371
+ if (!originalLine) return ''
372
+ const originalBase = path.posix.basename(shard.originalName)
373
+ return `${source[1]}${originalBase}:${originalLine}:${source[4]}${source[5]}`
374
+ }
375
+ }
376
+ return line.replace(/([^/:\s]+_\d+\.swift)\.o\b/g, (full, file: string) => {
377
+ const shard = shards.get(file)
378
+ return shard ? `${path.posix.basename(shard.originalName)}.o` : full
379
+ })
380
+ })
381
+ .join('\n')
382
+ }