@a16n/web-sim 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/README.md +13 -2
  2. package/bin/cli.ts +255 -0
  3. package/bin/web-sim.js +39 -0
  4. package/overrides/@backpackapp-io/react-native-toast/overrides.ts +15 -0
  5. package/overrides/@react-native-firebase/app/overrides.ts +34 -0
  6. package/overrides/@tiktok-for-business/react-native-sdk/NativeTiktokSdk.ts +29 -0
  7. package/overrides/@tiktok-for-business/react-native-sdk/overrides.ts +9 -0
  8. package/overrides/expo-application/ExpoApplication.ts +81 -0
  9. package/overrides/expo-application/overrides.ts +16 -0
  10. package/overrides/expo-background-task/ExpoBackgroundTaskModule.ts +30 -0
  11. package/overrides/expo-background-task/overrides.ts +9 -0
  12. package/overrides/expo-constants/ExponentConstants.ts +66 -0
  13. package/overrides/expo-constants/overrides.ts +9 -0
  14. package/overrides/expo-device/ExpoDevice.ts +104 -0
  15. package/overrides/expo-device/overrides.ts +9 -0
  16. package/overrides/expo-glass-effect/GlassContainer.tsx +9 -0
  17. package/overrides/expo-glass-effect/GlassView.tsx +95 -0
  18. package/overrides/expo-glass-effect/availability.ts +14 -0
  19. package/overrides/expo-glass-effect/overrides.ts +14 -0
  20. package/overrides/expo-haptics/Haptics.ts +67 -0
  21. package/overrides/expo-haptics/overrides.ts +5 -0
  22. package/overrides/expo-mail-composer/ExpoMailComposer.ts +40 -0
  23. package/overrides/expo-mail-composer/overrides.ts +9 -0
  24. package/overrides/expo-mesh-gradient/MeshGradientView.tsx +44 -0
  25. package/overrides/expo-mesh-gradient/overrides.ts +9 -0
  26. package/overrides/expo-modules-core/overrides.ts +12 -0
  27. package/overrides/expo-navigation-bar/ExpoNavigationBar.ts +29 -0
  28. package/overrides/expo-navigation-bar/NavigationBar.ts +43 -0
  29. package/overrides/expo-navigation-bar/overrides.ts +12 -0
  30. package/overrides/expo-router/NativeStackView.tsx +74 -0
  31. package/overrides/expo-router/NativeTabsView.tsx +263 -0
  32. package/overrides/expo-router/SafeAreaProvider.ts +6 -0
  33. package/overrides/expo-router/overrides.ts +23 -0
  34. package/overrides/expo-router/statusBarRequests.ts +51 -0
  35. package/overrides/expo-screen-orientation/ExpoScreenOrientation.ts +173 -0
  36. package/overrides/expo-screen-orientation/overrides.ts +21 -0
  37. package/overrides/expo-sharing/SharingNativeModule.ts +21 -0
  38. package/overrides/expo-sharing/overrides.ts +9 -0
  39. package/overrides/expo-sms/ExpoSMS.ts +24 -0
  40. package/overrides/expo-sms/overrides.ts +9 -0
  41. package/overrides/expo-splash-screen/SplashScreen.ts +25 -0
  42. package/overrides/expo-splash-screen/overrides.ts +5 -0
  43. package/overrides/expo-status-bar/StatusBar.tsx +44 -0
  44. package/overrides/expo-status-bar/overrides.ts +5 -0
  45. package/overrides/expo-store-review/ExpoStoreReview.ts +18 -0
  46. package/overrides/expo-store-review/overrides.ts +9 -0
  47. package/overrides/expo-symbols/SymbolView.tsx +192 -0
  48. package/overrides/expo-symbols/overrides.ts +9 -0
  49. package/overrides/expo-system-ui/ExpoSystemUI.ts +34 -0
  50. package/overrides/expo-system-ui/overrides.ts +9 -0
  51. package/overrides/expo-task-manager/ExpoTaskManager.ts +39 -0
  52. package/overrides/expo-task-manager/overrides.ts +9 -0
  53. package/overrides/expo-tracking-transparency/ExpoTrackingTransparency.ts +30 -0
  54. package/overrides/expo-tracking-transparency/overrides.ts +11 -0
  55. package/overrides/expo-video/ExpoVideo.ts +16 -0
  56. package/overrides/expo-video/overrides.ts +9 -0
  57. package/overrides/lottie-react-native/LottieView.tsx +87 -0
  58. package/overrides/lottie-react-native/overrides.ts +9 -0
  59. package/overrides/react-native-pager-view/PagerViewNativeComponent.tsx +254 -0
  60. package/overrides/react-native-pager-view/overrides.ts +9 -0
  61. package/overrides/react-native-reanimated/overrides.ts +28 -0
  62. package/overrides/react-native-safe-area-context/NativeSafeAreaProvider.tsx +40 -0
  63. package/overrides/react-native-safe-area-context/overrides.ts +12 -0
  64. package/overrides/react-native-share/NativeRNShare.ts +22 -0
  65. package/overrides/react-native-share/overrides.ts +12 -0
  66. package/overrides/react-native-share/platform.ts +14 -0
  67. package/overrides/react-native-turbo-image/TurboImage.tsx +101 -0
  68. package/overrides/react-native-turbo-image/overrides.ts +9 -0
  69. package/overrides/react-native-web/RefreshControl.tsx +57 -0
  70. package/overrides/react-native-web/overrides.ts +153 -0
  71. package/overrides/react-native-web/useElementLayout.ts +140 -0
  72. package/package.json +78 -4
  73. package/plugins/battery/overrides/expo-battery/ExpoBattery.ts +57 -0
  74. package/plugins/battery/overrides/expo-battery/overrides.ts +9 -0
  75. package/plugins/battery/plugin.ts +8 -0
  76. package/plugins/battery/shell.tsx +56 -0
  77. package/plugins/battery/state.ts +11 -0
  78. package/plugins/biometrics/overrides/expo-local-authentication/ExpoLocalAuthentication.ts +90 -0
  79. package/plugins/biometrics/overrides/expo-local-authentication/overrides.ts +11 -0
  80. package/plugins/biometrics/plugin.ts +8 -0
  81. package/plugins/biometrics/shell.tsx +88 -0
  82. package/plugins/biometrics/state.ts +41 -0
  83. package/plugins/brightness/app.ts +5 -0
  84. package/plugins/brightness/overrides/expo-brightness/Brightness.ts +98 -0
  85. package/plugins/brightness/overrides/expo-brightness/overrides.ts +10 -0
  86. package/plugins/brightness/plugin.ts +9 -0
  87. package/plugins/brightness/shell.tsx +55 -0
  88. package/plugins/brightness/state.ts +19 -0
  89. package/plugins/calendar/calendar.ts +299 -0
  90. package/plugins/calendar/overrides/expo-calendar/ExpoCalendar.ts +358 -0
  91. package/plugins/calendar/overrides/expo-calendar/LegacyExpoCalendar.ts +163 -0
  92. package/plugins/calendar/overrides/expo-calendar/overrides.ts +14 -0
  93. package/plugins/calendar/plugin.ts +8 -0
  94. package/plugins/calendar/shell.tsx +123 -0
  95. package/plugins/camera/overrides/expo-camera/ExpoCamera.tsx +269 -0
  96. package/plugins/camera/overrides/expo-camera/ExpoCameraManager.ts +56 -0
  97. package/plugins/camera/overrides/expo-camera/overrides.ts +12 -0
  98. package/plugins/camera/plugin.ts +9 -0
  99. package/plugins/camera/shell.tsx +107 -0
  100. package/plugins/camera/state.ts +61 -0
  101. package/plugins/clipboard/overrides/expo-clipboard/ExpoClipboard.ts +138 -0
  102. package/plugins/clipboard/overrides/expo-clipboard/overrides.ts +9 -0
  103. package/plugins/clipboard/plugin.ts +8 -0
  104. package/plugins/clipboard/shell.tsx +122 -0
  105. package/plugins/clipboard/state.ts +93 -0
  106. package/plugins/clock/app.ts +25 -0
  107. package/plugins/clock/plugin.ts +8 -0
  108. package/plugins/clock/shell.tsx +225 -0
  109. package/plugins/clock/state.ts +12 -0
  110. package/plugins/contacts/contacts.ts +125 -0
  111. package/plugins/contacts/overrides/expo-contacts/ExpoContacts.ts +153 -0
  112. package/plugins/contacts/overrides/expo-contacts/ExpoContactsNext.ts +232 -0
  113. package/plugins/contacts/overrides/expo-contacts/overrides.ts +12 -0
  114. package/plugins/contacts/plugin.ts +8 -0
  115. package/plugins/contacts/shell.tsx +109 -0
  116. package/plugins/home-indicator/app.ts +5 -0
  117. package/plugins/home-indicator/plugin.ts +9 -0
  118. package/plugins/home-indicator/requests.ts +48 -0
  119. package/plugins/home-indicator/shell.tsx +68 -0
  120. package/plugins/home-indicator/state.ts +31 -0
  121. package/plugins/keep-awake/app.ts +5 -0
  122. package/plugins/keep-awake/overrides/expo-keep-awake/ExpoKeepAwake.ts +27 -0
  123. package/plugins/keep-awake/overrides/expo-keep-awake/overrides.ts +9 -0
  124. package/plugins/keep-awake/plugin.ts +9 -0
  125. package/plugins/keep-awake/shell.tsx +80 -0
  126. package/plugins/keep-awake/state.ts +12 -0
  127. package/plugins/keyboard/Keyboard.tsx +354 -0
  128. package/plugins/keyboard/app.ts +90 -0
  129. package/plugins/keyboard/controller.ts +384 -0
  130. package/plugins/keyboard/fields.ts +244 -0
  131. package/plugins/keyboard/icons.tsx +283 -0
  132. package/plugins/keyboard/keyboard.css +362 -0
  133. package/plugins/keyboard/layouts/android.ts +175 -0
  134. package/plugins/keyboard/layouts/index.ts +10 -0
  135. package/plugins/keyboard/layouts/ios.ts +219 -0
  136. package/plugins/keyboard/layouts/types.ts +80 -0
  137. package/plugins/keyboard/overrides/react-native-keyboard-controller/KeyboardController.tsx +470 -0
  138. package/plugins/keyboard/overrides/react-native-keyboard-controller/overrides.ts +9 -0
  139. package/plugins/keyboard/plugin.ts +13 -0
  140. package/plugins/keyboard/shell.tsx +133 -0
  141. package/plugins/keyboard/state.ts +92 -0
  142. package/plugins/keyboard/suggestions.ts +63 -0
  143. package/plugins/keyboard/taps.ts +77 -0
  144. package/plugins/keyboard/typing.ts +112 -0
  145. package/plugins/locale/app.ts +232 -0
  146. package/plugins/locale/locale.ts +143 -0
  147. package/plugins/locale/overrides/expo-localization/ExpoLocalization.ts +41 -0
  148. package/plugins/locale/overrides/expo-localization/overrides.ts +9 -0
  149. package/plugins/locale/plugin.ts +9 -0
  150. package/plugins/locale/shell.tsx +147 -0
  151. package/plugins/locale/state.ts +36 -0
  152. package/plugins/location/geo.ts +56 -0
  153. package/plugins/location/overrides/expo-location/ExpoLocation.ts +235 -0
  154. package/plugins/location/overrides/expo-location/overrides.ts +11 -0
  155. package/plugins/location/places.ts +38 -0
  156. package/plugins/location/plugin.ts +8 -0
  157. package/plugins/location/shell.tsx +188 -0
  158. package/plugins/location/state.ts +51 -0
  159. package/plugins/motion/overrides/expo-sensors/DeviceSensor.ts +169 -0
  160. package/plugins/motion/overrides/expo-sensors/ExponentPedometer.ts +54 -0
  161. package/plugins/motion/overrides/expo-sensors/overrides.ts +14 -0
  162. package/plugins/motion/plugin.ts +8 -0
  163. package/plugins/motion/sensors.ts +116 -0
  164. package/plugins/motion/shell.tsx +136 -0
  165. package/plugins/motion/state.ts +46 -0
  166. package/plugins/network/app.ts +400 -0
  167. package/plugins/network/overrides/expo-network/ExpoNetwork.ts +51 -0
  168. package/plugins/network/overrides/expo-network/overrides.ts +9 -0
  169. package/plugins/network/plugin.ts +8 -0
  170. package/plugins/network/shell.tsx +67 -0
  171. package/plugins/network/state.ts +29 -0
  172. package/plugins/notifications/center.ts +255 -0
  173. package/plugins/notifications/content.ts +36 -0
  174. package/plugins/notifications/overrides/expo-notifications/NotificationsModule.ts +175 -0
  175. package/plugins/notifications/overrides/expo-notifications/channels.ts +108 -0
  176. package/plugins/notifications/overrides/expo-notifications/getDevicePushTokenAsync.ts +19 -0
  177. package/plugins/notifications/overrides/expo-notifications/getExpoPushTokenAsync.ts +16 -0
  178. package/plugins/notifications/overrides/expo-notifications/overrides.ts +36 -0
  179. package/plugins/notifications/plugin.ts +8 -0
  180. package/plugins/notifications/shell.tsx +192 -0
  181. package/plugins/notifications/state.ts +56 -0
  182. package/plugins/notifications/tokens.ts +47 -0
  183. package/plugins/notifications/trigger.ts +107 -0
  184. package/plugins/permissions/plugin.ts +6 -0
  185. package/plugins/permissions/shell.tsx +50 -0
  186. package/plugins/permissions/state.ts +38 -0
  187. package/plugins/photos/appLibrary.ts +114 -0
  188. package/plugins/photos/library.ts +322 -0
  189. package/plugins/photos/overrides/expo-image-picker/ExponentImagePicker.ts +153 -0
  190. package/plugins/photos/overrides/expo-image-picker/overrides.ts +13 -0
  191. package/plugins/photos/overrides/expo-media-library/ExpoMediaLibrary.ts +235 -0
  192. package/plugins/photos/overrides/expo-media-library/NativeMediaLibraryModule.ts +318 -0
  193. package/plugins/photos/overrides/expo-media-library/overrides.ts +19 -0
  194. package/plugins/photos/plugin.ts +8 -0
  195. package/plugins/photos/samples.ts +367 -0
  196. package/plugins/photos/shell.tsx +164 -0
  197. package/plugins/photos/state.ts +88 -0
  198. package/plugins/storage/files.ts +351 -0
  199. package/plugins/storage/overrides/expo-file-system/ExpoFileSystem.ts +770 -0
  200. package/plugins/storage/overrides/expo-file-system/ExponentFileSystem.ts +196 -0
  201. package/plugins/storage/overrides/expo-file-system/overrides.ts +13 -0
  202. package/plugins/storage/overrides/expo-secure-store/ExpoSecureStore.ts +75 -0
  203. package/plugins/storage/overrides/expo-secure-store/overrides.ts +9 -0
  204. package/plugins/storage/plugin.ts +8 -0
  205. package/plugins/storage/reset.ts +136 -0
  206. package/plugins/storage/secure.ts +71 -0
  207. package/plugins/storage/shell.tsx +365 -0
  208. package/plugins/storage/state.ts +13 -0
  209. package/src/client/app/appDocument.ts +113 -0
  210. package/src/client/app/appFocus.ts +97 -0
  211. package/src/client/app/console.ts +118 -0
  212. package/src/client/app/fonts.ts +59 -0
  213. package/src/client/app/main.tsx +99 -0
  214. package/src/client/app/routeContext.ts +45 -0
  215. package/src/client/app/touch.ts +640 -0
  216. package/src/client/entry.ts +20 -0
  217. package/src/client/modules.d.ts +8 -0
  218. package/src/client/react-native/app.ts +57 -0
  219. package/src/client/react-native/deep.ts +13 -0
  220. package/src/client/react-native/keyboard.tsx +192 -0
  221. package/src/client/react-native/library.ts +256 -0
  222. package/src/client/shell/Cookies.tsx +95 -0
  223. package/src/client/shell/LogDrawer.tsx +415 -0
  224. package/src/client/shell/PhotoPicker.tsx +174 -0
  225. package/src/client/shell/PluginOverlays.tsx +42 -0
  226. package/src/client/shell/PluginPanels.tsx +82 -0
  227. package/src/client/shell/ResetApp.tsx +87 -0
  228. package/src/client/shell/Resizer.tsx +99 -0
  229. package/src/client/shell/Shell.tsx +531 -0
  230. package/src/client/shell/SystemBars.tsx +376 -0
  231. package/src/client/shell/SystemCamera.tsx +181 -0
  232. package/src/client/shell/SystemOverlay.tsx +422 -0
  233. package/src/client/shell/SystemSheets.tsx +462 -0
  234. package/src/client/shell/backdrop.ts +229 -0
  235. package/src/client/shell/control.ts +91 -0
  236. package/src/client/shell/events.ts +226 -0
  237. package/src/client/shell/geometry.ts +68 -0
  238. package/src/client/shell/host.ts +492 -0
  239. package/src/client/shell/icons.tsx +34 -0
  240. package/src/client/shell/logFeed.ts +102 -0
  241. package/src/client/shell/main.tsx +22 -0
  242. package/src/client/shell/permissionCopy.ts +169 -0
  243. package/src/client/shell/plugins.ts +266 -0
  244. package/src/client/shell/popout.ts +185 -0
  245. package/src/client/shell/popover.ts +27 -0
  246. package/src/client/shell/shell.css +878 -0
  247. package/src/client/shell/statusTime.ts +31 -0
  248. package/src/client/shell/tooltips.ts +104 -0
  249. package/src/client/virtual.d.ts +21 -0
  250. package/src/devices/catalog.ts +223 -0
  251. package/src/devices/types.ts +83 -0
  252. package/src/node/appInfo.ts +186 -0
  253. package/src/node/appSource.ts +138 -0
  254. package/src/node/config.ts +180 -0
  255. package/src/node/control.ts +144 -0
  256. package/src/node/doctor.ts +199 -0
  257. package/src/node/events/cli.ts +206 -0
  258. package/src/node/events/shared.ts +238 -0
  259. package/src/node/events/store.ts +266 -0
  260. package/src/node/index.ts +5 -0
  261. package/src/node/overrides/define.ts +56 -0
  262. package/src/node/overrides/packages.ts +136 -0
  263. package/src/node/overrides/platformPatch.ts +56 -0
  264. package/src/node/overrides/plugin.ts +166 -0
  265. package/src/node/overrides/registry.ts +258 -0
  266. package/src/node/paths.ts +18 -0
  267. package/src/node/platform.ts +171 -0
  268. package/src/node/plugins.ts +98 -0
  269. package/src/node/proxy.ts +421 -0
  270. package/src/node/server.ts +253 -0
  271. package/src/plugin/index.ts +33 -0
  272. package/src/plugin/types.ts +127 -0
  273. package/src/plugin/ui.tsx +562 -0
  274. package/src/runtime/clock.ts +112 -0
  275. package/src/runtime/draw.ts +196 -0
  276. package/src/runtime/index.ts +513 -0
  277. package/src/runtime/media.ts +379 -0
  278. package/src/runtime/records.ts +76 -0
  279. package/src/runtime/timezone.ts +81 -0
