peachsim 0.1.2438 → 0.1.2440

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 (183) hide show
  1. package/README.md +30 -98
  2. package/cli/app-catalog.ts +4 -73
  3. package/cli/catalog/content.ts +1 -1
  4. package/cli/cloud-box-artifact.ts +26 -39
  5. package/cli/cloud-client.ts +69 -117
  6. package/cli/cloud-session.ts +2 -9
  7. package/cli/commands/box.ts +6 -6
  8. package/cli/commands/control.ts +4 -11
  9. package/cli/commands/flow.ts +5 -9
  10. package/cli/commands/kotlin.ts +2 -1
  11. package/cli/commands/platform.ts +21 -39
  12. package/cli/commands/record-three.ts +1 -1
  13. package/cli/commands/shell-url.ts +29 -23
  14. package/cli/dev-build-freshness.ts +4 -3
  15. package/cli/native-input.ts +2 -2
  16. package/cli/outbound-endpoints.ts +20 -45
  17. package/cli/remote-project-bundle.ts +8 -14
  18. package/cli/remote-simulators.ts +1 -1
  19. package/cli/send-to-box.ts +2 -1
  20. package/detox/jest-preset.cjs +1 -1
  21. package/detox/jest-transform.cjs +40 -2
  22. package/dist-lib/agent-daemon-client.cjs +34 -24
  23. package/dist-lib/agent-events.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +19 -17
  25. package/dist-lib/auth/shared-session.cjs +18 -16
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +2 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +20 -583
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +17 -99
  34. package/dist-lib/bundle-channel.cjs +8743 -5562
  35. package/dist-lib/capture-contract.cjs +1 -1
  36. package/dist-lib/capture-contract.mjs +13 -363
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +34 -155
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +2 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +26 -155
  43. package/dist-lib/config.cjs +1 -4
  44. package/dist-lib/config.mjs +11 -30
  45. package/dist-lib/detox/index.cjs +2554 -230
  46. package/dist-lib/detox/jest-preset.cjs +1 -1
  47. package/dist-lib/detox/jest-transform.cjs +40 -2
  48. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  49. package/dist-lib/esm-chunks/acorn-B27MTHKJ.mjs +50 -0
  50. package/dist-lib/esm-chunks/chunk-4U7IGWPB.mjs +42 -0
  51. package/dist-lib/esm-chunks/chunk-5CZQZKYU.mjs +10 -0
  52. package/dist-lib/esm-chunks/chunk-6HFWZJ6C.mjs +115 -0
  53. package/dist-lib/esm-chunks/chunk-6JGALQD5.mjs +12 -0
  54. package/dist-lib/esm-chunks/chunk-ADE23YGG.mjs +30 -0
  55. package/dist-lib/esm-chunks/chunk-D4Z36DQQ.mjs +186 -0
  56. package/dist-lib/esm-chunks/chunk-EATI62W3.mjs +188 -0
  57. package/dist-lib/esm-chunks/chunk-H6QIEJRC.mjs +10992 -0
  58. package/dist-lib/esm-chunks/chunk-HIK3VREC.mjs +1353 -0
  59. package/dist-lib/esm-chunks/chunk-HP7DHONL.mjs +598 -0
  60. package/dist-lib/esm-chunks/chunk-PRZI3CFF.mjs +5719 -0
  61. package/dist-lib/esm-chunks/chunk-QECVPSP3.mjs +10 -0
  62. package/dist-lib/esm-chunks/chunk-R5FNLCBO.mjs +17 -0
  63. package/dist-lib/esm-chunks/chunk-RVMUQQWC.mjs +664 -0
  64. package/dist-lib/esm-chunks/chunk-SJFNKW3W.mjs +57 -0
  65. package/dist-lib/esm-chunks/chunk-WQISIGIX.mjs +10 -0
  66. package/dist-lib/esm-chunks/chunk-X6UKJ5AX.mjs +375 -0
  67. package/dist-lib/esm-chunks/chunk-ZXNBC3PZ.mjs +18959 -0
  68. package/dist-lib/esm-chunks/metro-layout-parser-ZOI5PO4E.mjs +58 -0
  69. package/dist-lib/expo-swift-bundle.cjs +7881 -4717
  70. package/dist-lib/expo-swift-metadata.cjs +1 -1
  71. package/dist-lib/expo-swift-metadata.mjs +16 -165
  72. package/dist-lib/home-paths.cjs +1 -1
  73. package/dist-lib/host/bridge-host.cjs +15685 -11414
  74. package/dist-lib/host/fetch-proxy-handler.cjs +3928 -343
  75. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  76. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -1
  77. package/dist-lib/host/replacement-module-handler.cjs +4 -4
  78. package/dist-lib/host/websocket-proxy.cjs +1 -1
  79. package/dist-lib/index.cjs +9145 -32150
  80. package/dist-lib/jump-to-source-babel.cjs +1 -1
  81. package/dist-lib/jump-to-source-native.cjs +2 -2
  82. package/dist-lib/kotlin-host.cjs +260 -253
  83. package/dist-lib/menu.cjs +1 -1
  84. package/dist-lib/menu.mjs +5 -13
  85. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  86. package/dist-lib/metro-fingerprint-registry.mjs +5 -6
  87. package/dist-lib/metro-production-bundle.cjs +22 -3
  88. package/dist-lib/metro-production-bundle.mjs +26 -92
  89. package/dist-lib/native-app-identity-project.cjs +664 -452
  90. package/dist-lib/native-app-identity-project.mjs +509 -2318
  91. package/dist-lib/native-app-identity.cjs +1 -1
  92. package/dist-lib/native-app-identity.mjs +27 -1340
  93. package/dist-lib/native-firebase-metadata.cjs +1 -1
  94. package/dist-lib/native-firebase-metadata.mjs +5 -18
  95. package/dist-lib/pdfium-raster.cjs +1 -1
  96. package/dist-lib/pdfium-raster.mjs +2 -1
  97. package/dist-lib/plist.cjs +2 -2
  98. package/dist-lib/plist.mjs +5 -7
  99. package/dist-lib/profiles.cjs +2 -1
  100. package/dist-lib/public-brand.cjs +1 -1
  101. package/dist-lib/public-origins-lib-esm.json +246 -187
  102. package/dist-lib/public-origins-lib-static.json +1 -1
  103. package/dist-lib/public-origins-lib.json +1059 -1238
  104. package/dist-lib/react-native-host-modules.cjs +1 -1
  105. package/dist-lib/react-native-host-modules.mjs +2 -1
  106. package/dist-lib/reap-browser.cjs +18 -7
  107. package/dist-lib/scripts/dev-server-scanner.cjs +6 -230
  108. package/dist-lib/sdk.cjs +1 -1
  109. package/dist-lib/sdk.mjs +22 -78
  110. package/dist-lib/skills.cjs +21694 -17393
  111. package/dist-lib/swift-compile.cjs +1355 -1322
  112. package/dist-lib/swift-compile.mjs +68 -19013
  113. package/dist-lib/swift-package.cjs +1 -1
  114. package/dist-lib/swift-package.mjs +35 -630
  115. package/dist-lib/swift-submit.cjs +1 -1
  116. package/dist-lib/swift-submit.mjs +9 -24
  117. package/dist-lib/swift-toolchain.cjs +1 -1
  118. package/dist-lib/swift.cjs +1 -1
  119. package/dist-lib/vendor/@peculiar/x509.cjs +18061 -0
  120. package/dist-lib/vendor/acorn.cjs +5699 -0
  121. package/dist-lib/vendor/bplist-parser.cjs +1589 -0
  122. package/dist-lib/vendor/ignore.cjs +455 -0
  123. package/dist-lib/vendor/magic-string.cjs +1693 -0
  124. package/dist-lib/vendor/plist.cjs +10978 -0
  125. package/dist-lib/vendor/smol-toml.cjs +768 -0
  126. package/dist-lib/vendor/stream-json.cjs +1997 -0
  127. package/dist-lib/vendor/sucrase/dist/index.js.cjs +23593 -0
  128. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +15750 -0
  129. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +11316 -0
  130. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +482 -0
  131. package/dist-lib/vendor/sucrase.cjs +23593 -0
  132. package/dist-lib/vendor/terser.cjs +36874 -0
  133. package/dist-lib/vendor/valibot.cjs +6253 -0
  134. package/dist-lib/vendor/zod.cjs +23262 -0
  135. package/dist-lib/worklet-executable.cjs +3 -3
  136. package/dist-lib/worklet-executable.mjs +11 -16
  137. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +4 -0
  138. package/dist-types/packages/peach-engine/src/config.d.ts +1 -1
  139. package/dist-types/packages/peach-engine/src/remote-stream/cloud-display.d.ts +2 -2
  140. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +9 -0
  141. package/kotlin/fork/NOTICE +3 -0
  142. package/kotlin/sdk.tar.gz +0 -0
  143. package/kotlin/toolchain.json +6 -6
  144. package/package.json +17 -121
  145. package/runtime-companion.json +1 -1
  146. package/scripts/dev-server-scanner.ts +13 -223
  147. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSDateComponentsFormatter.h +1 -1
  148. package/src/android-autolinking.ts +2 -2
  149. package/src/bundle-channel.mjs +3 -15
  150. package/src/cloud-contract.ts +3 -4
  151. package/src/config.ts +0 -5
  152. package/src/host/bridge-host.ts +21 -1
  153. package/src/host/server-scan-handler.ts +1 -9
  154. package/src/index.ts +0 -2
  155. package/src/kotlin-host.ts +1 -2
  156. package/src/kotlinDiscoveryContract.ts +1 -0
  157. package/src/metro-production-bundle.ts +28 -6
  158. package/src/native-seam-manifest.ts +0 -13
  159. package/src/native-slices.ts +1 -1
  160. package/src/one-native-app-catalog.ts +8 -27
  161. package/src/one-native-app-config.ts +95 -0
  162. package/src/one-native-source.ts +250 -0
  163. package/src/one-widget-metadata.ts +45 -126
  164. package/src/oneWidgetContract.ts +80 -117
  165. package/src/serverDiscoveryContract.ts +0 -1
  166. package/src/simulator-route.ts +8 -0
  167. package/src/swift-compile.ts +13 -7
  168. package/src/swift-host.ts +2 -0
  169. package/src/swift-package-manifest.ts +13 -8
  170. package/src/vite-plugin.ts +2 -2
  171. package/src/xcode-project.ts +1 -1
  172. package/dist-lib/metro.cjs +0 -27984
  173. package/dist-lib/vite-swift.cjs +0 -43376
  174. package/dist-lib/vite.cjs +0 -21456
  175. package/src/androidAutolinkingContract.ts +0 -48
  176. package/src/androidRootModuleContract.ts +0 -39
  177. package/src/dev-server-open.ts +0 -92
  178. package/src/metro-plugin.ts +0 -578
  179. package/src/one-widget-discovery.ts +0 -23
  180. package/src/swift-vite-lifetime.ts +0 -42
  181. package/src/vite-plugin-one.ts +0 -746
  182. package/src/vite-plugin-swift.ts +0 -225
  183. package/src/vite.d.ts +0 -10
