peachsim 0.1.800 → 0.1.809

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 (82) hide show
  1. package/cli/drivers/playwright-sim-host.ts +2 -0
  2. package/cli/outbound-endpoints.ts +0 -4
  3. package/dist-lib/agent-daemon-client.cjs +1 -1
  4. package/dist-lib/agent-events.cjs +1 -1
  5. package/dist-lib/agent-identity.cjs +1 -1
  6. package/dist-lib/agent-sessions.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +132 -10
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cli-constants.cjs +1 -1
  21. package/dist-lib/cloud-contract.cjs +1 -1
  22. package/dist-lib/cloud-contract.mjs +1 -1
  23. package/dist-lib/cloud-test-args.cjs +1 -1
  24. package/dist-lib/cloud-test-args.mjs +1 -1
  25. package/dist-lib/cloud.cjs +1 -1
  26. package/dist-lib/cloud.mjs +1 -1
  27. package/dist-lib/config.cjs +1 -1
  28. package/dist-lib/detox/index.cjs +46 -7
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +132 -10
  31. package/dist-lib/expo-swift-metadata.cjs +1 -1
  32. package/dist-lib/expo-swift-metadata.mjs +1 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +252 -108
  35. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +1 -1
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +1 -1
  51. package/dist-lib/native-app-identity.cjs +1 -1
  52. package/dist-lib/native-app-identity.mjs +1 -1
  53. package/dist-lib/native-firebase-metadata.cjs +1 -1
  54. package/dist-lib/native-firebase-metadata.mjs +1 -1
  55. package/dist-lib/plist.cjs +1 -1
  56. package/dist-lib/plist.mjs +1 -1
  57. package/dist-lib/profiles.cjs +1 -1
  58. package/dist-lib/public-brand.cjs +1 -1
  59. package/dist-lib/react-native-host-modules.cjs +1 -1
  60. package/dist-lib/react-native-host-modules.mjs +1 -1
  61. package/dist-lib/render-mode.cjs +1 -1
  62. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  63. package/dist-lib/sdk.cjs +1 -1
  64. package/dist-lib/sdk.mjs +1 -1
  65. package/dist-lib/skills.cjs +252 -108
  66. package/dist-lib/swift-compile.cjs +141 -11
  67. package/dist-lib/swift-compile.mjs +140 -11
  68. package/dist-lib/swift-package.cjs +1 -1
  69. package/dist-lib/swift-package.mjs +1 -1
  70. package/dist-lib/swift-submit.cjs +1 -1
  71. package/dist-lib/swift-submit.mjs +1 -1
  72. package/dist-lib/swift-toolchain.cjs +1 -1
  73. package/dist-lib/swift.cjs +1 -1
  74. package/dist-lib/vite-swift.cjs +132 -10
  75. package/dist-lib/vite.cjs +1 -1
  76. package/dist-lib/worklet-executable.cjs +119 -0
  77. package/dist-lib/worklet-executable.mjs +93 -0
  78. package/package.json +9 -1
  79. package/src/swift-compile.ts +160 -11
  80. package/src/vite-plugin.ts +5 -2
  81. package/src/worklet-executable.ts +125 -0
  82. package/src/worklets-babel.ts +47 -6
