@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,258 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import semver from 'semver'
6
+ import type { OverrideRule, PackageOverrides, SourcePatch } from './define.ts'
7
+ import { RN_APP_SHIM, RUNTIME_ENTRY } from '../paths.ts'
8
+ import { entryFiles, type PackageInfo, packageOfFile } from './packages.ts'
9
+
10
+ export const DEFINITION_FILE = 'overrides.ts'
11
+
12
+ export type OverrideOrigin = 'project' | 'built-in' | 'config'
13
+
14
+ export type LoadedRule = OverrideRule & {
15
+ origin: OverrideOrigin
16
+ /** The file the rule was defined in, which its paths are relative to. */
17
+ definedIn: string
18
+ }
19
+
20
+ /**
21
+ * What loading one file of a package turns into.
22
+ */
23
+ export type FileOverride =
24
+ | { kind: 'replace'; file: string; rule: LoadedRule; info: PackageInfo }
25
+ | { kind: 'stub'; rule: LoadedRule; info: PackageInfo }
26
+ | { kind: 'patch'; patches: SourcePatch[]; rule: LoadedRule; info: PackageInfo; relative: string }
27
+
28
+ export type Warning = { package: string; version: string; message: string }
29
+
30
+ export class OverrideRegistry {
31
+ private readonly byPackage = new Map<string, LoadedRule[]>()
32
+ private readonly ruleCache = new Map<string, LoadedRule | null>()
33
+ private readonly entryCache = new Map<string, Set<string>>()
34
+ readonly warnings = new Map<string, Warning>()
35
+ /** Every file the overrides are made of, for the pre-bundle's hash and the watcher. */
36
+ readonly files: string[] = []
37
+ /** Packages the project's config says see the device's platform, for any version. */
38
+ devicePlatformPackages = new Set<string>()
39
+ private readonly devicePlatformCache = new Map<string, boolean>()
40
+ onWarning: (warning: Warning) => void = () => undefined
41
+
42
+ static async load(dirs: { dir: string; origin: OverrideOrigin }[], extra: PackageOverrides[] = []) {
43
+ const registry = new OverrideRegistry()
44
+ for (const { dir, origin } of dirs) {
45
+ if (!existsSync(dir)) {
46
+ continue
47
+ }
48
+ for (const file of walk(dir)) {
49
+ registry.files.push(file)
50
+ if (path.basename(file) !== DEFINITION_FILE) {
51
+ continue
52
+ }
53
+ // A query per load, because the dev server reloads overrides in the same process and Node caches modules
54
+ // by URL: without it, a restart after an edit would hash the new file but run the old one.
55
+ const module = (await import(`${pathToFileURL(file).href}?v=${Date.now()}`)) as { default?: PackageOverrides | PackageOverrides[] }
56
+ const definitions = Array.isArray(module.default) ? module.default : [module.default]
57
+ for (const definition of definitions) {
58
+ if (definition === undefined || typeof definition.package !== 'string') {
59
+ throw new Error(`${file} must default-export defineOverrides(...)`)
60
+ }
61
+ registry.add(definition, origin, file)
62
+ }
63
+ }
64
+ }
65
+ for (const definition of extra) {
66
+ registry.add(definition, 'config', '')
67
+ }
68
+ return registry
69
+ }
70
+
71
+ /** Counts a folder's files in the hash: a plugin's modules its overrides import. */
72
+ addHashedDir(dir: string): void {
73
+ for (const file of walk(dir)) {
74
+ if (!this.files.includes(file)) {
75
+ this.files.push(file)
76
+ }
77
+ }
78
+ }
79
+
80
+ private add(definition: PackageOverrides, origin: OverrideOrigin, definedIn: string) {
81
+ for (const rule of definition.rules) {
82
+ if (semver.validRange(rule.versions) === null) {
83
+ throw new Error(`${definedIn || 'web-sim.config'}: '${rule.versions}' is not a semver range`)
84
+ }
85
+ }
86
+ const rules = this.byPackage.get(definition.package) ?? []
87
+ const loaded = definition.rules.map((rule) => ({ ...rule, origin, definedIn }))
88
+ // Project and config rules are tried before built-in ones.
89
+ this.byPackage.set(definition.package, origin === 'built-in' ? [...rules, ...loaded] : [...loaded, ...rules])
90
+ }
91
+
92
+ packages(): string[] {
93
+ return [...this.byPackage.keys()]
94
+ }
95
+
96
+ rulesFor(name: string): LoadedRule[] {
97
+ return this.byPackage.get(name) ?? []
98
+ }
99
+
100
+ /**
101
+ * The rule for an installed copy of a package, or null when it has none. A package with overrides but none for
102
+ * this version is warned about once.
103
+ */
104
+ ruleFor(info: PackageInfo): LoadedRule | null {
105
+ const key = `${info.name}@${info.version}`
106
+ if (this.ruleCache.has(key)) {
107
+ return this.ruleCache.get(key)!
108
+ }
109
+ const rules = this.byPackage.get(info.name)
110
+ let match: LoadedRule | null = null
111
+ if (rules !== undefined) {
112
+ match = rules.find((rule) => semver.satisfies(info.version, rule.versions, { includePrerelease: true })) ?? null
113
+ if (match === null) {
114
+ const warning = {
115
+ package: info.name,
116
+ version: info.version,
117
+ message: `${key} has overrides for ${rules.map((rule) => `'${rule.versions}'`).join(', ')} but none for this version, so it runs unchanged`,
118
+ }
119
+ this.warnings.set(key, warning)
120
+ this.onWarning(warning)
121
+ }
122
+ }
123
+ this.ruleCache.set(key, match)
124
+ return match
125
+ }
126
+
127
+ /**
128
+ * What loading `file` should give instead of its contents, if anything.
129
+ */
130
+ overrideForFile(file: string): FileOverride | null {
131
+ if (!file.includes(`${path.sep}node_modules${path.sep}`)) {
132
+ return null
133
+ }
134
+ const owner = packageOfFile(file)
135
+ if (owner === null) {
136
+ return null
137
+ }
138
+ const { info, relative } = owner
139
+ const rule = this.ruleFor(info)
140
+ if (rule === null) {
141
+ return null
142
+ }
143
+ if (rule.stub) {
144
+ return { kind: 'stub', rule, info }
145
+ }
146
+ const replacement = rule.files?.[relative]
147
+ if (replacement !== undefined) {
148
+ return { kind: 'replace', file: resolveFrom(rule, replacement), rule, info }
149
+ }
150
+ if (rule.replace !== undefined && this.entriesOf(info).has(file)) {
151
+ return { kind: 'replace', file: resolveFrom(rule, rule.replace), rule, info }
152
+ }
153
+ const patches = (rule.patch ?? []).filter((patch) =>
154
+ typeof patch.file === 'string' ? patch.file === relative : patch.file.test(relative),
155
+ )
156
+ if (patches.length > 0) {
157
+ return { kind: 'patch', patches, rule, info, relative }
158
+ }
159
+ return null
160
+ }
161
+
162
+ /**
163
+ * Whether a dependency's file sees the simulated device's platform rather than `web`: its package is listed in the
164
+ * config's `devicePlatform`, or the rule for its version has `platform: 'device'` covering it.
165
+ */
166
+ seesDevicePlatform(file: string): boolean {
167
+ let sees = this.devicePlatformCache.get(file)
168
+ if (sees === undefined) {
169
+ sees = this.computeDevicePlatform(file)
170
+ this.devicePlatformCache.set(file, sees)
171
+ }
172
+ return sees
173
+ }
174
+
175
+ private computeDevicePlatform(file: string): boolean {
176
+ if (!file.includes(`${path.sep}node_modules${path.sep}`)) {
177
+ return false
178
+ }
179
+ const owner = packageOfFile(file)
180
+ if (owner === null) {
181
+ return false
182
+ }
183
+ if (this.devicePlatformPackages.has(owner.info.name)) {
184
+ return true
185
+ }
186
+ const platform = this.byPackage.has(owner.info.name) ? this.ruleFor(owner.info)?.platform : undefined
187
+ if (platform === undefined) {
188
+ return false
189
+ }
190
+ if (platform === 'device') {
191
+ return true
192
+ }
193
+ return platform.device.some((pattern) =>
194
+ typeof pattern === 'string'
195
+ ? pattern.endsWith('/')
196
+ ? owner.relative.startsWith(pattern)
197
+ : owner.relative === pattern
198
+ : pattern.test(owner.relative),
199
+ )
200
+ }
201
+
202
+ private entriesOf(info: PackageInfo): Set<string> {
203
+ let entries = this.entryCache.get(info.dir)
204
+ if (entries === undefined) {
205
+ entries = new Set(entryFiles(info))
206
+ this.entryCache.set(info.dir, entries)
207
+ }
208
+ return entries
209
+ }
210
+
211
+ /**
212
+ * A hash of everything that changes what the pre-bundle holds, so an edited override rebuilds it.
213
+ */
214
+ hash(): string {
215
+ const hash = createHash('sha256')
216
+ // The code that applies overrides, and the `react-native` shims, decide what the pre-bundle holds too.
217
+ // Overrides bundle `web-sim/runtime` into the dependencies they replace, so it is part of what they are.
218
+ const runtime = [...walk(path.dirname(RUNTIME_ENTRY)), ...walk(path.dirname(RN_APP_SHIM)), ...walk(import.meta.dirname)]
219
+ for (const file of [...this.files, ...runtime].sort()) {
220
+ hash.update(file)
221
+ hash.update(readFileSync(file))
222
+ }
223
+ for (const [name, rules] of this.byPackage) {
224
+ if (rules.some((rule) => rule.origin === 'config')) {
225
+ hash.update(name + JSON.stringify(rules, (_, value) => (typeof value === 'function' ? String(value) : value)))
226
+ }
227
+ }
228
+ hash.update(JSON.stringify([...this.devicePlatformPackages].sort()))
229
+ return hash.digest('hex').slice(0, 10)
230
+ }
231
+ }
232
+
233
+ export function applyPatches(source: string, override: Extract<FileOverride, { kind: 'patch' }>): string {
234
+ return override.patches.reduce((current, patch) => {
235
+ const next = patch.replace(current)
236
+ if (next === current) {
237
+ throw new Error(
238
+ `web-sim: a patch for ${override.info.name}@${override.info.version} (${override.relative}, from ${override.rule.definedIn || 'web-sim.config'}) no longer changes the file. Update the override, or narrow its 'versions'.`,
239
+ )
240
+ }
241
+ return next
242
+ }, source)
243
+ }
244
+
245
+ function resolveFrom(rule: LoadedRule, file: string): string {
246
+ return path.resolve(path.dirname(rule.definedIn), file)
247
+ }
248
+
249
+ function* walk(dir: string): Generator<string> {
250
+ for (const entry of readdirSync(dir)) {
251
+ const full = path.join(dir, entry)
252
+ if (statSync(full).isDirectory()) {
253
+ yield* walk(full)
254
+ } else if (/\.(tsx?|jsx?|mjs|css)$/.test(entry)) {
255
+ yield full
256
+ }
257
+ }
258
+ }
@@ -0,0 +1,18 @@
1
+ import path from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+
4
+ /** The web-sim package's root. */
5
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
6
+
7
+ const at = (relative: string) => path.join(PACKAGE_ROOT, relative)
8
+
9
+ export const CLIENT_ENTRY = at('src/client/entry.ts')
10
+ export const RUNTIME_ENTRY = at('src/runtime/index.ts')
11
+ export const BUILT_IN_OVERRIDES = at('overrides')
12
+ export const BUILT_IN_PLUGINS = at('plugins')
13
+ export const SHELL_API_ENTRY = at('src/plugin/index.ts')
14
+ /** What `react-native` resolves to for dependencies: react-native-web, plus what it lacks. */
15
+ export const RN_LIBRARY_SHIM = at('src/client/react-native/library.ts')
16
+ /** What `react-native` resolves to for app code: the same, reporting the simulated platform. */
17
+ export const RN_APP_SHIM = at('src/client/react-native/app.ts')
18
+ export const RN_DEEP_SHIM = at('src/client/react-native/deep.ts')
@@ -0,0 +1,171 @@
1
+ import { existsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import type { Plugin as EsbuildPlugin } from 'esbuild'
4
+ import type { Plugin, ViteDevServer } from 'vite'
5
+ import type { Platform } from '../devices/types.ts'
6
+ import { STUB_FACTORY } from './overrides/plugin.ts'
7
+ import { RN_APP_SHIM, RN_DEEP_SHIM, RN_LIBRARY_SHIM } from './paths.ts'
8
+
9
+ const SCRIPT_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs']
10
+
11
+ /**
12
+ * Deep imports into React Native's own source that libraries make, and what in `deep.ts` stands in for each one's
13
+ * default export. Any other deep import gets a stub.
14
+ */
15
+ const DEEP_IMPORTS: Record<string, string> = {
16
+ 'Libraries/Utilities/codegenNativeComponent': 'codegenNativeComponent',
17
+ 'Libraries/Utilities/codegenNativeCommands': 'codegenNativeCommands',
18
+ 'Libraries/TurboModule/TurboModuleRegistry': 'TurboModuleRegistry',
19
+ 'Libraries/Image/resolveAssetSource': 'resolveAssetSource',
20
+ 'Libraries/Utilities/Platform': 'Platform',
21
+ }
22
+
23
+ /**
24
+ * The platform split. App code is resolved and run as if on the simulated device: `.ios.tsx` (or `.android.tsx`),
25
+ * then `.native.tsx`, then `.tsx`, falling back to `.web.tsx` only when nothing else exists, and `Platform.OS` and
26
+ * `process.env.EXPO_OS` report the device's platform. Dependencies keep their web builds and see `web`, because
27
+ * their native branches call native modules that do not exist here, unless an override's `platform: 'device'` (or
28
+ * the config's `devicePlatform`) says a package's branches are look and feel: then its `react-native` is the app's,
29
+ * and its `process.env.EXPO_OS` the device's platform, while its files still resolve as web.
30
+ *
31
+ * One dev server serves one platform at a time. Switching it drops every transformed app module, so the app reloads
32
+ * with the other platform's files.
33
+ */
34
+ export class PlatformScope {
35
+ platform: Platform
36
+ private server: ViteDevServer | null = null
37
+
38
+ readonly projectRoot: string
39
+ readonly resolveNativeFiles: boolean
40
+ /** Whether a dependency's file sees the device's platform (`platform: 'device'` overrides, `devicePlatform`). */
41
+ readonly libraryOnDevice: (file: string) => boolean
42
+
43
+ constructor(projectRoot: string, initial: Platform, resolveNativeFiles: boolean, libraryOnDevice: (file: string) => boolean = () => false) {
44
+ this.projectRoot = projectRoot
45
+ this.resolveNativeFiles = resolveNativeFiles
46
+ this.platform = initial
47
+ this.libraryOnDevice = libraryOnDevice
48
+ }
49
+
50
+ /** What `react-native` resolves to for an import from `importer`. */
51
+ reactNativeFor(importer: string | undefined): string {
52
+ if (importer === undefined) {
53
+ return RN_LIBRARY_SHIM
54
+ }
55
+ const file = importer.split('?')[0]
56
+ return this.isAppSource(file) || this.libraryOnDevice(file) ? RN_APP_SHIM : RN_LIBRARY_SHIM
57
+ }
58
+
59
+ isAppSource(file: string): boolean {
60
+ return (
61
+ file.startsWith(this.projectRoot + path.sep) &&
62
+ !file.includes(`${path.sep}node_modules${path.sep}`) &&
63
+ !file.startsWith('\0')
64
+ )
65
+ }
66
+
67
+ setPlatform(platform: Platform): boolean {
68
+ if (platform === this.platform) {
69
+ return false
70
+ }
71
+ this.platform = platform
72
+ this.server?.environments.client.moduleGraph.invalidateAll()
73
+ return true
74
+ }
75
+
76
+ /** The file an app import should load on this platform, given the one Vite's web resolution found. */
77
+ variantOf(file: string): string {
78
+ const extension = path.extname(file)
79
+ if (!SCRIPT_EXTENSIONS.includes(extension)) {
80
+ return file
81
+ }
82
+ const stem = file.slice(0, -extension.length).replace(/\.(web|ios|android|native)$/, '')
83
+ for (const suffix of [`.${this.platform}`, '.native', '']) {
84
+ for (const candidate of SCRIPT_EXTENSIONS) {
85
+ if (existsSync(stem + suffix + candidate)) {
86
+ return stem + suffix + candidate
87
+ }
88
+ }
89
+ }
90
+ return file
91
+ }
92
+
93
+ vitePlugin(): Plugin {
94
+ const scope = this
95
+ return {
96
+ name: 'web-sim:platform',
97
+ enforce: 'pre',
98
+ configureServer: (server) => {
99
+ this.server = server
100
+ },
101
+ async resolveId(source, importer, options) {
102
+ if (source === 'react-native') {
103
+ return scope.reactNativeFor(importer)
104
+ }
105
+ if (source.startsWith('react-native/') && !source.endsWith('.json')) {
106
+ return deepImportId(source)
107
+ }
108
+ if (
109
+ !scope.resolveNativeFiles ||
110
+ importer === undefined ||
111
+ !scope.isAppSource(importer.split('?')[0]) ||
112
+ SCRIPT_EXTENSIONS.includes(path.extname(source)) ||
113
+ source.includes('?')
114
+ ) {
115
+ return null
116
+ }
117
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true })
118
+ if (resolved == null || !scope.isAppSource(resolved.id)) {
119
+ return resolved
120
+ }
121
+ const variant = scope.variantOf(resolved.id)
122
+ return variant === resolved.id ? resolved : variant
123
+ },
124
+ load(id) {
125
+ return id.startsWith(DEEP_PREFIX) ? deepImportModule(id.slice(DEEP_PREFIX.length), 'esm') : null
126
+ },
127
+ transform: (code, id) => {
128
+ const file = id.split('?')[0]
129
+ if (!this.isAppSource(file) || !code.includes('process.env.EXPO_OS')) {
130
+ return null
131
+ }
132
+ return { code: code.replaceAll('process.env.EXPO_OS', JSON.stringify(this.platform)), map: null }
133
+ },
134
+ }
135
+ }
136
+
137
+ esbuildPlugin(): EsbuildPlugin {
138
+ const scope = this
139
+ return {
140
+ name: 'web-sim-platform',
141
+ setup(build) {
142
+ build.onResolve({ filter: /^react-native$/ }, ({ importer }) => ({ path: scope.reactNativeFor(importer || undefined) }))
143
+ build.onResolve({ filter: /^react-native\/.+/ }, ({ path: source }) =>
144
+ source.endsWith('.json') ? undefined : { path: source, namespace: 'web-sim-rn-deep' },
145
+ )
146
+ build.onLoad({ filter: /.*/, namespace: 'web-sim-rn-deep' }, ({ path: source }) => ({
147
+ contents: deepImportModule(source, 'cjs-compatible'),
148
+ loader: 'js',
149
+ resolveDir: path.dirname(RN_DEEP_SHIM),
150
+ }))
151
+ },
152
+ }
153
+ }
154
+ }
155
+
156
+ const DEEP_PREFIX = '\0web-sim-rn-deep:'
157
+
158
+ function deepImportId(source: string): string {
159
+ return DEEP_PREFIX + source
160
+ }
161
+
162
+ function deepImportModule(source: string, mode: 'esm' | 'cjs-compatible'): string {
163
+ const subpath = source.slice('react-native/'.length).replace(/\.js$/, '')
164
+ const name = DEEP_IMPORTS[subpath]
165
+ if (name !== undefined) {
166
+ return `export * from ${JSON.stringify(RN_DEEP_SHIM)};\nexport { ${name} as default } from ${JSON.stringify(RN_DEEP_SHIM)};`
167
+ }
168
+ return mode === 'esm'
169
+ ? `${STUB_FACTORY}\nexport default createStub(${JSON.stringify(source)});`
170
+ : `${STUB_FACTORY}\nmodule.exports = createStub(${JSON.stringify(source)});`
171
+ }
@@ -0,0 +1,98 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import type { Plugin as VitePlugin } from 'vite'
5
+ import { findPackage } from './overrides/packages.ts'
6
+
7
+ /**
8
+ * A web-sim plugin: what it simulates, as overrides for the app's packages and a module for the shell with its state,
9
+ * panel and actions. Paths are relative to the file the plugin is defined in, or absolute.
10
+ *
11
+ * ```ts
12
+ * export default definePlugin({
13
+ * name: 'battery',
14
+ * packages: ['expo-battery'],
15
+ * overrides: './overrides',
16
+ * shell: './shell.tsx',
17
+ * })
18
+ * ```
19
+ */
20
+ export type WebSimPlugin = {
21
+ name: string
22
+ /** The packages it simulates. Its panel shows when the app has one installed; without any, always. */
23
+ packages?: string[]
24
+ /** A folder of overrides, one folder per package with an `overrides.ts`. */
25
+ overrides?: string
26
+ /** A module that default-exports `defineShellPlugin(...)` from `web-sim/shell`. */
27
+ shell?: string
28
+ /**
29
+ * A module run in the app's window before the app, for what no package override reaches: `fetch`, timers, globals.
30
+ * It talks to the shell through `plugin(id)` from `web-sim/runtime`.
31
+ */
32
+ app?: string
33
+ /** More Vite plugins, for what overrides cannot do. */
34
+ vite?: VitePlugin[]
35
+ }
36
+
37
+ export function definePlugin(plugin: WebSimPlugin): WebSimPlugin {
38
+ return plugin
39
+ }
40
+
41
+ export type LoadedPlugin = WebSimPlugin & {
42
+ origin: 'built-in' | 'config'
43
+ /** Whether the app uses it: no `packages`, or one of them installed. */
44
+ active: boolean
45
+ overridesDir: string | null
46
+ shellFile: string | null
47
+ appFile: string | null
48
+ /** The plugin's own folder, watched for changes. Null for plugins defined inline in the config. */
49
+ dir: string | null
50
+ }
51
+
52
+ export const PLUGIN_FILE = 'plugin.ts'
53
+
54
+ /**
55
+ * The built-in plugins (one folder each in `builtInDir`, with a `plugin.ts`), then the config's, which replace
56
+ * built-in ones of the same name. `disabled` names plugins to leave out.
57
+ */
58
+ export async function loadPlugins(options: {
59
+ projectRoot: string
60
+ builtInDir: string
61
+ configured: WebSimPlugin[]
62
+ configFile: string | null
63
+ disabled: string[]
64
+ }): Promise<LoadedPlugin[]> {
65
+ const { projectRoot, builtInDir, configured, configFile, disabled } = options
66
+ const byName = new Map<string, LoadedPlugin>()
67
+ const add = (plugin: WebSimPlugin, origin: LoadedPlugin['origin'], base: string, dir: string | null) => {
68
+ const resolve = (file: string | undefined) => (file === undefined ? null : path.resolve(base, file))
69
+ byName.set(plugin.name, {
70
+ ...plugin,
71
+ origin,
72
+ active: plugin.packages === undefined || plugin.packages.length === 0 || plugin.packages.some((name) => findPackage(name, projectRoot) !== null),
73
+ overridesDir: resolve(plugin.overrides),
74
+ shellFile: resolve(plugin.shell),
75
+ appFile: resolve(plugin.app),
76
+ dir,
77
+ })
78
+ }
79
+ if (existsSync(builtInDir)) {
80
+ for (const entry of readdirSync(builtInDir).sort()) {
81
+ const file = path.join(builtInDir, entry, PLUGIN_FILE)
82
+ if (!existsSync(file)) {
83
+ continue
84
+ }
85
+ // A query per load: the dev server reloads plugins in the same process, and Node caches modules by URL.
86
+ const module = (await import(`${pathToFileURL(file).href}?v=${Date.now()}`)) as { default?: WebSimPlugin }
87
+ if (module.default === undefined || typeof module.default.name !== 'string') {
88
+ throw new Error(`${file} must default-export definePlugin(...)`)
89
+ }
90
+ add(module.default, 'built-in', path.dirname(file), path.dirname(file))
91
+ }
92
+ }
93
+ const configBase = configFile !== null ? path.dirname(configFile) : projectRoot
94
+ for (const plugin of configured) {
95
+ add(plugin, 'config', configBase, null)
96
+ }
97
+ return [...byName.values()].filter((plugin) => !disabled.includes(plugin.name))
98
+ }