@@ -239,11 +239,11 @@ export interface RNXMetroDefine {
239
239
  /** the dependency array or async-path object, delimiters included; null when omitted. */
240
240
  dependencies: { start: number; end: number } | null
241
241
  /**
242
- * the module's verbose name, quotes included, when the graph carries one.
243
- * Metro emits it as a fourth `__d` argument on a development graph and omits
244
- * it entirely on a production one.
242
+ * the module's verbose name when the graph carries one: its range, quotes
243
+ * included, and its value. Metro emits it as a fourth `__d` argument on a
244
+ * development graph and omits it entirely on a production one.
245
245
  */
246
- verboseName?: { start: number; end: number }
246
+ verboseName?: { start: number; end: number; value: string }
247
247
  }
248
248
 
249
249
  export interface RNXMetroRun {
@@ -372,8 +372,14 @@ export async function readRNXMetroBundleLayout(
372
372
  dependencies && readableDependencies
373
373
  ? { start: dependencies.start, end: dependencies.end }
374
374
  : null,
375
- ...(verboseName
376
- ? { verboseName: { start: verboseName.start, end: verboseName.end } }
375
+ ...(verboseName?.type === 'Literal' && typeof verboseName.value === 'string'
376
+ ? {
377
+ verboseName: {
378
+ start: verboseName.start,
379
+ end: verboseName.end,
380
+ value: verboseName.value,
381
+ },
382
+ }
377
383
  : {}),
378
384
  })
379
385
  }
