@a16n/web-sim 0.0.0-stage → 0.1.1

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 (281) 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 +157 -0
  71. package/overrides/react-native-web/useElementLayout.ts +152 -0
  72. package/package.json +80 -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 +129 -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 +76 -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 +23 -0
  250. package/src/devices/catalog.ts +223 -0
  251. package/src/devices/types.ts +83 -0
  252. package/src/node/appInfo.ts +188 -0
  253. package/src/node/appSource.ts +140 -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/fonts.ts +377 -0
  261. package/src/node/index.ts +5 -0
  262. package/src/node/overrides/define.ts +56 -0
  263. package/src/node/overrides/packages.ts +136 -0
  264. package/src/node/overrides/platformPatch.ts +56 -0
  265. package/src/node/overrides/plugin.ts +169 -0
  266. package/src/node/overrides/registry.ts +258 -0
  267. package/src/node/paths.ts +18 -0
  268. package/src/node/platform.ts +171 -0
  269. package/src/node/plugins.ts +98 -0
  270. package/src/node/proxy.ts +421 -0
  271. package/src/node/server.ts +254 -0
  272. package/src/node/worklets.ts +86 -0
  273. package/src/plugin/index.ts +33 -0
  274. package/src/plugin/types.ts +127 -0
  275. package/src/plugin/ui.tsx +562 -0
  276. package/src/runtime/clock.ts +112 -0
  277. package/src/runtime/draw.ts +196 -0
  278. package/src/runtime/index.ts +519 -0
  279. package/src/runtime/media.ts +379 -0
  280. package/src/runtime/records.ts +76 -0
  281. package/src/runtime/timezone.ts +81 -0
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @a16n/web-sim
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A React Native device simulator that runs in a Chrome tab: your app's real code on Vite and react-native-web, inside a
4
+ drawn iPhone or Android device.
5
+
6
+ ```sh
7
+ pnpm dlx @a16n/web-sim dev # in an Expo or React Native app: http://localhost:5310
8
+ pnpm dlx @a16n/web-sim doctor # how each dependency runs in the simulator
9
+ pnpm dlx @a16n/web-sim --help
10
+ ```
11
+
12
+ Needs Node 22.18 or later. The app brings its own React, react-native-web and Expo; web-sim uses the app's copies.
13
+
14
+ See https://github.com/a16n-dev/web-sim for how it works, configuration, overrides and plugins.
package/bin/cli.ts ADDED
@@ -0,0 +1,255 @@
1
+ import { type ChildProcess, spawn } from 'node:child_process'
2
+ import { watch } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { parseArgs } from 'node:util'
6
+ import { DEVICES } from '../src/devices/catalog.ts'
7
+ import { diagnose, printDiagnosis } from '../src/node/doctor.ts'
8
+ import { CONTROL_PATH, type ControlCommand } from '../src/node/control.ts'
9
+ import { loadConfig } from '../src/node/config.ts'
10
+ import { isCliError, logsCommand, waitCommand } from '../src/node/events/cli.ts'
11
+ import { DEFAULT_PORT, loadContext, runDevServer } from '../src/node/server.ts'
12
+
13
+ const HELP = `web-sim — a React Native device simulator in a Chrome tab
14
+
15
+ Usage: web-sim <command> [options]
16
+
17
+ Commands:
18
+ dev Start the simulator for the app in the current directory
19
+ --port <n> Port (default 5310, or 'port' in web-sim.config.ts)
20
+ --open Open it in the browser
21
+ doctor How each dependency runs in the simulator
22
+ --all Include plain JS packages
23
+ devices List the built-in devices
24
+
25
+ Controlling the open simulator tab (the dev server must be running):
26
+ plugins The loaded plugins, their actions and state
27
+ state [plugin] The simulator's state, or one plugin's ('sim' is the simulator itself)
28
+ set <plugin> key=value...
29
+ Change a plugin's state. Values are JSON when they parse, else strings:
30
+ web-sim set battery level=0.15 power=charging
31
+ web-sim set sim device=pixel-9 appearance=dark
32
+ web-sim set sim device=iphone-resizable width=430 height=700
33
+ run <plugin> <action> [json]
34
+ Run a plugin's action: web-sim run battery animate '{"to":0.05,"seconds":5}'
35
+ web-sim run clock set '{"time":"2026-12-25T08:00"}'
36
+ web-sim run clock advance '{"hours":1}'
37
+ --port <n> The dev server's port
38
+
39
+ The event log (kept by the dev server, also after the tab closes):
40
+ logs [kind...] The newest events. A kind is a glob: network (network.*), 'ui.dialog.*', console, '*.state'.
41
+ Without a kind, debug events (state changes, console.debug) are left out.
42
+ --level <l> The lowest level: debug, info, warn, error
43
+ --since <t> An event id, a time back from now (30s, 5m, 2h), or now (also --until)
44
+ --run <r> current, previous, or a run's number (each app launch or reload is a run)
45
+ --actor <a> app, user, cli, system (comma-separated)
46
+ --span <s> One request, dialog, command or action, and what it caused
47
+ --where <cond> path<op>value on the event's data, repeatable: --where 'status>=400' --where url~/api
48
+ (operators = != > >= < <= ~)
49
+ --text <t> Text in the summary or the data
50
+ --limit <n> How many, newest last (default 50)
51
+ -f, --follow Keep printing new events
52
+ --json One JSON event per line
53
+ --kinds The kinds seen so far, with counts
54
+ --clear Empty the log
55
+ wait <kind> Wait for a matching event, print it and exit 0; exit 1 at the timeout. Takes the same filters,
56
+ and also an event that came since the last CLI command, so this holds even if the banner won:
57
+ web-sim run notifications push '{"title":"Hi"}' && web-sim wait ui.banner.shown
58
+ --timeout <t> Default 10s
59
+ --since now Only events from now on
60
+
61
+ Options:
62
+ --root <dir> The app's directory (default: the current directory)
63
+ -h, --help Show this help
64
+ `
65
+
66
+ const { positionals, values } = parseArgs({
67
+ allowPositionals: true,
68
+ options: {
69
+ port: { type: 'string' },
70
+ open: { type: 'boolean' },
71
+ all: { type: 'boolean' },
72
+ root: { type: 'string' },
73
+ help: { type: 'boolean', short: 'h' },
74
+ level: { type: 'string' },
75
+ since: { type: 'string' },
76
+ until: { type: 'string' },
77
+ run: { type: 'string' },
78
+ actor: { type: 'string' },
79
+ span: { type: 'string' },
80
+ where: { type: 'string', multiple: true },
81
+ text: { type: 'string' },
82
+ limit: { type: 'string' },
83
+ json: { type: 'boolean' },
84
+ follow: { type: 'boolean', short: 'f' },
85
+ kinds: { type: 'boolean' },
86
+ clear: { type: 'boolean' },
87
+ timeout: { type: 'string' },
88
+ },
89
+ })
90
+
91
+ const root = path.resolve(values.root ?? process.cwd())
92
+ const [command] = positionals
93
+
94
+ switch (command) {
95
+ case 'dev': {
96
+ const port = values.port === undefined ? undefined : Number(values.port)
97
+ if (process.env.WEB_SIM_SERVER !== '1') {
98
+ // The server runs in a child process, started again when web-sim's own code changes: Node can't reload modules
99
+ // it has loaded, and a server left running across an edit to web-sim would mix old code with new files.
100
+ superviseServer()
101
+ } else {
102
+ await runDevServer(root, { port })
103
+ }
104
+ if (values.open && process.env.WEB_SIM_SERVER !== '1') {
105
+ const { exec } = await import('node:child_process')
106
+ exec(`open http://localhost:${port ?? 5310}/`)
107
+ }
108
+ break
109
+ }
110
+ case 'doctor': {
111
+ const context = await loadContext(root)
112
+ process.exitCode = printDiagnosis(diagnose(context), values.all ?? false)
113
+ break
114
+ }
115
+ case 'devices': {
116
+ for (const device of DEVICES) {
117
+ console.log(
118
+ `${device.id.padEnd(20)} ${device.label.padEnd(22)} ${device.platform.padEnd(8)} ${device.screen.width}×${device.screen.height} @${device.pixelRatio}x`,
119
+ )
120
+ }
121
+ break
122
+ }
123
+ case 'plugins':
124
+ await control({ type: 'plugins' })
125
+ break
126
+ case 'state':
127
+ await control({ type: 'state', plugin: positionals[1] })
128
+ break
129
+ case 'set': {
130
+ const [, plugin, ...pairs] = positionals
131
+ if (plugin === undefined || pairs.length === 0) {
132
+ fail('Usage: web-sim set <plugin> key=value...')
133
+ }
134
+ const patch = Object.fromEntries(
135
+ pairs.map((pair) => {
136
+ const at = pair.indexOf('=')
137
+ if (at < 1) {
138
+ fail(`'${pair}' is not key=value`)
139
+ }
140
+ return [pair.slice(0, at), parseValue(pair.slice(at + 1))]
141
+ }),
142
+ )
143
+ await control({ type: 'set', plugin, patch })
144
+ break
145
+ }
146
+ case 'run': {
147
+ const [, plugin, action, args] = positionals
148
+ if (plugin === undefined || action === undefined) {
149
+ fail('Usage: web-sim run <plugin> <action> [json]')
150
+ }
151
+ await control({ type: 'run', plugin, action, args: args === undefined ? undefined : parseValue(args) })
152
+ break
153
+ }
154
+ case 'logs':
155
+ case 'wait':
156
+ try {
157
+ const base = `http://localhost:${await devServerPort()}`
158
+ if (command === 'logs') {
159
+ await logsCommand(base, positionals.slice(1), values)
160
+ } else if (!(await waitCommand(base, positionals.slice(1), values))) {
161
+ process.exitCode = 1
162
+ }
163
+ } catch (error) {
164
+ if (!isCliError(error)) {
165
+ throw error
166
+ }
167
+ fail(error.message)
168
+ }
169
+ break
170
+ default:
171
+ console.log(HELP)
172
+ process.exitCode = command === undefined || values.help ? 0 : 1
173
+ }
174
+
175
+ function parseValue(text: string): unknown {
176
+ try {
177
+ return JSON.parse(text)
178
+ } catch {
179
+ return text
180
+ }
181
+ }
182
+
183
+ function fail(message: string): never {
184
+ console.error(message)
185
+ process.exit(1)
186
+ }
187
+
188
+ /** The dev server's port: --port, else the config's, else the default. */
189
+ async function devServerPort(): Promise<number> {
190
+ return values.port !== undefined ? Number(values.port) : ((await loadConfig(root)).config.port ?? DEFAULT_PORT)
191
+ }
192
+
193
+ /** Sends a command to the dev server, which relays it to the simulator tab, and prints the answer as JSON. */
194
+
195
+ async function control(command: ControlCommand): Promise<void> {
196
+ const serverPort = await devServerPort()
197
+ let response: Response
198
+ try {
199
+ response = await fetch(`http://localhost:${serverPort}${CONTROL_PATH}`, { method: 'POST', body: JSON.stringify(command) })
200
+ } catch {
201
+ fail(`No web-sim dev server on port ${serverPort}. Start one with 'web-sim dev', or pass --port.`)
202
+ }
203
+ const reply = (await response.json()) as { ok: boolean; result?: unknown; error?: string }
204
+ if (!reply.ok) {
205
+ fail(reply.error ?? 'failed')
206
+ }
207
+ console.log(JSON.stringify(reply.result, null, 2))
208
+ }
209
+
210
+ /** Runs `web-sim dev` in a child process, and runs it again when web-sim's Node code (`src/node`, `src/devices`) changes. */
211
+ function superviseServer(): void {
212
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
213
+ let child: ChildProcess | null = null
214
+ const start = () => {
215
+ child = spawn(process.execPath, [...process.execArgv, ...process.argv.slice(1)], {
216
+ stdio: 'inherit',
217
+ env: { ...process.env, WEB_SIM_SERVER: '1' },
218
+ })
219
+ child.on('exit', (code, signal) => {
220
+ if (signal === null && !restarting) {
221
+ process.exit(code ?? 0)
222
+ }
223
+ })
224
+ }
225
+ let restarting = false
226
+ let timer: NodeJS.Timeout | undefined
227
+ const restart = (file: string) => {
228
+ clearTimeout(timer)
229
+ timer = setTimeout(() => {
230
+ console.log(`\x1b[36mweb-sim\x1b[0m ${file} changed, starting the server again`)
231
+ restarting = true
232
+ const running = child
233
+ if (running === null || running.exitCode !== null) {
234
+ restarting = false
235
+ start()
236
+ return
237
+ }
238
+ running.once('exit', () => {
239
+ restarting = false
240
+ start()
241
+ })
242
+ running.kill()
243
+ }, 200)
244
+ }
245
+ for (const dir of ['src/node', 'src/devices']) {
246
+ watch(path.join(packageRoot, dir), { recursive: true }, (_, file) => restart(path.join(dir, file ?? '')))
247
+ }
248
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
249
+ process.on(signal, () => {
250
+ child?.kill(signal)
251
+ process.exit(0)
252
+ })
253
+ }
254
+ start()
255
+ }
package/bin/web-sim.js ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // web-sim's Node code is TypeScript, run as it is. Node strips types itself, except from files under node_modules,
3
+ // which is where an installed web-sim lives (`pnpm dlx`, `pnpm add -D`): there, this strips them. It also lets a
4
+ // project's `web-sim.config.ts` and overrides import `web-sim` without installing it, as with `pnpm dlx`.
5
+ import { readFileSync } from 'node:fs'
6
+ import { registerHooks } from 'node:module'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const ROOT = new URL('../', import.meta.url)
10
+ const { name } = JSON.parse(readFileSync(new URL('package.json', ROOT), 'utf8'))
11
+ const INSTALLED = fileURLToPath(ROOT).split(/[\\/]/).includes('node_modules')
12
+ const SELF = new URL('package.json', ROOT).href
13
+ const NAMES = [...new Set([name, 'web-sim'])]
14
+
15
+ let transformSync
16
+ if (INSTALLED) {
17
+ ;({ transformSync } = await import('esbuild'))
18
+ }
19
+
20
+ registerHooks({
21
+ resolve(specifier, context, nextResolve) {
22
+ // `web-sim` and `web-sim/...` are this copy of web-sim, whatever the package is published as.
23
+ const own = NAMES.find((pkg) => specifier === pkg || specifier.startsWith(`${pkg}/`))
24
+ if (own !== undefined) {
25
+ return nextResolve(name + specifier.slice(own.length), { ...context, parentURL: SELF })
26
+ }
27
+ return nextResolve(specifier, context)
28
+ },
29
+ load(url, context, nextLoad) {
30
+ if (INSTALLED && url.startsWith(ROOT.href) && /\.m?ts(\?|$)/.test(url)) {
31
+ const file = fileURLToPath(url.split('?')[0])
32
+ const { code } = transformSync(readFileSync(file, 'utf8'), { loader: 'ts', format: 'esm', sourcefile: file, sourcemap: 'inline' })
33
+ return { format: 'module', source: code, shortCircuit: true }
34
+ }
35
+ return nextLoad(url, context)
36
+ },
37
+ })
38
+
39
+ await import('./cli.ts')
@@ -0,0 +1,15 @@
1
+ import { defineOverrides } from '../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('@backpackapp-io/react-native-toast', [
4
+ {
5
+ versions: '>=0.13 <0.14',
6
+ note: 'a type re-exported as a value, which esbuild rejects',
7
+ patch: [
8
+ // `ToastAnimationType` is a TypeScript type. Metro's Babel leaves it undefined; esbuild refuses to bundle it.
9
+ {
10
+ file: 'lib/module/index.js',
11
+ replace: (source) => source.replace('export { ToastPosition, ToastAnimationType }', 'export { ToastPosition }'),
12
+ },
13
+ ],
14
+ },
15
+ ])
@@ -0,0 +1,34 @@
1
+ import { defineOverrides } from '../../../src/node/overrides/define.ts'
2
+
3
+ /**
4
+ * On a phone the default Firebase app exists before any JS runs, made by the native SDK from GoogleService-Info.plist
5
+ * or google-services.json. The web build has no native apps, so `getApp()` throws unless the app calls
6
+ * `initializeApp` itself, which native apps never do. This gives the web build the same default app, from the same
7
+ * files.
8
+ */
9
+ const NATIVE_APPS = `(() => {
10
+ const services = __webSim.app().googleServices ?? {};
11
+ const options = services[__webSim.getState().device.platform];
12
+ if (options === undefined || options.appId === undefined) {
13
+ return [];
14
+ }
15
+ const { clientId, ...webOptions } = options;
16
+ if (!getApps().some((existing) => existing.name === '[DEFAULT]')) {
17
+ initializeApp(webOptions, { name: '[DEFAULT]' });
18
+ }
19
+ return [{ appConfig: { name: '[DEFAULT]', automaticDataCollectionEnabled: true, automaticResourceManagement: false }, options }];
20
+ })()`
21
+
22
+ export default defineOverrides('@react-native-firebase/app', [
23
+ {
24
+ versions: '>=27 <28',
25
+ note: 'the default app made from the app’s Firebase config files, as the native SDK makes it',
26
+ patch: [
27
+ {
28
+ file: 'dist/module/internal/web/RNFBAppModule.js',
29
+ replace: (source) =>
30
+ `import * as __webSim from 'web-sim/runtime';\n${source.replace('NATIVE_FIREBASE_APPS: [],', `NATIVE_FIREBASE_APPS: ${NATIVE_APPS},`)}`,
31
+ },
32
+ ],
33
+ },
34
+ ])
@@ -0,0 +1,29 @@
1
+ import { log, requestPermission } from 'web-sim/runtime'
2
+
3
+ function record(summary: string, data?: unknown): Promise<null> {
4
+ log('analytics.tiktok', `TikTok: ${summary}`, data)
5
+ return Promise.resolve(null)
6
+ }
7
+
8
+ /**
9
+ * The TikTok Business SDK's native module. Each call resolves as the SDK would and is logged as an
10
+ * `analytics.tiktok` event, so a test can check what the app reported; nothing reaches TikTok.
11
+ */
12
+ export default {
13
+ initialize: (config: { appId?: string }) => {
14
+ log('analytics.tiktok', 'TikTok: initialize', { appId: config.appId })
15
+ return Promise.resolve({ success: true, message: 'Initialized' })
16
+ },
17
+ trackEvent: (name: string, properties?: unknown) => record(name, properties),
18
+ trackContentEvent: (name: string, properties?: unknown) => record(name, properties),
19
+ trackCustomEvent: (name: string, properties?: unknown) => record(name, properties),
20
+ trackAdRevenueEvent: (properties?: unknown) => record('ad revenue', properties),
21
+ startTrack: () => record('start tracking'),
22
+ flush: () => record('flush'),
23
+ identify: (payload?: unknown) => record('identify', payload),
24
+ logout: () => record('logout'),
25
+ fetchDeferredDeeplink: () => Promise.resolve({}),
26
+ trackGooglePlayPurchase: (payload?: unknown) => record('Google Play purchase', payload),
27
+ /** iOS's App Tracking Transparency prompt, shared with expo-tracking-transparency. */
28
+ requestTrackingAuthorization: async () => ((await requestPermission('tracking')).granted ? 'authorized' : 'denied'),
29
+ }
@@ -0,0 +1,9 @@
1
+ import { defineOverrides } from '../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('@tiktok-for-business/react-native-sdk', [
4
+ {
5
+ versions: '>=0.1.3 <0.2',
6
+ note: 'calls answered and logged as analytics events, sending nothing; the package has no web build',
7
+ files: { 'lib/module/NativeTiktokBusinessReactNativeSdk.js': './NativeTiktokSdk.ts' },
8
+ },
9
+ ])
@@ -0,0 +1,81 @@
1
+ import { app, platform } from 'web-sim/runtime'
2
+
3
+ /** `ApplicationReleaseType.DEVELOPMENT`: a development build installed on the phone. */
4
+ const DEVELOPMENT = 3
5
+
6
+ /** A value made once per app and kept in localStorage, as the OS keeps it until the app is deleted. */
7
+ function kept(name: string, create: () => string): string {
8
+ const key = `web-sim:expo-application:${app().slug}:${name}`
9
+ try {
10
+ const stored = localStorage.getItem(key)
11
+ if (stored !== null) {
12
+ return stored
13
+ }
14
+ const value = create()
15
+ localStorage.setItem(key, value)
16
+ return value
17
+ } catch {
18
+ return create()
19
+ }
20
+ }
21
+
22
+ function hex(length: number): string {
23
+ return Array.from(crypto.getRandomValues(new Uint8Array(length / 2)), (byte) => byte.toString(16).padStart(2, '0')).join('')
24
+ }
25
+
26
+ function installationTime(): number {
27
+ return Number(kept('installed', () => String(Date.now())))
28
+ }
29
+
30
+ /**
31
+ * `ExpoApplication` as the simulated phone answers for the app in `app.json`: its name, the platform's bundle ID or
32
+ * package, `version`, and the iOS `buildNumber` or Android `versionCode`.
33
+ */
34
+ function createModule() {
35
+ const info = app()
36
+ const config = info.config ?? {}
37
+ const ios = platform() === 'ios'
38
+ const applicationId = ios
39
+ ? (config.ios?.bundleIdentifier ?? config.android?.package ?? info.bundleId)
40
+ : (config.android?.package ?? config.ios?.bundleIdentifier ?? info.bundleId)
41
+ const common = {
42
+ applicationName: info.name,
43
+ applicationId,
44
+ // Read by older versions of the JS layer.
45
+ bundleId: applicationId,
46
+ nativeApplicationVersion: info.version,
47
+ nativeBuildVersion: ios ? String(config.ios?.buildNumber ?? '1') : String(config.android?.versionCode ?? 1),
48
+ async getInstallationTimeAsync() {
49
+ return installationTime()
50
+ },
51
+ }
52
+ if (ios) {
53
+ return {
54
+ ...common,
55
+ async getIosIdForVendorAsync() {
56
+ return kept('idfv', () => crypto.randomUUID().toUpperCase())
57
+ },
58
+ async getApplicationReleaseTypeAsync() {
59
+ return DEVELOPMENT
60
+ },
61
+ async getStoreEnvironmentAsync() {
62
+ return 'xcode'
63
+ },
64
+ async getPushNotificationServiceEnvironmentAsync() {
65
+ return 'development'
66
+ },
67
+ }
68
+ }
69
+ return {
70
+ ...common,
71
+ androidId: kept('android-id', () => hex(16)),
72
+ async getInstallReferrerAsync() {
73
+ return 'utm_source=google-play&utm_medium=organic'
74
+ },
75
+ async getLastUpdateTimeAsync() {
76
+ return installationTime()
77
+ },
78
+ }
79
+ }
80
+
81
+ export default createModule()
@@ -0,0 +1,16 @@
1
+ import { defineOverrides } from '../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-application', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: 'the app’s ID, version and build from app.json; Android ID and install time kept per app',
7
+ files: { 'build/ExpoApplication.web.js': './ExpoApplication.ts' },
8
+ patch: [
9
+ {
10
+ // `getAndroidId` checks `Platform.OS`, which is 'web' inside dependencies: ask the module instead.
11
+ file: 'build/Application.js',
12
+ replace: (source) => source.replace("if (Platform.OS !== 'android') {", 'if (ExpoApplication.androidId == null) {'),
13
+ },
14
+ ],
15
+ },
16
+ ])
@@ -0,0 +1,30 @@
1
+ import { sessionValue } from 'web-sim/runtime'
2
+
3
+ type RegisteredTask = { taskName: string; taskType: string; options: Record<string, unknown> }
4
+
5
+ /** The task manager's registry (expo-task-manager's override keeps it under the same key). */
6
+ function registeredTasks(): Map<string, RegisteredTask> {
7
+ return sessionValue('expo-task-manager.tasks', () => new Map<string, RegisteredTask>())
8
+ }
9
+
10
+ /** BackgroundTaskStatus.Available. */
11
+ const AVAILABLE = 2
12
+
13
+ export default {
14
+ async getStatusAsync() {
15
+ return AVAILABLE
16
+ },
17
+ async registerTaskAsync(taskName: string, options: Record<string, unknown> = {}) {
18
+ registeredTasks().set(taskName, { taskName, taskType: 'backgroundTask', options })
19
+ },
20
+ async unregisterTaskAsync(taskName: string) {
21
+ registeredTasks().delete(taskName)
22
+ },
23
+ async triggerTaskWorkerForTestingAsync() {
24
+ return false
25
+ },
26
+ addListener() {
27
+ return { remove() {} }
28
+ },
29
+ removeListeners() {},
30
+ }
@@ -0,0 +1,9 @@
1
+ import { defineOverrides } from '../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-background-task', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: 'background tasks available and registered with the task manager; the worker never runs them',
7
+ files: { 'build/ExpoBackgroundTaskModule.web.js': './ExpoBackgroundTaskModule.ts' },
8
+ },
9
+ ])
@@ -0,0 +1,66 @@
1
+ import { app, getState, hardware } from 'web-sim/runtime'
2
+
3
+ const IOS_FONTS = [
4
+ 'Academy Engraved LET', 'American Typewriter', 'Arial', 'Arial Hebrew', 'Avenir', 'Avenir Next', 'Baskerville',
5
+ 'Bodoni 72', 'Chalkboard SE', 'Charter', 'Cochin', 'Copperplate', 'Courier New', 'Didot', 'Futura', 'Georgia',
6
+ 'Gill Sans', 'Helvetica', 'Helvetica Neue', 'Hoefler Text', 'Menlo', 'Noteworthy', 'Optima', 'Palatino',
7
+ 'Papyrus', 'Rockwell', 'Savoye LET', 'Snell Roundhand', 'System', 'Times New Roman', 'Trebuchet MS', 'Verdana',
8
+ 'Zapfino',
9
+ ]
10
+
11
+ const ANDROID_FONTS = ['normal', 'notoserif', 'sans-serif', 'sans-serif-light', 'sans-serif-thin', 'sans-serif-condensed', 'sans-serif-medium', 'serif', 'Roboto', 'monospace']
12
+
13
+ /**
14
+ * `ExponentConstants` as a development build on the simulated phone reports it. `Constants.expoConfig` and
15
+ * `Constants.manifest` are the app's `app.json`.
16
+ */
17
+ function createModule() {
18
+ const { device, orientation } = getState()
19
+ const info = hardware(device)
20
+ const ios = device.platform === 'ios'
21
+ const config = app().config ?? { name: app().name, slug: app().slug, version: app().version }
22
+ const scheme = Array.isArray(config.scheme) ? config.scheme[0] : config.scheme
23
+ // iOS hides the status bar in landscape on devices with a cutout.
24
+ const statusBarHeight = ios && orientation === 'landscape' && device.cutout.kind !== 'none' ? 0 : device.statusBarHeight
25
+ const appWindow = window as Window & { __webSimConstantsSession?: string }
26
+ appWindow.__webSimConstantsSession ??= `${Date.now()}-${Math.floor(Math.random() * 1e9)}`
27
+ const userAgent = ios
28
+ ? `Mozilla/5.0 (iPhone; CPU iPhone OS ${device.osVersion.replace(/\./g, '_')} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`
29
+ : `Mozilla/5.0 (Linux; Android ${info.osRelease ?? device.osVersion}; ${info.modelName} Build/${info.osBuildId}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.135 Mobile Safari/537.36`
30
+ return {
31
+ name: 'ExponentConstants',
32
+ appOwnership: null,
33
+ executionEnvironment: 'bare',
34
+ sessionId: appWindow.__webSimConstantsSession,
35
+ isHeadless: false,
36
+ isDetached: false,
37
+ debugMode: true,
38
+ expoVersion: null,
39
+ expoRuntimeVersion: null,
40
+ linkingUri: scheme ? `${scheme}://` : '',
41
+ experienceUrl: '',
42
+ deviceName: ios ? 'iPhone' : info.modelName,
43
+ deviceYearClass: info.yearClass,
44
+ systemVersion: Number.parseFloat(ios ? device.osVersion : (info.osRelease ?? device.osVersion)),
45
+ systemFonts: ios ? IOS_FONTS : ANDROID_FONTS,
46
+ statusBarHeight,
47
+ manifest: config,
48
+ manifest2: null,
49
+ platform: ios
50
+ ? {
51
+ ios: {
52
+ buildNumber: config.ios?.buildNumber ?? '1',
53
+ platform: info.modelId ?? 'iPhone',
54
+ model: info.modelName,
55
+ userInterfaceIdiom: 'handset',
56
+ systemVersion: device.osVersion,
57
+ },
58
+ }
59
+ : { android: { versionCode: config.android?.versionCode ?? 1 } },
60
+ async getWebViewUserAgentAsync() {
61
+ return userAgent
62
+ },
63
+ }
64
+ }
65
+
66
+ export default createModule()
@@ -0,0 +1,9 @@
1
+ import { defineOverrides } from '../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-constants', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: 'app.json as expoConfig; the phone’s status bar, platform block and name',
7
+ files: { 'build/ExponentConstants.web.js': './ExponentConstants.ts' },
8
+ },
9
+ ])