@@ -582,6 +582,7 @@ export function swiftArtifactHash(
582
582
  moduleRoot: string,
583
583
  ): string {
584
584
  const hash = createHash('sha256')
585
+ // v20: supplied table editing and swipe methods preserve objective-c selectors
585
586
  // v18: NSValue(time:) constructs NSStructBox through NSValue.boxedTime
586
587
  // v17: AVAsset(url:) constructs AVURLAsset for the class cluster
587
588
  // v16: overrides of @objc extension members rename to __peach_ovr_
@@ -597,7 +598,7 @@ export function swiftArtifactHash(
597
598
  // v6: app and scene delegate classes compile final
598
599
  // (v5: a target declaring resources gets SwiftPM's Bundle.module accessor;
599
600
  // v4: sources compile through swiftSourceAsIOS)
600
- hash.update(`swift-compile/v18\n${release}\n`)
601
+ hash.update(`swift-compile/v20\n${release}\n`)
601
602
  if (input.oneModule) hash.update('one-module\n')
602
603
  hash.update(swiftModuleDigest(moduleRoot))
603
604
  for (const file of Object.keys(input.files).sort()) {
@@ -1419,6 +1420,141 @@ export function lowerNotificationDelegate(source: string): string {
1419
1420
  return result
1420
1421
  }
1421
1422
 
1423
+ // uikit's Objective-C table requirements expose only supplied methods. index
1424
+ // the module first: a conformance, subclass or extension may live in another file.
1425
+ export function tableProtocolConformances(sources: string[]): Map<string, Set<string>> {
1426
+ const parents = new Map<string, Set<string>>()
1427
+ for (const source of sources) {
1428
+ const code = swiftCodeMask(source)
1429
+ for (const owner of code.matchAll(
1430
+ /\b(?:class|extension)\s+([A-Za-z_]\w*)\s*:\s*([^{}]+)\{/g,
1431
+ )) {
1432
+ const inherited = parents.get(owner[1]!) ?? new Set<string>()
1433
+ for (const type of owner[2]!.matchAll(/\b[A-Za-z_]\w*\b/g)) inherited.add(type[0])
1434
+ parents.set(owner[1]!, inherited)
1435
+ }
1436
+ }
1437
+ const result = new Map<string, Set<string>>()
1438
+ const protocols = ['UITableViewDataSource', 'UITableViewDelegate']
1439
+ for (const type of parents.keys()) {
1440
+ const pending = [type]
1441
+ const seen = new Set<string>()
1442
+ const conformances = new Set<string>()
1443
+ while (pending.length) {
1444
+ const next = pending.pop()!
1445
+ if (seen.has(next)) continue
1446
+ seen.add(next)
1447
+ if (protocols.includes(next)) conformances.add(next)
1448
+ for (const parent of parents.get(next) ?? []) pending.push(parent)
1449
+ }
1450
+ if (conformances.size) result.set(type, conformances)
1451
+ }
1452
+ return result
1453
+ }
1454
+
1455
+ function lowerTableProtocolMethods(
1456
+ source: string,
1457
+ conformances: Map<string, Set<string>>,
1458
+ ): string {
1459
+ const code = swiftCodeMask(source)
1460
+ const dataSource: Record<string, string> = {
1461
+ numberOfRowsInSection: 'tableView:numberOfRowsInSection:',
1462
+ cellForRowAt: 'tableView:cellForRowAtIndexPath:',
1463
+ titleForHeaderInSection: 'tableView:titleForHeaderInSection:',
1464
+ titleForFooterInSection: 'tableView:titleForFooterInSection:',
1465
+ canEditRowAt: 'tableView:canEditRowAtIndexPath:',
1466
+ commit: 'tableView:commitEditingStyle:forRowAtIndexPath:',
1467
+ }
1468
+ const delegate: Record<string, string> = {
1469
+ willDisplay: 'tableView:willDisplayCell:forRowAtIndexPath:',
1470
+ didEndDisplaying: 'tableView:didEndDisplayingCell:forRowAtIndexPath:',
1471
+ heightForRowAt: 'tableView:heightForRowAtIndexPath:',
1472
+ estimatedHeightForRowAt: 'tableView:estimatedHeightForRowAtIndexPath:',
1473
+ heightForHeaderInSection: 'tableView:heightForHeaderInSection:',
1474
+ heightForFooterInSection: 'tableView:heightForFooterInSection:',
1475
+ estimatedHeightForHeaderInSection: 'tableView:estimatedHeightForHeaderInSection:',
1476
+ estimatedHeightForFooterInSection: 'tableView:estimatedHeightForFooterInSection:',
1477
+ viewForHeaderInSection: 'tableView:viewForHeaderInSection:',
1478
+ viewForFooterInSection: 'tableView:viewForFooterInSection:',
1479
+ willDisplayHeaderView: 'tableView:willDisplayHeaderView:forSection:',
1480
+ willDisplayFooterView: 'tableView:willDisplayFooterView:forSection:',
1481
+ didEndDisplayingHeaderView: 'tableView:didEndDisplayingHeaderView:forSection:',
1482
+ didEndDisplayingFooterView: 'tableView:didEndDisplayingFooterView:forSection:',
1483
+ shouldHighlightRowAt: 'tableView:shouldHighlightRowAtIndexPath:',
1484
+ didHighlightRowAt: 'tableView:didHighlightRowAtIndexPath:',
1485
+ didUnhighlightRowAt: 'tableView:didUnhighlightRowAtIndexPath:',
1486
+ willSelectRowAt: 'tableView:willSelectRowAtIndexPath:',
1487
+ willDeselectRowAt: 'tableView:willDeselectRowAtIndexPath:',
1488
+ didSelectRowAt: 'tableView:didSelectRowAtIndexPath:',
1489
+ didDeselectRowAt: 'tableView:didDeselectRowAtIndexPath:',
1490
+ accessoryButtonTappedForRowWith:
1491
+ 'tableView:accessoryButtonTappedForRowWithIndexPath:',
1492
+ editingStyleForRowAt: 'tableView:editingStyleForRowAtIndexPath:',
1493
+ leadingSwipeActionsConfigurationForRowAt:
1494
+ 'tableView:leadingSwipeActionsConfigurationForRowAtIndexPath:',
1495
+ trailingSwipeActionsConfigurationForRowAt:
1496
+ 'tableView:trailingSwipeActionsConfigurationForRowAtIndexPath:',
1497
+ willBeginEditingRowAt: 'tableView:willBeginEditingRowAtIndexPath:',
1498
+ didEndEditingRowAt: 'tableView:didEndEditingRowAtIndexPath:',
1499
+ }
1500
+ const braces = [...code.matchAll(/[{}]/g)].map((match) => match.index)
1501
+ const edits: [number, string][] = []
1502
+ for (const owner of code.matchAll(/\b(?:class|extension)\s+([A-Za-z_]\w*)[^{}]*\{/g)) {
1503
+ const conforms = conformances.get(owner[1]!)
1504
+ if (!conforms) continue
1505
+ const selectors = {
1506
+ ...(conforms.has('UITableViewDataSource') ? dataSource : {}),
1507
+ ...(conforms.has('UITableViewDelegate') ? delegate : {}),
1508
+ }
1509
+ const open = owner.index + owner[0].length - 1
1510
+ const close = closingBrace(code, braces, open)
1511
+ let depth = 1
1512
+ let previous = open + 1
1513
+ for (const token of swiftCodeScan(code.slice(open + 1, close - 1)).tokens) {
1514
+ const at = open + 1 + token
1515
+ if (code[at] === '{') depth++
1516
+ else if (code[at] === '}') {
1517
+ depth--
1518
+ if (depth === 1) previous = at + 1
1519
+ } else if (depth === 1 && /^func\b/.test(code.slice(at))) {
1520
+ const signature = code.slice(at, code.indexOf('{', at))
1521
+ const prefix = code.slice(previous, at)
1522
+ const attributes =
1523
+ /(?:@\w+(?:\([^{}]*\))?\s*|(?:public|open|private|fileprivate|internal|final|override|static|class|nonisolated|dynamic)\s+)*$/.exec(
1524
+ prefix,
1525
+ )?.[0] ?? ''
1526
+ // an override dispatches through its superclass's method record.
1527
+ if (/\b(?:override|static|class)\b|@(?:objc|ObjC|IBAction)\b/.test(attributes))
1528
+ continue
1529
+ let selector: string | undefined
1530
+ if (
1531
+ conforms.has('UITableViewDataSource') &&
1532
+ /^func\s+numberOfSections\s*\(\s*in\s+\w+\s*:\s*(?:UIKit\.)?UITableView\s*\)/.test(
1533
+ signature,
1534
+ )
1535
+ )
1536
+ selector = 'numberOfSectionsInTableView:'
1537
+ else {
1538
+ const match =
1539
+ /^func\s+tableView\s*\(\s*_\s+\w+\s*:\s*(?:UIKit\.)?UITableView\s*,\s*(\w+)\b/.exec(
1540
+ signature,
1541
+ )
1542
+ if (match) selector = selectors[match[1]!]
1543
+ }
1544
+ if (selector)
1545
+ edits.push([
1546
+ at,
1547
+ `${/\bnonisolated\b/.test(attributes) ? '' : '@MainActor '}@ObjC(${JSON.stringify(selector)}) `,
1548
+ ])
1549
+ }
1550
+ }
1551
+ }
1552
+ let result = source
1553
+ for (const [at, text] of edits.sort((a, b) => b[0] - a[0]))
1554
+ result = result.slice(0, at) + text + result.slice(at)
1555
+ return result
1556
+ }
1557
+
1422
1558
  // the index-preserving view lowerAnyObjectDoubleValue matches on: every
1423
1559
  // char outside code (comments, strings, regex literals) reads as a space,
1424
1560
  // so an identifier that survives is code. newlines stay, keeping every
@@ -1541,9 +1677,10 @@ function swiftCodeMask(source: string): string {
1541
1677
  export function swiftSourceAsIOS(
1542
1678
  original: string,
1543
1679
  extraObjCExtensions?: Map<string, Set<string>>,
1680
+ tableConformances = tableProtocolConformances([original]),
1544
1681
  ): string {
1545
1682
  const source = liftExtensionOverrides(
1546
- lowerNotificationDelegate(original),
1683
+ lowerTableProtocolMethods(lowerNotificationDelegate(original), tableConformances),
1547
1684
  extraObjCExtensions,
1548
1685
  )
1549
1686
  const { lineStarts, tokens } = swiftCodeScan(source)
@@ -1862,8 +1999,11 @@ const compiledSource = (
1862
1999
  file: string,
1863
2000
  contents: string,
1864
2001
  extraObjCExtensions?: Map<string, Set<string>>,
2002
+ tableConformances?: Map<string, Set<string>>,
1865
2003
  ) =>
1866
- file.endsWith('.swift') ? swiftSourceAsIOS(contents, extraObjCExtensions) : contents
2004
+ file.endsWith('.swift')
2005
+ ? swiftSourceAsIOS(contents, extraObjCExtensions, tableConformances)
2006
+ : contents
1867
2007
 
1868
2008
  /** a dependency package's build copy: the published tree with every Swift
1869
2009
  * source rewritten as app sources are, so an unchanged upstream package that
@@ -1890,6 +2030,7 @@ export function prepareSwiftDependency(source: string, destination: string): voi
1890
2030
  }
1891
2031
  gather(source, true)
1892
2032
  const objcExtensions = objcExtensionMemberIndex(origins)
2033
+ const tableConformances = tableProtocolConformances(origins)
1893
2034
  const copy = (from: string, to: string, root: boolean) => {
1894
2035
  mkdirSync(to, { recursive: true })
1895
2036
  for (const entry of readdirSync(from, { withFileTypes: true })) {
@@ -1905,7 +2046,12 @@ export function prepareSwiftDependency(source: string, destination: string): voi
1905
2046
  )
1906
2047
  writeFileSync(
1907
2048
  target,
1908
- compiledSource(file, readFileSync(file, 'utf8'), objcExtensions),
2049
+ compiledSource(
2050
+ file,
2051
+ readFileSync(file, 'utf8'),
2052
+ objcExtensions,
2053
+ tableConformances,
2054
+ ),
1909
2055
  )
1910
2056
  else cpSync(file, target, { verbatimSymlinks: true })
1911
2057
  }
@@ -1962,17 +2108,17 @@ export function writeSwiftProject(
1962
2108
  const moduleFiles = `\n// sootsim-swift files ${modulePlan.digest('hex').slice(0, 16)}\n// resource accessors ${resourcePlan}\n`
1963
2109
  // an override in one file may answer an @objc member an extension
1964
2110
  // declares in another, so the module-wide member index precedes the copy.
1965
- const objcExtensions = objcExtensionMemberIndex(
1966
- Object.entries(input.files)
1967
- .filter(([file]) => file.endsWith('.swift'))
1968
- .map(([, contents]) => contents),
1969
- )
2111
+ const swiftSources = Object.entries(input.files)
2112
+ .filter(([file]) => file.endsWith('.swift'))
2113
+ .map(([, contents]) => contents)
2114
+ const objcExtensions = objcExtensionMemberIndex(swiftSources)
2115
+ const tableConformances = tableProtocolConformances(swiftSources)
1970
2116
  if (targets.length === 0) {
1971
2117
  for (const [file, contents] of Object.entries(input.files)) {
1972
2118
  if (file === 'Package.swift') continue
1973
2119
  files.set(
1974
2120
  path.join(layout.sources, file),
1975
- compiledSource(file, contents, objcExtensions),
2121
+ compiledSource(file, contents, objcExtensions, tableConformances),
1976
2122
  )
1977
2123
  }
1978
2124
  let manifest = readFileSync(
@@ -2022,7 +2168,10 @@ export function writeSwiftProject(
2022
2168
  const base = layout.multi ? layout.root : layout.sources
2023
2169
  for (const [file, contents] of Object.entries(input.files)) {
2024
2170
  if (file === 'Package.swift') continue
2025
- files.set(path.join(base, file), compiledSource(file, contents, objcExtensions))
2171
+ files.set(
2172
+ path.join(base, file),
2173
+ compiledSource(file, contents, objcExtensions, tableConformances),
2174
+ )
2026
2175
  }
2027
2176
  files.set(
2028
2177
  path.join(layout.root, 'Package.swift'),
@@ -46,6 +46,7 @@ import {
46
46
  REANIMATED_WORKLETIZATION_REGEX,
47
47
  shouldApplyWorkletsPlugin,
48
48
  transformWorkletsCode,
49
+ type WorkletBodyMode,
49
50
  } from './worklets-babel.ts'
50
51
 
51
52
  const sootsimPluginRequire = createRequire(import.meta.url)
@@ -461,7 +462,8 @@ export function engineShellWorkerPlugins(): Plugin[] {
461
462
  gestureHandlerReanimatedRequire(),
462
463
  manifestNativeSeamRedirect(),
463
464
  keyboardControllerBindingsRedirect(),
464
- workletsBabelTransform(() => true),
465
+ // the shell runs received UI source; native clones belong to tenants.
466
+ workletsBabelTransform(() => true, 'transport'),
465
467
  workerBootChunkPlugin(ENGINE_WORKER_BOOT_CLOSURES),
466
468
  ]
467
469
  }
@@ -1774,6 +1776,7 @@ export function workletsBabelTransform(
1774
1776
  // accepted for future per-target overrides; matching is content-driven
1775
1777
  // today so we don't actually consult it. kept for plugin-list parity.
1776
1778
  _isAppSource: (p: string) => boolean = () => false,
1779
+ bodyMode: WorkletBodyMode = 'executable',
1777
1780
  ): Plugin {
1778
1781
  return {
1779
1782
  name: 'sootsim-worklets-babel-transform',
@@ -1792,7 +1795,7 @@ export function workletsBabelTransform(
1792
1795
  if (process.env.SOOTSIM_WORKLETS_BABEL_DEBUG) {
1793
1796
  console.log('[worklets-babel] transforming', id.slice(-80))
1794
1797
  }
1795
- return await transformWorkletsCode(code, id, true)
1798
+ return await transformWorkletsCode(code, id, true, bodyMode)
1796
1799
  } catch (err) {
1797
1800
  // surface but don't kill the build — fall back to raw code so the
1798
1801
  // rest of the pipeline can run. these failures are loud in the
@@ -0,0 +1,125 @@
1
+ import { parse } from 'acorn'
2
+
3
+ interface SyntaxNode {
4
+ type: string
5
+ }
6
+
7
+ function isNode(value: unknown): value is SyntaxNode {
8
+ return (
9
+ value !== null &&
10
+ typeof value === 'object' &&
11
+ typeof Reflect.get(value, 'type') === 'string'
12
+ )
13
+ }
14
+
15
+ function walk(node: SyntaxNode, visit: (node: SyntaxNode) => void): void {
16
+ visit(node)
17
+ for (const value of Object.values(node)) {
18
+ if (isNode(value)) walk(value, visit)
19
+ else if (Array.isArray(value)) {
20
+ for (const child of value) if (isNode(child)) walk(child, visit)
21
+ }
22
+ }
23
+ }
24
+
25
+ function propertyName(node: unknown): string | undefined {
26
+ if (!isNode(node)) return undefined
27
+ const name = Reflect.get(node, node.type === 'Identifier' ? 'name' : 'value')
28
+ return typeof name === 'string' ? name : undefined
29
+ }
30
+
31
+ // collect upstream init records by their actual __initData assignments, including
32
+ // minified identifiers and inline records. babel and acorn share these node shapes.
33
+ export function workletExecutableBodies(syntax: unknown): Array<{
34
+ initData: SyntaxNode
35
+ codeProperty: SyntaxNode
36
+ code: string
37
+ }> {
38
+ if (!isNode(syntax)) throw new Error('peach: expected worklet syntax')
39
+ const tree = syntax
40
+ const initNames = new Set<string>()
41
+ const objects = new Set<SyntaxNode>()
42
+ walk(tree, (node) => {
43
+ if (node.type !== 'AssignmentExpression') return
44
+ const left = Reflect.get(node, 'left')
45
+ if (
46
+ !isNode(left) ||
47
+ left.type !== 'MemberExpression' ||
48
+ propertyName(Reflect.get(left, 'property')) !== '__initData'
49
+ )
50
+ return
51
+ const right = Reflect.get(node, 'right')
52
+ if (!isNode(right)) return
53
+ if (right.type === 'ObjectExpression') objects.add(right)
54
+ else if (right.type === 'Identifier') {
55
+ const name = propertyName(right)
56
+ if (name) initNames.add(name)
57
+ }
58
+ })
59
+ walk(tree, (node) => {
60
+ if (node.type !== 'VariableDeclarator') return
61
+ const name = propertyName(Reflect.get(node, 'id'))
62
+ const init = Reflect.get(node, 'init')
63
+ if (name && initNames.has(name) && isNode(init) && init.type === 'ObjectExpression') {
64
+ objects.add(init)
65
+ }
66
+ })
67
+ const bodies: Array<{ initData: SyntaxNode; codeProperty: SyntaxNode; code: string }> =
68
+ []
69
+ for (const object of objects) {
70
+ const properties = Reflect.get(object, 'properties')
71
+ if (!Array.isArray(properties)) continue
72
+ if (
73
+ properties.some(
74
+ (property) =>
75
+ isNode(property) &&
76
+ propertyName(Reflect.get(property, 'key')) === '__peachExecutable',
77
+ )
78
+ )
79
+ continue
80
+ const property = properties.find(
81
+ (property) =>
82
+ isNode(property) &&
83
+ ['Property', 'ObjectProperty'].includes(property.type) &&
84
+ propertyName(Reflect.get(property, 'key')) === 'code',
85
+ )
86
+ if (!isNode(property)) continue
87
+ const literal = Reflect.get(property, 'value')
88
+ const code = isNode(literal) && Reflect.get(literal, 'value')
89
+ if (typeof code !== 'string') {
90
+ throw new Error('peach: worklet init data requires literal code at build time')
91
+ }
92
+ bodies.push({ initData: object, codeProperty: property, code })
93
+ }
94
+ return bodies
95
+ }
96
+
97
+ // retain source metadata for browser peer transport. local native clones execute
98
+ // the same body as compiled javascript, including worklets nested in that body.
99
+ export function compileWorkletExecutables(
100
+ source: string,
101
+ onInsert?: (offset: number, text: string) => void,
102
+ ): string {
103
+ if (!source.includes('__initData')) return source
104
+ const tree = parse(source, { ecmaVersion: 'latest', sourceType: 'module' })
105
+ const edits = workletExecutableBodies(tree).map(({ codeProperty, code }) => {
106
+ const body = compileWorkletExecutables(code)
107
+ const expression = parse(`(${body})`, { ecmaVersion: 'latest' }).body[0]
108
+ const fn = expression && Reflect.get(expression, 'expression')
109
+ if (
110
+ !isNode(fn) ||
111
+ !['FunctionExpression', 'ArrowFunctionExpression'].includes(fn.type)
112
+ ) {
113
+ throw new Error('peach: worklet code did not compile to a function')
114
+ }
115
+ const offset = Reflect.get(codeProperty, 'end')
116
+ if (typeof offset !== 'number') throw new Error('peach: worklet code has no offset')
117
+ return { offset, text: `, __peachExecutable: (${body})` }
118
+ })
119
+ let compiled = source
120
+ for (const edit of edits.sort((a, b) => b.offset - a.offset)) {
121
+ onInsert?.(edit.offset, edit.text)
122
+ compiled = compiled.slice(0, edit.offset) + edit.text + compiled.slice(edit.offset)
123
+ }
124
+ return compiled
125
+ }
@@ -3,7 +3,11 @@ import fs from 'node:fs'
3
3
  import { createRequire } from 'node:module'
4
4
  import path from 'node:path'
5
5
  import { fileURLToPath } from 'node:url'
6
- import type { TransformOptions } from '@babel/core'
6
+ import {
7
+ compileWorkletExecutables,
8
+ workletExecutableBodies,
9
+ } from './worklet-executable.ts'
10
+ import type { PluginObj, TransformOptions } from '@babel/core'
7
11
  import type { TransformResult } from 'vite'
8
12
 
9
13
  const sootsimPluginRequire = createRequire(import.meta.url)
@@ -87,7 +91,9 @@ function isTypescriptFile(id: string): boolean {
87
91
  // output is a pure function of the source text, the file path, the sourcemap
88
92
  // flag, and the babel toolchain, so cache it on disk keyed by all four. a
89
93
  // normal dev rebuild changes a handful of files and replays the rest.
90
- const CACHE_SCHEMA = 'v1'
94
+ export type WorkletBodyMode = 'executable' | 'transport'
95
+
96
+ const CACHE_SCHEMA = 'v4'
91
97
  const CACHE_ROOT = path.resolve(
92
98
  workspaceRoot,
93
99
  'node_modules',
@@ -134,6 +140,7 @@ function getCacheEntryPath(
134
140
  code: string,
135
141
  id: string,
136
142
  sourceMaps: TransformOptions['sourceMaps'],
143
+ bodyMode: WorkletBodyMode,
137
144
  ): string | null {
138
145
  const dir = getCacheDir()
139
146
  if (!dir) return null
@@ -146,6 +153,7 @@ function getCacheEntryPath(
146
153
  [
147
154
  id,
148
155
  String(sourceMaps),
156
+ bodyMode,
149
157
  process.env.BABEL_ENV ?? '',
150
158
  process.env.NODE_ENV ?? '',
151
159
  code,
@@ -180,9 +188,36 @@ function writeCachedTransform(
180
188
  } catch {}
181
189
  }
182
190
 
191
+ // the final program visitor runs after upstream has built its init records.
192
+ // inserting syntax here lets babel map the original source in the same pass.
193
+ function executableWorkletsPlugin(
194
+ api: Pick<typeof import('@babel/core'), 'types' | 'template'>,
195
+ ): PluginObj {
196
+ return {
197
+ visitor: {
198
+ Program: {
199
+ exit(path) {
200
+ for (const { initData, code } of workletExecutableBodies(path.node)) {
201
+ const properties = Reflect.get(initData, 'properties')
202
+ if (!Array.isArray(properties))
203
+ throw new Error('peach: invalid worklet init record')
204
+ properties.push(
205
+ api.types.objectProperty(
206
+ api.types.identifier('__peachExecutable'),
207
+ api.template.expression.ast(`(${compileWorkletExecutables(code)})`),
208
+ ),
209
+ )
210
+ }
211
+ },
212
+ },
213
+ },
214
+ }
215
+ }
216
+
183
217
  function createWorkletsBabelOptions(
184
218
  id: string,
185
219
  sourceMaps: TransformOptions['sourceMaps'],
220
+ bodyMode: WorkletBodyMode,
186
221
  ): TransformOptions {
187
222
  const isTSX = id.endsWith('.tsx')
188
223
  const isTS = isTypescriptFile(id)
@@ -202,6 +237,7 @@ function createWorkletsBabelOptions(
202
237
  plugins: [
203
238
  [sootsimPluginRequire.resolve('@babel/plugin-syntax-jsx')],
204
239
  [getWorkletsPluginPath(), { processNestedWorklets: true }],
240
+ ...(bodyMode === 'executable' ? [executableWorkletsPlugin] : []),
205
241
  ],
206
242
  }
207
243
  }
@@ -210,15 +246,19 @@ export async function transformWorkletsCode(
210
246
  code: string,
211
247
  id: string,
212
248
  sourceMaps: TransformOptions['sourceMaps'] = true,
249
+ bodyMode: WorkletBodyMode = 'executable',
213
250
  ): Promise<Pick<TransformResult, 'code' | 'map'> | null> {
214
- const entryPath = getCacheEntryPath(code, id, sourceMaps)
251
+ const entryPath = getCacheEntryPath(code, id, sourceMaps, bodyMode)
215
252
  const cached = readCachedTransform(entryPath)
216
253
  if (cached) return cached
217
254
  if (!babelCorePromise) {
218
255
  babelCorePromise = import('@babel/core') as Promise<typeof import('@babel/core')>
219
256
  }
220
257
  const { transformAsync } = await babelCorePromise
221
- const result = await transformAsync(code, createWorkletsBabelOptions(id, sourceMaps))
258
+ const result = await transformAsync(
259
+ code,
260
+ createWorkletsBabelOptions(id, sourceMaps, bodyMode),
261
+ )
222
262
  if (!result?.code) return null
223
263
  const transformed = {
224
264
  code: result.code,
@@ -232,14 +272,15 @@ export function transformWorkletsCodeSync(
232
272
  code: string,
233
273
  id: string,
234
274
  sourceMaps: TransformOptions['sourceMaps'] = false,
275
+ bodyMode: WorkletBodyMode = 'executable',
235
276
  ): Pick<TransformResult, 'code' | 'map'> | null {
236
- const entryPath = getCacheEntryPath(code, id, sourceMaps)
277
+ const entryPath = getCacheEntryPath(code, id, sourceMaps, bodyMode)
237
278
  const cached = readCachedTransform(entryPath)
238
279
  if (cached) return cached
239
280
  const { transformSync } = sootsimPluginRequire(
240
281
  '@babel/core',
241
282
  ) as typeof import('@babel/core')
242
- const result = transformSync(code, createWorkletsBabelOptions(id, sourceMaps))
283
+ const result = transformSync(code, createWorkletsBabelOptions(id, sourceMaps, bodyMode))
243
284
  if (!result?.code) return null
244
285
  const transformed = {
245
286
  code: result.code,