@@ -397,6 +403,22 @@ export async function validateRNXMetroModulePaths(
397
403
  checkRNXMetroModulePaths(await readRNXMetroBundleLayout(source), modulePaths)
398
404
  }
399
405
 
406
+ // a development graph names every module in its fourth `__d` argument; a graph
407
+ // with an unnamed or blank module has no complete identity of its own.
408
+ export function readRNXMetroDeclaredModulePaths(
409
+ layout: RNXMetroBundleLayout,
410
+ ): RNXMetroModulePathMap | null {
411
+ if (layout.moduleIdFailures > 0) return null
412
+ const modulePaths: RNXMetroModulePathMap = {}
413
+ for (const statement of layout.statements) {
414
+ if (statement.kind !== 'define') continue
415
+ const name = statement.verboseName?.value
416
+ if (!name) return null
417
+ modulePaths[String(statement.moduleId)] = name
418
+ }
419
+ return modulePaths
420
+ }
421
+
400
422
  /** the identity contract against a layout the caller already read. */
401
423
  export function checkRNXMetroModulePaths(
402
424
  layout: RNXMetroBundleLayout,
@@ -142,19 +142,6 @@ export const NATIVE_SEAM_MANIFEST: NativeSeamEntry[] = [
142
142
  notes:
143
143
  'ImageResizer TurboModule following ios/ImageResizer.mm: loader decode, rotation, scaling, and the file written to the app container',
144
144
  },
145
- {
146
- pkg: 'react-native-adjust',
147
- // upstream's `index.js` reads `NativeModules.Adjust` and
148
- // `NativeModules.AdjustEventEmitter` directly — there is no NativeAdjust
149
- // spec file. listed for documentation parity; the actual seam delivery is
150
- // through the bundle-loader stub-registry routing the package entry to
151
- // `stubs/react-native-adjust.ts`, which imports the native seam from this
152
- // target.
153
- seamBasenames: ['index'],
154
- target: seamPath('react-native-adjust'),
155
- notes:
156
- 'Adjust attribution SAAS — noop native side (Adjust + AdjustEventEmitter NativeModules), pure-JS classes (AdjustConfig/AdjustEvent/...) live in stubs/react-native-adjust.ts',
157
- },
158
145
  {
159
146
  pkg: 'expo-clipboard',
160
147
  // src/ExpoClipboard.ts — `requireNativeModule<ExpoClipboardModule>('ExpoClipboard')`.
@@ -6,7 +6,7 @@ export const NATIVE_SLICE_RECIPES = {
6
6
  GhosttyKit: {
7
7
  name: 'GhosttyKit',
8
8
  upstream: 'cf8edc23f3a6a87a96e41a90013e89e987d34980',
9
- source: '8092fa9cc2677618c811fc58d6c8f2d01d59da38',
9
+ source: '6aa8c2a90bff8845e4b5f802842e72d62f2b46b9',
10
10
  port: 'f4f9162f713b9ab15e0e44499e6878608e48b23e75d7833012aecf0a61ac83ba',
11
11
  repository: 'https://github.com/natew/ghostty.git',
12
12
  zig: '0.16.0',
@@ -1,13 +1,10 @@
1
1
  // what `one prebuild` writes into Images.xcassets from `native.app.ios`: the
2
2
  // AccentColor asset from `accentColor` and the entries of the `assetCatalog`
3
- // folder. a One app with no ios/ on disk declares them only in the config its
4
- // dev server evaluated, so the plugin in that server reports them and the cli
5
- // stamps them into the page's app catalog the way it stamps a prebuilt one.
3
+ // folder. a One app with no ios/ on disk declares them only in its config.
6
4
 
7
5
  import path from 'node:path'
8
6
  import { isRecord } from './is-record'
9
-
10
- export const ONE_NATIVE_APP_CATALOG_ROUTE = '/__peach/native-app-catalog'
7
+ import { readOneNativeApp } from './one-native-app-config'
11
8
 
12
9
  const HEX_COLOR = /^#[\da-f]{6}$/i
13
10
 
@@ -32,28 +29,12 @@ function parseAccent(value: unknown): OneNativeAppAccent | null {
32
29
  return { light: value.light, dark }
33
30
  }
34
31
 
35
- export function parseOneNativeAppCatalog(value: unknown): OneNativeAppCatalog | null {
36
- if (!isRecord(value)) return null
37
- const accentColor = parseAccent(value.accentColor)
32
+ // the catalog folder resolves against the app root, as prebuild resolves it.
33
+ export function readOneNativeAppCatalog(root: string): OneNativeAppCatalog | null {
34
+ const ios = readOneNativeApp(root)?.ios
35
+ if (!isRecord(ios)) return null
36
+ const accentColor = parseAccent(ios.accentColor)
38
37
  const assetCatalog =
39
- typeof value.assetCatalog === 'string' && path.isAbsolute(value.assetCatalog)
40
- ? value.assetCatalog
41
- : null
38
+ typeof ios.assetCatalog === 'string' ? path.resolve(root, ios.assetCatalog) : null
42
39
  return accentColor || assetCatalog ? { accentColor, assetCatalog } : null
43
40
  }
44
-
45
- // the native entry config One's dev server holds on globalThis; the catalog
46
- // folder resolves against the app root, as prebuild resolves it.
47
- export function readOneNativeAppCatalog(
48
- entryConfig: unknown,
49
- root: string,
50
- ): OneNativeAppCatalog | null {
51
- const app = isRecord(entryConfig) ? entryConfig.app : undefined
52
- const ios = isRecord(app) ? app.ios : undefined
53
- if (!isRecord(ios)) return null
54
- return parseOneNativeAppCatalog({
55
- accentColor: ios.accentColor,
56
- assetCatalog:
57
- typeof ios.assetCatalog === 'string' ? path.resolve(root, ios.assetCatalog) : null,
58
- })
59
- }
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { parseSync, type Expression, type ObjectExpression } from 'oxc-parser'
4
+ import { isRecord } from './is-record'
5
+ import { visitParsedProgram } from './visit-parsed-program'
6
+
7
+ const CONFIG_FILES = [
8
+ 'vite.config.ts',
9
+ 'vite.config.mts',
10
+ 'vite.config.js',
11
+ 'vite.config.mjs',
12
+ ]
13
+
14
+ export function oneConfigPath(root: string): string | null {
15
+ for (const name of CONFIG_FILES) {
16
+ const file = path.join(root, name)
17
+ if (fs.existsSync(file)) return file
18
+ }
19
+ return null
20
+ }
21
+
22
+ const NOT_STATIC = Symbol('not static')
23
+
24
+ function staticValue(node: Expression): unknown {
25
+ switch (node.type) {
26
+ case 'Literal':
27
+ return node.value
28
+ case 'TemplateLiteral':
29
+ return node.expressions.length === 0
30
+ ? node.quasis.map((quasi) => quasi.value.cooked).join('')
31
+ : NOT_STATIC
32
+ case 'UnaryExpression':
33
+ if (node.operator === '-' && node.argument.type === 'Literal') {
34
+ const value = node.argument.value
35
+ return typeof value === 'number' ? -value : NOT_STATIC
36
+ }
37
+ return NOT_STATIC
38
+ case 'TSAsExpression':
39
+ case 'TSSatisfiesExpression':
40
+ case 'ParenthesizedExpression':
41
+ return staticValue(node.expression)
42
+ case 'ArrayExpression': {
43
+ const items: unknown[] = []
44
+ for (const element of node.elements) {
45
+ if (!element || element.type === 'SpreadElement') return NOT_STATIC
46
+ const value = staticValue(element)
47
+ if (value === NOT_STATIC) return NOT_STATIC
48
+ items.push(value)
49
+ }
50
+ return items
51
+ }
52
+ case 'ObjectExpression':
53
+ return staticObject(node)
54
+ default:
55
+ return NOT_STATIC
56
+ }
57
+ }
58
+
59
+ // properties computed at runtime read as absent, the way a config without them reads.
60
+ function staticObject(node: ObjectExpression): Record<string, unknown> {
61
+ const out: Record<string, unknown> = {}
62
+ for (const property of node.properties) {
63
+ if (property.type !== 'Property' || property.computed || property.kind !== 'init')
64
+ continue
65
+ const key =
66
+ property.key.type === 'Identifier'
67
+ ? property.key.name
68
+ : property.key.type === 'Literal'
69
+ ? String(property.key.value)
70
+ : null
71
+ if (key === null) continue
72
+ const value = staticValue(property.value)
73
+ if (value !== NOT_STATIC) out[key] = value
74
+ }
75
+ return out
76
+ }
77
+
78
+ // One's native.app is plain data, so it reads from the `one({ native: { app } })`
79
+ // call in the app's vite config without evaluating the config.
80
+ export function readOneNativeApp(root: string): Record<string, unknown> | null {
81
+ const file = oneConfigPath(root)
82
+ if (!file) return null
83
+ const { program } = parseSync(file, fs.readFileSync(file, 'utf8'))
84
+ let app: Record<string, unknown> | null = null
85
+ visitParsedProgram(program, {
86
+ CallExpression(call) {
87
+ if (app || call.callee.type !== 'Identifier' || call.callee.name !== 'one') return
88
+ const [options] = call.arguments
89
+ if (options?.type !== 'ObjectExpression') return
90
+ const { native } = staticObject(options)
91
+ if (isRecord(native) && isRecord(native.app)) app = native.app
92
+ },
93
+ })
94
+ return app
95
+ }
@@ -0,0 +1,250 @@
1
+ // a One app's Swift packages and Kotlin module, compiled for the app root the
2
+ // launch names (`?root=`), with one socket per root announcing edits, as
3
+ // prebuild compiles the same sources into the app.
4
+
5
+ import fs from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import path from 'node:path'
8
+ import { fileURLToPath, pathToFileURL } from 'node:url'
9
+ import { WebSocket, WebSocketServer } from 'ws'
10
+ import { isLoopbackHost } from './backend-origin'
11
+ import { KOTLIN_PACKAGE_PATH } from './kotlinDiscoveryContract'
12
+ import { configuredOneWidget } from './one-widget-metadata'
13
+ import { ONE_WIDGET_PACKAGE, oneWidgetPackage } from './one-widget-package'
14
+ import { ONE_WIDGET_PATH } from './oneWidgetContract'
15
+ import { swiftPackageMetadata, swiftPackageWatchFiles } from './swift-host'
16
+ import { SWIFT_HMR_PATH, SWIFT_PACKAGE_PATH } from './swift-submit'
17
+ import { privateSwiftDistributionRoot } from './swift-toolchain'
18
+ import type { IncomingMessage, ServerResponse } from 'node:http'
19
+ import type { Duplex } from 'node:stream'
20
+
21
+ interface App {
22
+ root: string
23
+ origin: string
24
+ sockets: WebSocketServer
25
+ watched: Set<string>
26
+ // active swift packages: each one's directory and the other files it rebuilds on
27
+ active: Map<string, { packagePath: string; files: Set<string> }>
28
+ packages?: Map<string, string>
29
+ kotlinModule?: string
30
+ }
31
+
32
+ const apps = new Map<string, App>()
33
+
34
+ // the workspace module beside peachsim compiles locally; an install has none,
35
+ // and its packages compile on Contrast
36
+ function swiftModuleRoot(): string | undefined {
37
+ if (privateSwiftDistributionRoot()) return undefined
38
+ const root = path.resolve(
39
+ path.dirname(fileURLToPath(import.meta.url)),
40
+ '../../sootsim-swift',
41
+ )
42
+ return fs.existsSync(path.join(root, 'toolchain.json')) ? root : undefined
43
+ }
44
+
45
+ function appFor(url: URL, origin: string): App | null {
46
+ const requested = url.searchParams.get('root')
47
+ if (!requested || !path.isAbsolute(requested) || !fs.existsSync(requested)) return null
48
+ const root = fs.realpathSync(requested)
49
+ let app = apps.get(root)
50
+ if (!app) {
51
+ app = {
52
+ root,
53
+ origin,
54
+ sockets: new WebSocketServer({ noServer: true }),
55
+ watched: new Set(),
56
+ active: new Map(),
57
+ }
58
+ apps.set(root, app)
59
+ }
60
+ return app
61
+ }
62
+
63
+ function send(app: App, change: object) {
64
+ const message = JSON.stringify(change)
65
+ for (const client of app.sockets.clients)
66
+ if (client.readyState === WebSocket.OPEN) client.send(message)
67
+ }
68
+
69
+ // One owns the package id rule, so the app's own One install names its packages
70
+ async function swiftPackages(root: string): Promise<Map<string, string>> {
71
+ const resolved = createRequire(path.join(root, 'package.json')).resolve(
72
+ 'vxrn/swift-package-id',
73
+ )
74
+ const loaded: { swiftPackageDirectories?: unknown } = await import(
75
+ pathToFileURL(resolved).href
76
+ )
77
+ const directories =
78
+ typeof loaded.swiftPackageDirectories === 'function'
79
+ ? loaded.swiftPackageDirectories(root)
80
+ : null
81
+ if (!(directories instanceof Map))
82
+ throw new Error('vxrn/swift-package-id has no swiftPackageDirectories')
83
+ const packages = new Map<string, string>()
84
+ for (const [name, directory] of directories)
85
+ if (typeof name === 'string' && typeof directory === 'string')
86
+ packages.set(name, directory)
87
+ return packages
88
+ }
89
+
90
+ async function packageMetadata(app: App, packageName: string) {
91
+ const widget =
92
+ packageName === ONE_WIDGET_PACKAGE ? await oneWidgetPackage(app.root) : null
93
+ app.packages ??= await swiftPackages(app.root)
94
+ if (widget && app.packages.has(packageName))
95
+ throw new Error(
96
+ `swift package ${packageName} conflicts with One's generated widget extension`,
97
+ )
98
+ const packagePath = widget?.packagePath ?? app.packages.get(packageName)
99
+ if (!packagePath) throw new Error(`swift package ${packageName} was not found`)
100
+ const moduleRoot = swiftModuleRoot()
101
+ const built = await swiftPackageMetadata(
102
+ packagePath,
103
+ packageName,
104
+ moduleRoot,
105
+ app.origin,
106
+ )
107
+ if (!app.active.has(packageName)) {
108
+ const files = [
109
+ ...(await swiftPackageWatchFiles(packagePath, moduleRoot)),
110
+ ...(widget?.watched ?? []),
111
+ ]
112
+ app.active.set(packageName, { packagePath, files: new Set(files) })
113
+ watch(app, packagePath, true)
114
+ for (const file of files)
115
+ if (!file.startsWith(`${packagePath}${path.sep}`)) watch(app, path.dirname(file))
116
+ }
117
+ return {
118
+ ...built,
119
+ hmrPath: SWIFT_HMR_PATH,
120
+ ...(widget ? { widget: widget.widget } : {}),
121
+ }
122
+ }
123
+
124
+ function changed(app: App, file: string) {
125
+ if (path.basename(file) === 'Package.swift') app.packages = undefined
126
+ for (const [packageName, { packagePath, files }] of app.active) {
127
+ if (!files.has(file) && !file.startsWith(`${packagePath}${path.sep}`)) continue
128
+ packageMetadata(app, packageName).then(
129
+ (metadata) => send(app, { type: 'package', packageName, metadata }),
130
+ (error: unknown) =>
131
+ send(app, {
132
+ type: 'error',
133
+ packageName,
134
+ message: error instanceof Error ? error.message : String(error),
135
+ }),
136
+ )
137
+ }
138
+ const kotlinModule = app.kotlinModule
139
+ if (
140
+ kotlinModule &&
141
+ (file.endsWith('.kt') || file.startsWith(`${kotlinModule}${path.sep}`))
142
+ )
143
+ send(app, { type: 'kotlin', packageName: 'kotlin' })
144
+ }
145
+
146
+ function watch(app: App, directory: string, recursive = false) {
147
+ if (app.watched.has(directory) || !fs.existsSync(directory)) return
148
+ app.watched.add(directory)
149
+ fs.watch(directory, { recursive }, (_event, name) => {
150
+ if (name && !name.split(path.sep).includes('node_modules'))
151
+ changed(app, path.join(directory, name))
152
+ })
153
+ }
154
+
155
+ function loopbackClient(req: IncomingMessage): boolean {
156
+ const remote = req.socket.remoteAddress?.replace(/^::ffff:/, '')
157
+ const origin = req.headers.origin
158
+ return (
159
+ !!remote &&
160
+ isLoopbackHost(remote) &&
161
+ (!origin || isLoopbackHost(new URL(origin).hostname))
162
+ )
163
+ }
164
+
165
+ // answers One's Swift package metadata and Kotlin module routes
166
+ export async function handleOneNativeSourceRequest(
167
+ req: IncomingMessage,
168
+ res: ServerResponse,
169
+ ): Promise<boolean> {
170
+ const url = new URL(req.url ?? '/', 'http://localhost')
171
+ const isSwift = url.pathname.startsWith(SWIFT_PACKAGE_PATH)
172
+ if (
173
+ !isSwift &&
174
+ url.pathname !== KOTLIN_PACKAGE_PATH &&
175
+ url.pathname !== ONE_WIDGET_PATH
176
+ )
177
+ return false
178
+ if (!loopbackClient(req)) {
179
+ res.writeHead(403)
180
+ res.end('native source requires a loopback client')
181
+ return true
182
+ }
183
+ res.setHeader('access-control-allow-origin', req.headers.origin ?? '*')
184
+ res.setHeader('vary', 'origin')
185
+ const app = req.headers.host ? appFor(url, `http://${req.headers.host}`) : null
186
+ if (!app) {
187
+ res.writeHead(400)
188
+ res.end('missing absolute app root')
189
+ return true
190
+ }
191
+ try {
192
+ if (url.pathname === ONE_WIDGET_PATH) {
193
+ const bundle = url.searchParams.get('bundle')
194
+ if (!bundle) {
195
+ res.writeHead(400)
196
+ res.end('missing bundle')
197
+ return true
198
+ }
199
+ const packageUrl = new URL(`${SWIFT_PACKAGE_PATH}${ONE_WIDGET_PACKAGE}`, app.origin)
200
+ packageUrl.searchParams.set('root', app.root)
201
+ const widget = await configuredOneWidget(app.root, bundle, packageUrl.href)
202
+ res.setHeader('content-type', 'application/json')
203
+ res.end(JSON.stringify(widget))
204
+ return true
205
+ }
206
+ if (isSwift) {
207
+ const packageName = decodeURIComponent(
208
+ url.pathname.slice(SWIFT_PACKAGE_PATH.length),
209
+ )
210
+ const metadata = await packageMetadata(app, packageName)
211
+ res.setHeader('content-type', 'application/json')
212
+ res.end(JSON.stringify(metadata))
213
+ return true
214
+ }
215
+ const kotlin = await import('./kotlin-host')
216
+ if (!app.kotlinModule) {
217
+ app.kotlinModule = kotlin.peachKotlinModuleRoot()
218
+ watch(app, app.root, true)
219
+ watch(app, app.kotlinModule, true)
220
+ }
221
+ return await kotlin.serveKotlinRequest(url.pathname, res, {
222
+ root: app.root,
223
+ moduleRoot: app.kotlinModule,
224
+ origin: app.origin,
225
+ hmrPath: SWIFT_HMR_PATH,
226
+ })
227
+ } catch (error) {
228
+ if (!res.headersSent) res.writeHead(500)
229
+ res.end(error instanceof Error ? error.message : String(error))
230
+ return true
231
+ }
232
+ }
233
+
234
+ export function handleOneNativeSourceUpgrade(
235
+ req: IncomingMessage,
236
+ socket: Duplex,
237
+ head: Buffer,
238
+ ): boolean {
239
+ const url = new URL(req.url ?? '/', 'http://localhost')
240
+ if (url.pathname !== SWIFT_HMR_PATH) return false
241
+ const app = req.headers.host ? appFor(url, `http://${req.headers.host}`) : null
242
+ if (!app || !loopbackClient(req)) {
243
+ socket.destroy()
244
+ return true
245
+ }
246
+ app.sockets.handleUpgrade(req, socket, head, (client) => {
247
+ app.sockets.emit('connection', client, req)
248
+ })
249
+ return true
250
+ }