@@ -0,0 +1,421 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import type { IncomingMessage, ServerResponse } from 'node:http'
3
+ import path from 'node:path'
4
+ import net, { type Socket } from 'node:net'
5
+ import { Readable, type Duplex } from 'node:stream'
6
+ import tls from 'node:tls'
7
+ import type { Plugin } from 'vite'
8
+
9
+ /**
10
+ * A phone's requests go straight to the server; a browser's cross-origin requests need the server to allow the page's
11
+ * origin (CORS), which an API built for an app never does. So the app's cross-origin requests come here, and the dev
12
+ * server makes them as the phone would: with no `Origin`, with the headers the app set (`Cookie` and `User-Agent`
13
+ * too, which a browser won't let a page set), and with the phone's cookie jar.
14
+ *
15
+ * The browser half is the network plugin's `app.ts`. It sends the target as `?url=`, and the app's headers as JSON in
16
+ * `x-web-sim-headers`. The response comes back as the server sent it, except `Set-Cookie`, which a browser hides from
17
+ * pages; it comes as JSON in `x-web-sim-set-cookie`, for the browser half to give back to the app as React Native's
18
+ * fetch does.
19
+ */
20
+ export const PROXY_PATH = '/__web-sim/proxy'
21
+ /**
22
+ * WebSockets to other servers come here: a browser's carry the page's `Origin` and none of the phone's cookies, so a
23
+ * server that checks either turns them away. `?url=` is the target, `&headers=` the app's headers as JSON (React
24
+ * Native's third constructor argument), `&offline=1` a socket the network panel has cut off.
25
+ */
26
+ export const WEBSOCKET_PATH = '/__web-sim/websocket'
27
+ /**
28
+ * The cookie jar, for the network panel: GET lists it by domain (names, paths, expiry; no values, which the event log
29
+ * keeps out too), DELETE clears it, or one domain's with `?domain=`. Each change is also sent to the shell as the
30
+ * `web-sim:cookies` message, with the same list.
31
+ */
32
+ export const COOKIES_PATH = '/__web-sim/cookies'
33
+
34
+ /** A cookie as the panel and the CLI see it. */
35
+ export type CookieSummary = { name: string; path: string; expires: number | null }
36
+
37
+ /** Headers that belong to one hop, which a proxy doesn't pass on. */
38
+ const HOP_BY_HOP = new Set([
39
+ 'connection',
40
+ 'keep-alive',
41
+ 'transfer-encoding',
42
+ 'upgrade',
43
+ 'proxy-authenticate',
44
+ 'proxy-authorization',
45
+ 'te',
46
+ 'trailer',
47
+ 'host',
48
+ 'content-length',
49
+ ])
50
+
51
+ /** What React Native's networking sends as its user agent when the app sets none. */
52
+ const USER_AGENTS: Record<string, string> = {
53
+ ios: 'CFNetwork/3826.400.120 Darwin/25.0.0',
54
+ android: 'okhttp/4.12.0',
55
+ }
56
+
57
+ type Cookie = { name: string; value: string; path: string; expires: number | null }
58
+
59
+ /**
60
+ * The phone's cookie jar (NSHTTPCookieStorage, OkHttp's CookieJar): cookies a server sets are sent back to it, by
61
+ * host and path, until they expire. Kept in a file, so like the phone's it outlives the app and the dev server.
62
+ */
63
+ class CookieJar {
64
+ private readonly hosts = new Map<string, Map<string, Cookie>>()
65
+ private saving: ReturnType<typeof setTimeout> | null = null
66
+ private readonly file: string | null
67
+ /** Called after each change to what the jar holds. */
68
+ onChange: (() => void) | null = null
69
+
70
+ constructor(file: string | null) {
71
+ this.file = file
72
+ if (file === null) {
73
+ return
74
+ }
75
+ try {
76
+ const saved = JSON.parse(readFileSync(file, 'utf8')) as Record<string, Cookie[]>
77
+ for (const [domain, cookies] of Object.entries(saved)) {
78
+ this.hosts.set(domain, new Map(cookies.map((cookie) => [`${cookie.name};${cookie.path}`, cookie])))
79
+ }
80
+ } catch {
81
+ // No jar yet.
82
+ }
83
+ }
84
+
85
+ private save() {
86
+ const file = this.file
87
+ if (file === null || this.saving !== null) {
88
+ return
89
+ }
90
+ this.saving = setTimeout(() => {
91
+ this.saving = null
92
+ const json = Object.fromEntries([...this.hosts].map(([domain, jar]) => [domain, [...jar.values()]]))
93
+ mkdirSync(path.dirname(file), { recursive: true })
94
+ writeFileSync(file, JSON.stringify(json, null, 2))
95
+ }, 200)
96
+ }
97
+
98
+ store(url: URL, setCookies: string[]) {
99
+ for (const header of setCookies) {
100
+ const [pair = '', ...attributes] = header.split(';')
101
+ const at = pair.indexOf('=')
102
+ if (at < 1) {
103
+ continue
104
+ }
105
+ const cookie: Cookie = { name: pair.slice(0, at).trim(), value: pair.slice(at + 1).trim(), path: '/', expires: null }
106
+ let domain = url.hostname
107
+ for (const attribute of attributes) {
108
+ const [key = '', ...rest] = attribute.split('=')
109
+ const value = rest.join('=').trim()
110
+ switch (key.trim().toLowerCase()) {
111
+ case 'path':
112
+ cookie.path = value || '/'
113
+ break
114
+ case 'domain':
115
+ domain = value.replace(/^\./, '').toLowerCase() || domain
116
+ break
117
+ case 'max-age':
118
+ cookie.expires = Date.now() + Number(value) * 1000
119
+ break
120
+ case 'expires':
121
+ cookie.expires ??= Date.parse(value)
122
+ break
123
+ }
124
+ }
125
+ const jar = this.hosts.get(domain) ?? new Map<string, Cookie>()
126
+ this.hosts.set(domain, jar)
127
+ const key = `${cookie.name};${cookie.path}`
128
+ if (cookie.expires !== null && cookie.expires <= Date.now()) {
129
+ jar.delete(key)
130
+ } else {
131
+ jar.set(key, cookie)
132
+ }
133
+ }
134
+ if (setCookies.length > 0) {
135
+ this.save()
136
+ this.onChange?.()
137
+ }
138
+ }
139
+
140
+ /** The cookies held now, by domain, expired ones left out. */
141
+ list(): Record<string, CookieSummary[]> {
142
+ const now = Date.now()
143
+ const domains: Record<string, CookieSummary[]> = {}
144
+ for (const [domain, jar] of [...this.hosts].sort(([a], [b]) => a.localeCompare(b))) {
145
+ const cookies = [...jar.values()]
146
+ .filter((cookie) => cookie.expires === null || cookie.expires > now)
147
+ .map(({ name, path, expires }) => ({ name, path, expires }))
148
+ if (cookies.length > 0) {
149
+ domains[domain] = cookies
150
+ }
151
+ }
152
+ return domains
153
+ }
154
+
155
+ /** Empties the jar, or one domain's cookies. Returns how many cookies it held. */
156
+ clear(domain?: string): number {
157
+ const domains = domain === undefined ? [...this.hosts.keys()] : [domain.replace(/^\./, '').toLowerCase()]
158
+ let count = 0
159
+ for (const name of domains) {
160
+ count += this.hosts.get(name)?.size ?? 0
161
+ this.hosts.delete(name)
162
+ }
163
+ this.save()
164
+ this.onChange?.()
165
+ return count
166
+ }
167
+
168
+ header(url: URL): string | null {
169
+ const now = Date.now()
170
+ const cookies: string[] = []
171
+ for (const [domain, jar] of this.hosts) {
172
+ if (url.hostname !== domain && !url.hostname.endsWith(`.${domain}`)) {
173
+ continue
174
+ }
175
+ for (const [key, cookie] of jar) {
176
+ if (cookie.expires !== null && cookie.expires <= now) {
177
+ jar.delete(key)
178
+ } else if (url.pathname.startsWith(cookie.path)) {
179
+ cookies.push(`${cookie.name}=${cookie.value}`)
180
+ }
181
+ }
182
+ }
183
+ return cookies.length > 0 ? cookies.join('; ') : null
184
+ }
185
+ }
186
+
187
+ function readBody(req: IncomingMessage): Promise<Buffer> {
188
+ return new Promise((resolve, reject) => {
189
+ const chunks: Buffer[] = []
190
+ req.on('data', (chunk: Buffer) => chunks.push(chunk))
191
+ req.on('end', () => resolve(Buffer.concat(chunks)))
192
+ req.on('error', reject)
193
+ })
194
+ }
195
+
196
+ function fail(res: ServerResponse, status: number, message: string) {
197
+ res.statusCode = status
198
+ res.setHeader('Content-Type', 'text/plain')
199
+ res.setHeader('x-web-sim-proxy-error', '1')
200
+ res.end(message)
201
+ }
202
+
203
+ /** `jarFile` keeps the phone's cookies between runs; null keeps them in memory. */
204
+ export function appProxy(jarFile: string | null = null): Plugin {
205
+ const jar = new CookieJar(jarFile)
206
+ return {
207
+ name: 'web-sim:proxy',
208
+ configureServer(server) {
209
+ jar.onChange = () => server.ws.send('web-sim:cookies', jar.list())
210
+ server.middlewares.use(COOKIES_PATH, (req: IncomingMessage, res: ServerResponse) => {
211
+ res.setHeader('Content-Type', 'application/json')
212
+ if (req.method === 'DELETE') {
213
+ const domain = new URL(req.url ?? '', 'http://localhost').searchParams.get('domain') ?? undefined
214
+ const cleared = jar.clear(domain)
215
+ res.end(JSON.stringify({ cleared, domains: jar.list() }))
216
+ } else {
217
+ res.end(JSON.stringify(jar.list()))
218
+ }
219
+ })
220
+ server.httpServer?.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer) => {
221
+ if (req.url?.startsWith(WEBSOCKET_PATH)) {
222
+ tunnelWebSocket(req, socket as Socket, head, jar)
223
+ }
224
+ })
225
+ server.middlewares.use(PROXY_PATH, async (req: IncomingMessage, res: ServerResponse) => {
226
+ const query = new URL(req.url ?? '', 'http://localhost').searchParams
227
+ let target: URL
228
+ try {
229
+ target = new URL(query.get('url') ?? '')
230
+ } catch {
231
+ fail(res, 400, 'web-sim proxy: ?url= must be an absolute URL')
232
+ return
233
+ }
234
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') {
235
+ fail(res, 400, `web-sim proxy: only http and https URLs, not ${target.protocol}`)
236
+ return
237
+ }
238
+ let appHeaders: [string, string][] = []
239
+ try {
240
+ appHeaders = JSON.parse(String(req.headers['x-web-sim-headers'] ?? '[]')) as [string, string][]
241
+ } catch {
242
+ fail(res, 400, 'web-sim proxy: x-web-sim-headers must be JSON')
243
+ return
244
+ }
245
+ const headers = new Headers()
246
+ for (const [name, value] of appHeaders) {
247
+ if (!HOP_BY_HOP.has(name.toLowerCase())) {
248
+ headers.append(name, value)
249
+ }
250
+ }
251
+ // A FormData body's type, with its boundary, is set by the browser on the request it sends here.
252
+ const bodyType = req.headers['content-type']
253
+ if (!headers.has('content-type') && typeof bodyType === 'string') {
254
+ headers.set('content-type', bodyType)
255
+ }
256
+ if (!headers.has('user-agent')) {
257
+ headers.set('user-agent', USER_AGENTS[String(req.headers['x-web-sim-platform'])] ?? USER_AGENTS.ios)
258
+ }
259
+ const appCookie = headers.get('cookie')
260
+ let method = (req.method ?? 'GET').toUpperCase()
261
+ let body: Buffer | undefined = method === 'GET' || method === 'HEAD' ? undefined : await readBody(req)
262
+ const abort = new AbortController()
263
+ res.on('close', () => abort.abort())
264
+ let url = target
265
+ let response: Response
266
+ let setCookies: string[]
267
+ // Redirects are followed here, not by fetch, so the cookies each hop sets reach the jar and the next hop, as a
268
+ // phone's networking does.
269
+ for (let hop = 0; ; hop++) {
270
+ const cookies = appCookie ?? jar.header(url)
271
+ if (cookies === null) {
272
+ headers.delete('cookie')
273
+ } else {
274
+ headers.set('cookie', cookies)
275
+ }
276
+ try {
277
+ response = await fetch(url, { method, headers, body: body as BodyInit | undefined, redirect: 'manual', signal: abort.signal })
278
+ } catch (error) {
279
+ const cause = (error as { cause?: { code?: string; message?: string } }).cause
280
+ fail(res, 502, `web-sim proxy: ${cause?.code ?? cause?.message ?? (error as Error).message}`)
281
+ return
282
+ }
283
+ setCookies = response.headers.getSetCookie()
284
+ jar.store(url, setCookies)
285
+ const location = response.headers.get('location')
286
+ if (response.status < 300 || response.status > 308 || response.status === 304 || location === null || hop === 20) {
287
+ break
288
+ }
289
+ url = new URL(location, url)
290
+ // 303, and 301/302 after a POST, continue as a GET without the body, as browsers and phones do.
291
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === 'POST')) {
292
+ method = 'GET'
293
+ body = undefined
294
+ headers.delete('content-type')
295
+ }
296
+ await response.body?.cancel()
297
+ }
298
+ res.statusCode = response.status
299
+ res.statusMessage = response.statusText
300
+ response.headers.forEach((value, name) => {
301
+ // fetch has already undone the content encoding.
302
+ if (!HOP_BY_HOP.has(name) && name !== 'set-cookie' && name !== 'content-encoding') {
303
+ res.setHeader(name, value)
304
+ }
305
+ })
306
+ if (setCookies.length > 0) {
307
+ res.setHeader('x-web-sim-set-cookie', JSON.stringify(setCookies))
308
+ }
309
+ res.setHeader('x-web-sim-url', url.href)
310
+ if (response.body === null) {
311
+ res.end()
312
+ return
313
+ }
314
+ Readable.fromWeb(response.body as never)
315
+ .on('error', () => res.destroy())
316
+ .pipe(res)
317
+ })
318
+ },
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Opens the app's WebSocket to its server as the phone would, then joins the two connections byte for byte. The
324
+ * browser's handshake key goes upstream unchanged, so the server's answer is valid for the browser, and frames pass
325
+ * through untouched (the browser masks them, as a client must).
326
+ */
327
+ function tunnelWebSocket(req: IncomingMessage, client: Socket, head: Buffer, jar: CookieJar) {
328
+ const query = new URL(req.url ?? '', 'http://localhost').searchParams
329
+ const reject = (status: string) => {
330
+ client.end(`HTTP/1.1 ${status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`)
331
+ }
332
+ let target: URL
333
+ try {
334
+ target = new URL(query.get('url') ?? '')
335
+ } catch {
336
+ reject('400 Bad Request')
337
+ return
338
+ }
339
+ if ((target.protocol !== 'ws:' && target.protocol !== 'wss:') || query.get('offline') === '1') {
340
+ reject('400 Bad Request')
341
+ return
342
+ }
343
+ let appHeaders: Record<string, string> = {}
344
+ try {
345
+ appHeaders = JSON.parse(query.get('headers') ?? '{}') as Record<string, string>
346
+ } catch {
347
+ // An unreadable header list is sent as none.
348
+ }
349
+ const secure = target.protocol === 'wss:'
350
+ const port = Number(target.port || (secure ? 443 : 80))
351
+ const lines = [
352
+ `GET ${target.pathname}${target.search} HTTP/1.1`,
353
+ `Host: ${target.host}`,
354
+ 'Upgrade: websocket',
355
+ 'Connection: Upgrade',
356
+ `Sec-WebSocket-Key: ${req.headers['sec-websocket-key'] ?? ''}`,
357
+ 'Sec-WebSocket-Version: 13',
358
+ ]
359
+ for (const name of ['sec-websocket-protocol', 'sec-websocket-extensions']) {
360
+ const value = req.headers[name]
361
+ if (typeof value === 'string') {
362
+ lines.push(`${name}: ${value}`)
363
+ }
364
+ }
365
+ const names = new Set(Object.keys(appHeaders).map((name) => name.toLowerCase()))
366
+ for (const [name, value] of Object.entries(appHeaders)) {
367
+ if (!HOP_BY_HOP.has(name.toLowerCase()) && !/^(upgrade|sec-websocket-)/i.test(name)) {
368
+ lines.push(`${name}: ${String(value).replace(/[\r\n]/g, ' ')}`)
369
+ }
370
+ }
371
+ if (!names.has('user-agent')) {
372
+ lines.push(`User-Agent: ${USER_AGENTS[query.get('platform') ?? ''] ?? USER_AGENTS.ios}`)
373
+ }
374
+ const cookies = jar.header(new URL(`${secure ? 'https' : 'http'}://${target.host}${target.pathname}`))
375
+ if (cookies !== null && !names.has('cookie')) {
376
+ lines.push(`Cookie: ${cookies}`)
377
+ }
378
+ const upstream: Socket = secure ? tls.connect({ host: target.hostname, port, servername: target.hostname }) : net.connect({ host: target.hostname, port })
379
+ upstream.on('error', () => {
380
+ if (!client.destroyed) {
381
+ reject('502 Bad Gateway')
382
+ }
383
+ })
384
+ client.on('error', () => upstream.destroy())
385
+ upstream.once(secure ? 'secureConnect' : 'connect', () => {
386
+ upstream.write(`${lines.join('\r\n')}\r\n\r\n`)
387
+ if (head.length > 0) {
388
+ upstream.write(head)
389
+ }
390
+ })
391
+ // The server's answer is read up to the end of its headers, to keep the cookies it sets and drop them from what
392
+ // the browser gets (they belong to the server's domain, not the dev server's).
393
+ let buffered = Buffer.alloc(0)
394
+ const onData = (chunk: Buffer) => {
395
+ buffered = Buffer.concat([buffered, chunk])
396
+ const end = buffered.indexOf('\r\n\r\n')
397
+ if (end === -1) {
398
+ return
399
+ }
400
+ upstream.off('data', onData)
401
+ const headLines = buffered.subarray(0, end).toString('latin1').split('\r\n')
402
+ const rest = buffered.subarray(end + 4)
403
+ const setCookies = headLines.filter((line) => /^set-cookie:/i.test(line)).map((line) => line.slice(line.indexOf(':') + 1).trim())
404
+ jar.store(new URL(`${secure ? 'https' : 'http'}://${target.host}${target.pathname}`), setCookies)
405
+ const forwarded = headLines.filter((line) => !/^set-cookie:/i.test(line))
406
+ client.write(`${forwarded.join('\r\n')}\r\n\r\n`)
407
+ if (!/^HTTP\/1\.1 101/.test(headLines[0] ?? '')) {
408
+ client.end(rest)
409
+ upstream.destroy()
410
+ return
411
+ }
412
+ if (rest.length > 0) {
413
+ client.write(rest)
414
+ }
415
+ upstream.pipe(client)
416
+ client.pipe(upstream)
417
+ }
418
+ upstream.on('data', onData)
419
+ upstream.on('close', () => client.destroy())
420
+ client.on('close', () => upstream.destroy())
421
+ }
@@ -0,0 +1,253 @@
1
+ import { existsSync, watch } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import path from 'node:path'
4
+ import react from '@vitejs/plugin-react'
5
+ import { createServer, type InlineConfig, mergeConfig, type Plugin, searchForWorkspaceRoot, type ViteDevServer } from 'vite'
6
+ import { DEFAULT_DEVICE_ID, DEVICES } from '../devices/catalog.ts'
7
+ import type { Platform } from '../devices/types.ts'
8
+ import { appPage, assetRequires } from './appSource.ts'
9
+ import { loadProject, type Project } from './config.ts'
10
+ import { defineOverrides } from './overrides/define.ts'
11
+ import { overridesEsbuild, overridesPlugin } from './overrides/plugin.ts'
12
+ import { OverrideRegistry } from './overrides/registry.ts'
13
+ import { BUILT_IN_OVERRIDES, BUILT_IN_PLUGINS, CLIENT_ENTRY, PACKAGE_ROOT, SHELL_API_ENTRY } from './paths.ts'
14
+ import { controlChannel } from './control.ts'
15
+ import { appProxy } from './proxy.ts'
16
+ import { EventStore, eventsChannel } from './events/store.ts'
17
+ import { type LoadedPlugin, loadPlugins } from './plugins.ts'
18
+ import { PlatformScope } from './platform.ts'
19
+
20
+ export const DEFAULT_PORT = 5310
21
+
22
+ /** Libraries resolve their web builds: `.web.tsx` before `.tsx`. */
23
+ const WEB_EXTENSIONS = ['.web.tsx', '.web.ts', '.web.mjs', '.web.js', '.web.jsx', '.tsx', '.ts', '.mjs', '.js', '.jsx', '.json']
24
+
25
+ export type SimContext = {
26
+ project: Project
27
+ registry: OverrideRegistry
28
+ scope: PlatformScope
29
+ plugins: LoadedPlugin[]
30
+ }
31
+
32
+ export async function loadContext(projectRoot: string): Promise<SimContext> {
33
+ const project = await loadProject(projectRoot)
34
+ const { config } = project
35
+ const plugins = await loadPlugins({
36
+ projectRoot,
37
+ builtInDir: BUILT_IN_PLUGINS,
38
+ configured: config.plugins ?? [],
39
+ configFile: project.configFile,
40
+ disabled: config.disablePlugins ?? [],
41
+ })
42
+ const registry = await OverrideRegistry.load(
43
+ [
44
+ { dir: path.resolve(projectRoot, config.overridesDir ?? 'web-sim/overrides'), origin: 'project' },
45
+ ...plugins.flatMap((plugin) => (plugin.overridesDir !== null ? [{ dir: plugin.overridesDir, origin: plugin.origin === 'config' ? ('project' as const) : ('built-in' as const) }] : [])),
46
+ { dir: BUILT_IN_OVERRIDES, origin: 'built-in' },
47
+ ],
48
+ [
49
+ ...(config.overrides ?? []),
50
+ ...(config.stub ?? []).map((name) => defineOverrides(name, [{ versions: '*', stub: true, note: 'stub in web-sim.config' }])),
51
+ ],
52
+ )
53
+ registry.devicePlatformPackages = new Set(config.devicePlatform ?? [])
54
+ for (const plugin of plugins) {
55
+ if (plugin.dir !== null) {
56
+ registry.addHashedDir(plugin.dir)
57
+ }
58
+ }
59
+ const devices = [...DEVICES, ...(config.devices ?? [])]
60
+ const defaultDevice = devices.find((device) => device.id === (config.defaultDevice ?? DEFAULT_DEVICE_ID)) ?? devices[0]
61
+ const scope = new PlatformScope(projectRoot, defaultDevice.platform, config.resolveNativeFiles ?? true, (file) => registry.seesDevicePlatform(file))
62
+ return { project, registry, scope, plugins }
63
+ }
64
+
65
+ /** Where a dev server keeps its event log: one directory per port, as Vite keeps one pre-bundle per port. */
66
+ export function eventsDir(projectRoot: string, port: number): string {
67
+ return path.join(projectRoot, 'node_modules', '.cache', 'web-sim', String(port))
68
+ }
69
+
70
+ export async function createSimServer(context: SimContext, port: number, events = new EventStore(eventsDir(context.project.root, port))): Promise<ViteDevServer> {
71
+ const { project, registry, scope, plugins } = context
72
+ const { config } = project
73
+ const devices = [...DEVICES, ...(config.devices ?? [])]
74
+ const defaultDevice = config.defaultDevice ?? DEFAULT_DEVICE_ID
75
+
76
+ registry.onWarning = (warning) => console.warn(`\x1b[33mweb-sim\x1b[0m ${warning.message}`)
77
+
78
+ const requireFromProject = createRequire(path.join(project.root, 'package.json'))
79
+ const babelPlugins = [...(config.babelPlugins ?? [])]
80
+ try {
81
+ babelPlugins.push(requireFromProject.resolve('react-native-worklets/plugin'))
82
+ } catch {
83
+ // Not a Reanimated 4 app.
84
+ }
85
+
86
+ const sourceDefines = {
87
+ __DEV__: 'true',
88
+ global: 'globalThis',
89
+ 'process.env.NODE_ENV': JSON.stringify('development'),
90
+ 'process.env.EXPO_OS': JSON.stringify('web'),
91
+ 'process.env': JSON.stringify({ NODE_ENV: 'development', EXPO_OS: 'web', ...project.env }),
92
+ __WEB_SIM_PROXY__: JSON.stringify(config.proxy !== false),
93
+ }
94
+
95
+ const vite: InlineConfig = {
96
+ configFile: false,
97
+ root: project.root,
98
+ // One pre-bundle per port, so two simulators can serve one app at once.
99
+ cacheDir: path.join(project.root, 'node_modules', '.vite', `web-sim-${port}`),
100
+ appType: 'custom',
101
+ clearScreen: false,
102
+ plugins: [
103
+ appPage(project, { devices, defaultDevice, plugins }),
104
+ controlChannel(events),
105
+ ...(config.proxy === false ? [] : [appProxy(path.join(project.root, 'node_modules', '.cache', 'web-sim', 'cookies.json'))]),
106
+ eventsChannel(events),
107
+ ...plugins.flatMap((plugin) => plugin.vite ?? []),
108
+ scope.vitePlugin(),
109
+ overridesPlugin(registry),
110
+ assetRequires(scope),
111
+ platformChannel(scope),
112
+ metroSockets(),
113
+ react({
114
+ babel: (id) => ({ plugins: scope.isAppSource(id.split('?')[0]) ? babelPlugins : [] }) as never,
115
+ }),
116
+ ],
117
+ define: sourceDefines,
118
+ resolve: {
119
+ // Hooks only work against the React that is rendering, so every import reaches the app's copy.
120
+ dedupe: ['react', 'react-dom', 'react-native-web'],
121
+ extensions: WEB_EXTENSIONS,
122
+ alias: [{ find: /^web-sim\/shell$/, replacement: SHELL_API_ENTRY }, ...project.aliases],
123
+ },
124
+ optimizeDeps: {
125
+ entries: [
126
+ CLIENT_ENTRY,
127
+ ...(project.routesDir !== null ? [`${project.routesDir.slice(1)}/**/*.{ts,tsx,js,jsx}`] : []),
128
+ ...(project.entry !== null ? [project.entry.slice(1)] : []),
129
+ ],
130
+ include: ['react', 'react-dom', 'react-dom/client', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'react-native-web'],
131
+ // web-sim's own source, served as it is. Installed (in node_modules), Vite would otherwise pre-bundle it once a
132
+ // panel imports it, and reload the page the first time.
133
+ exclude: ['web-sim/shell'],
134
+ esbuildOptions: {
135
+ plugins: [scope.esbuildPlugin(), overridesEsbuild(registry)],
136
+ loader: { '.js': 'jsx' },
137
+ resolveExtensions: WEB_EXTENSIONS,
138
+ define: {
139
+ __DEV__: 'true',
140
+ global: 'globalThis',
141
+ 'process.env.NODE_ENV': JSON.stringify('development'),
142
+ 'process.env.EXPO_OS': JSON.stringify('web'),
143
+ 'process.env': JSON.stringify({ NODE_ENV: 'development', EXPO_OS: 'web', ...project.env }),
144
+ },
145
+ },
146
+ },
147
+ server: {
148
+ port,
149
+ strictPort: true,
150
+ fs: { allow: [searchForWorkspaceRoot(project.root), PACKAGE_ROOT] },
151
+ // DevTools skips web-sim's own frames, so a console.log the app makes points at the app, not at the wrapper that
152
+ // logs it. A linked install of web-sim resolves outside node_modules, which Vite's default misses.
153
+ sourcemapIgnoreList: (sourcePath, sourcemapPath) =>
154
+ sourcePath.includes('node_modules') || path.resolve(path.dirname(sourcemapPath), sourcePath).startsWith(PACKAGE_ROOT),
155
+ },
156
+ }
157
+ const server = await createServer(config.vite ? mergeConfig(vite, config.vite) : vite)
158
+ await server.listen()
159
+ return server
160
+ }
161
+
162
+ /**
163
+ * Expo's dev-mode client opens Metro's sockets (`/hot` for fast refresh, `/message` for dev tools), which this server
164
+ * doesn't have. Left unanswered, each stays connecting for good, and Chrome opens one WebSocket to a host at a time,
165
+ * so every later socket to the dev server (the app's proxied ones too) would wait behind them. They are turned away
166
+ * at once.
167
+ */
168
+ function metroSockets(): Plugin {
169
+ return {
170
+ name: 'web-sim:metro-sockets',
171
+ configureServer(server) {
172
+ server.httpServer?.on('upgrade', (req, socket) => {
173
+ const path = (req.url ?? '').split('?')[0]
174
+ if (path === '/hot' || path === '/message' || path === '/debugger-proxy' || path.startsWith('/inspector')) {
175
+ socket.end('HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
176
+ }
177
+ })
178
+ },
179
+ }
180
+ }
181
+
182
+ /**
183
+ * The shell tells the server which platform the device it shows runs, before it loads the app, so app files resolve
184
+ * for that platform.
185
+ */
186
+ function platformChannel(scope: PlatformScope): Plugin {
187
+ return {
188
+ name: 'web-sim:platform-channel',
189
+ configureServer(server) {
190
+ server.ws.on('web-sim:platform', (data: { platform: Platform }, client) => {
191
+ const changed = scope.setPlatform(data.platform)
192
+ if (changed) {
193
+ server.config.logger.info(`\x1b[36mweb-sim\x1b[0m app code now resolves for ${data.platform}`, { timestamp: true })
194
+ }
195
+ client.send('web-sim:platform-ready', { platform: scope.platform })
196
+ })
197
+ },
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Runs the dev server, and starts it again when an override or the config changes: overrides decide what the
203
+ * pre-bundle holds, so they are read once per server.
204
+ */
205
+ export async function runDevServer(projectRoot: string, options: { port?: number }): Promise<void> {
206
+ let context = await loadContext(projectRoot)
207
+ const port = options.port ?? context.project.config.port ?? DEFAULT_PORT
208
+ // One log for the life of the process, across the restarts below.
209
+ const events = new EventStore(eventsDir(projectRoot, port))
210
+ let server = await createSimServer(context, port, events)
211
+ printBanner(context, port)
212
+
213
+ const watched = [
214
+ path.resolve(projectRoot, context.project.config.overridesDir ?? 'web-sim/overrides'),
215
+ BUILT_IN_OVERRIDES,
216
+ BUILT_IN_PLUGINS,
217
+ ...(context.project.configFile !== null ? [context.project.configFile] : []),
218
+ ].filter((target) => existsSync(target))
219
+
220
+ let timer: NodeJS.Timeout | undefined
221
+ let restarting = Promise.resolve()
222
+ const restart = (reason: string) => {
223
+ clearTimeout(timer)
224
+ timer = setTimeout(() => {
225
+ restarting = restarting.then(async () => {
226
+ console.log(`\x1b[36mweb-sim\x1b[0m ${reason} changed, restarting`)
227
+ const platform = context.scope.platform
228
+ await server.close()
229
+ try {
230
+ context = await loadContext(projectRoot)
231
+ context.scope.platform = platform
232
+ server = await createSimServer(context, port, events)
233
+ } catch (error) {
234
+ console.error(error)
235
+ }
236
+ })
237
+ }, 150)
238
+ }
239
+ for (const target of watched) {
240
+ watch(target, { recursive: true }, (_, file) => restart(path.relative(projectRoot, path.join(target, file ?? ''))))
241
+ }
242
+ }
243
+
244
+ function printBanner(context: SimContext, port: number) {
245
+ const { project, registry } = context
246
+ const mode = project.routesDir !== null ? `expo-router app in ${project.routesDir.slice(1)}` : `entry ${project.entry?.slice(1)}`
247
+ console.log(`
248
+ \x1b[1mweb-sim\x1b[0m ${project.name} (${mode})
249
+ \x1b[36mhttp://localhost:${port}/\x1b[0m
250
+ ${registry.packages().length} packages with overrides
251
+ plugins: ${context.plugins.filter((plugin) => plugin.active).map((plugin) => plugin.name).join(', ') || 'none'}
252
+ `)
253
+ }