react-native-roku 0.0.0-stage → 0.2.0-preview.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 (200) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/CONTRIBUTING.md +34 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE.md +10 -0
  5. package/README.md +66 -2
  6. package/bin/react-native-roku.mjs +91 -0
  7. package/build/assets.cjs +311 -0
  8. package/build/assets.d.cts +50 -0
  9. package/build/compatibility.d.mts +40 -0
  10. package/build/compatibility.mjs +272 -0
  11. package/build/dev.d.mts +34 -0
  12. package/build/dev.mjs +297 -0
  13. package/build/devWorkspace.d.mts +11 -0
  14. package/build/devWorkspace.mjs +86 -0
  15. package/build/device.d.mts +47 -0
  16. package/build/device.mjs +310 -0
  17. package/build/environment.d.mts +29 -0
  18. package/build/environment.mjs +144 -0
  19. package/build/esbuild.d.mts +5 -0
  20. package/build/esbuild.mjs +118 -0
  21. package/build/fontVariants.d.mts +27 -0
  22. package/build/fontVariants.mjs +424 -0
  23. package/build/frontend.d.mts +52 -0
  24. package/build/frontend.mjs +75 -0
  25. package/build/identity.mjs +45 -0
  26. package/build/index.d.mts +22 -0
  27. package/build/index.mjs +87 -0
  28. package/build/intl.mjs +121 -0
  29. package/build/metro.cjs +38 -0
  30. package/build/metro.d.cts +37 -0
  31. package/build/metroFrontend.mjs +222 -0
  32. package/build/metroMetadata.mjs +119 -0
  33. package/build/metroModules.mjs +397 -0
  34. package/build/metroRefresh.d.mts +64 -0
  35. package/build/metroRefresh.mjs +346 -0
  36. package/build/metroTransformer.cjs +146 -0
  37. package/build/nativeTextMemo.mjs +296 -0
  38. package/build/nativewind.d.mts +9 -0
  39. package/build/nativewind.mjs +92 -0
  40. package/build/project.d.mts +111 -0
  41. package/build/project.mjs +615 -0
  42. package/build/reactCompiler.mjs +113 -0
  43. package/build/reactProfile.cjs +35 -0
  44. package/build/refreshRuntime.mjs +187 -0
  45. package/build/refreshSourceMap.mjs +53 -0
  46. package/build/release.mjs +99 -0
  47. package/build/resolution.d.mts +3 -0
  48. package/build/resolution.mjs +25 -0
  49. package/build/surfaces.d.mts +1 -0
  50. package/build/surfaces.mjs +42 -0
  51. package/build/testing/node.d.mts +29 -0
  52. package/build/testing/node.mjs +106 -0
  53. package/build/yoga.d.mts +8 -0
  54. package/build/yoga.mjs +186 -0
  55. package/compatibility/public-api.json +327 -0
  56. package/compatibility/registry.json +2258 -0
  57. package/config/release.json +15 -0
  58. package/config/toolchain.json +34 -0
  59. package/docs/compatibility.md +813 -0
  60. package/docs/getting-started.md +460 -0
  61. package/docs/maintenance.md +362 -0
  62. package/docs/qualification.md +241 -0
  63. package/docs/standalone-testing.md +56 -0
  64. package/examples/hello-roku/README.md +35 -0
  65. package/examples/hello-roku/package.template.json +31 -0
  66. package/examples/hello-roku/pnpm-workspace.yaml +11 -0
  67. package/examples/hello-roku/roku.config.json +22 -0
  68. package/examples/hello-roku/src/App.tsx +54 -0
  69. package/examples/hello-roku/src/Catalog.tsx +200 -0
  70. package/examples/hello-roku/src/assets.d.ts +16 -0
  71. package/examples/hello-roku/src/catalog-cover.png +0 -0
  72. package/examples/hello-roku/tsconfig.json +1 -0
  73. package/examples/hello-roku/tsconfig.react.json +1 -0
  74. package/native/components/RNRAppControl.brs +215 -0
  75. package/native/components/RNRAppControl.xml +13 -0
  76. package/native/components/RNRDeviceFacts.brs +19 -0
  77. package/native/components/RNRDeviceFacts.xml +9 -0
  78. package/native/components/RNRDeviceFactsTask.brs +74 -0
  79. package/native/components/RNRDeviceFactsTask.xml +9 -0
  80. package/native/components/RNRTextRaster.brs +15 -0
  81. package/native/components/RNRTextRaster.xml +9 -0
  82. package/native/components/RNRTextRasterTask.brs +77 -0
  83. package/native/components/RNRTextRasterTask.xml +9 -0
  84. package/native/manifest.json +7 -0
  85. package/package.json +183 -3
  86. package/src/animation/clock.ts +10 -0
  87. package/src/animation/derivedValue.ts +163 -0
  88. package/src/animation/legacyAnimated.ts +255 -0
  89. package/src/animation/reanimated.ts +243 -0
  90. package/src/animation/sharedValue.ts +285 -0
  91. package/src/animation/worklets.ts +23 -0
  92. package/src/application/AppRegistry.ts +31 -0
  93. package/src/application/mountApplication.ts +136 -0
  94. package/src/graphics/BitmapLayer.tsx +68 -0
  95. package/src/graphics/RoundedBorder.tsx +116 -0
  96. package/src/graphics/TextRasterCache.ts +259 -0
  97. package/src/graphics/gradient.ts +37 -0
  98. package/src/graphics/inlineRaster.ts +85 -0
  99. package/src/graphics/png.ts +77 -0
  100. package/src/graphics/rasterPixels.ts +89 -0
  101. package/src/graphics/surfaces.ts +105 -0
  102. package/src/graphics/textRaster.types.ts +60 -0
  103. package/src/graphics/textRasterGeometry.ts +116 -0
  104. package/src/host/host.types.ts +57 -0
  105. package/src/index.ts +22 -0
  106. package/src/interop/nativewind.ts +2 -0
  107. package/src/layout/FontResources.ts +252 -0
  108. package/src/layout/affine.ts +89 -0
  109. package/src/layout/flexLayout.ts +398 -0
  110. package/src/layout/fontFaces.d.mts +19 -0
  111. package/src/layout/fontFaces.mjs +85 -0
  112. package/src/layout/fontVariants.d.mts +2 -0
  113. package/src/layout/fontVariants.mjs +8 -0
  114. package/src/layout/inlineParagraph.ts +158 -0
  115. package/src/layout/inlineText.ts +68 -0
  116. package/src/layout/layoutReuse.ts +117 -0
  117. package/src/layout/nativeNodeFields.ts +179 -0
  118. package/src/layout/preparedFields.ts +78 -0
  119. package/src/layout/textLayout.ts +138 -0
  120. package/src/layout/transform.ts +113 -0
  121. package/src/media/SceneGraphAudio.ts +161 -0
  122. package/src/media/SceneGraphVideo.ts +167 -0
  123. package/src/media/audioSession.ts +84 -0
  124. package/src/media/index.ts +2 -0
  125. package/src/media/videoErrorDetails.ts +40 -0
  126. package/src/media/videoSession.ts +136 -0
  127. package/src/navigation/RouterStore.ts +244 -0
  128. package/src/navigation/expoRouter.ts +115 -0
  129. package/src/react-native/NativeInput.ts +494 -0
  130. package/src/react-native/NativeSystemState.ts +95 -0
  131. package/src/react-native/accessibility.ts +265 -0
  132. package/src/react-native/activityIndicator.ts +72 -0
  133. package/src/react-native/compilerPressable.ts +26 -0
  134. package/src/react-native/createNativeRoot.ts +2126 -0
  135. package/src/react-native/directionalFocus.ts +55 -0
  136. package/src/react-native/environment.ts +275 -0
  137. package/src/react-native/flatList.ts +1001 -0
  138. package/src/react-native/flatListViewability.ts +231 -0
  139. package/src/react-native/focusEvents.ts +85 -0
  140. package/src/react-native/image.ts +247 -0
  141. package/src/react-native/index.ts +54 -0
  142. package/src/react-native/interactionManager.ts +76 -0
  143. package/src/react-native/keyboard.ts +60 -0
  144. package/src/react-native/linearGradient.ts +94 -0
  145. package/src/react-native/modal.tsx +148 -0
  146. package/src/react-native/nativeHostContext.ts +80 -0
  147. package/src/react-native/nativeModules.ts +86 -0
  148. package/src/react-native/nativeRoot.types.ts +22 -0
  149. package/src/react-native/nativeViewHandle.ts +191 -0
  150. package/src/react-native/nativewindPressable.ts +38 -0
  151. package/src/react-native/panResponder.ts +73 -0
  152. package/src/react-native/primitives.ts +685 -0
  153. package/src/react-native/safeArea.ts +76 -0
  154. package/src/react-native/scrollView.ts +289 -0
  155. package/src/react-native/styleInterop.ts +8 -0
  156. package/src/react-native/styleSheet.ts +54 -0
  157. package/src/react-native/textInput.ts +334 -0
  158. package/src/react-native/unsupported.ts +25 -0
  159. package/src/renderer/SceneRoot.ts +1006 -0
  160. package/src/scene/SdkDeviceFacts.ts +151 -0
  161. package/src/scene/SdkDeviceServices.ts +72 -0
  162. package/src/scene/SdkSceneGraph.ts +124 -0
  163. package/src/scene/SdkTextEntry.ts +321 -0
  164. package/src/scene/SdkTextMetrics.ts +136 -0
  165. package/src/scene/SdkTextRasterTransport.ts +191 -0
  166. package/src/scene/SdkWebTransport.ts +122 -0
  167. package/src/scene/createRokuHost.ts +213 -0
  168. package/src/scene/sceneGraph.types.ts +38 -0
  169. package/src/services/DeviceServices.ts +53 -0
  170. package/src/services/RegistryStorage.ts +85 -0
  171. package/src/services/RokuKeySession.ts +29 -0
  172. package/src/services/asyncStorage.ts +23 -0
  173. package/src/services/base64.ts +52 -0
  174. package/src/services/crypto.ts +18 -0
  175. package/src/services/expoConstants.ts +11 -0
  176. package/src/services/expoLinking.ts +12 -0
  177. package/src/services/expoStatusBar.ts +4 -0
  178. package/src/services/installWebRuntime.ts +105 -0
  179. package/src/services/intlEnglish.ts +54 -0
  180. package/src/services/languageRuntime.ts +65 -0
  181. package/src/services/nativeTimers.ts +96 -0
  182. package/src/services/secureStore.ts +23 -0
  183. package/src/services/textEntryRequest.ts +22 -0
  184. package/src/services/utf8.ts +57 -0
  185. package/src/services/webRuntime.ts +346 -0
  186. package/src/testing/CanvasResources.ts +141 -0
  187. package/src/testing/CanvasSceneGraph.ts +496 -0
  188. package/src/testing/CanvasTextEntry.ts +237 -0
  189. package/src/testing/PreviewTextObservations.ts +82 -0
  190. package/src/testing/RecordingSceneGraph.ts +136 -0
  191. package/src/types/normalize-colors.d.ts +4 -0
  192. package/src/vector/dynamicSvg.tsx +226 -0
  193. package/src/vector/svg.ts +222 -0
  194. package/src/vector/svg.types.ts +4 -0
  195. package/src/vector/svgElements.ts +58 -0
  196. package/src/vector/svgKey.d.mts +4 -0
  197. package/src/vector/svgKey.mjs +16 -0
  198. package/src/vector/svgPath.ts +157 -0
  199. package/src/vector/svgPixels.ts +133 -0
  200. package/tsconfig.consumer.json +29 -0
@@ -0,0 +1,346 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import ts from "typescript";
5
+ import { refreshSourceMaps } from "./refreshSourceMap.mjs";
6
+ import { createRequire } from "node:module";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const sha = (value) => createHash("sha256").update(value).digest("hex");
10
+ const inside = (parent, path) => {
11
+ const child = relative(parent, path);
12
+ return child === "" || (!isAbsolute(child) && child !== ".." && !child.startsWith(".." + sep));
13
+ };
14
+
15
+ /** Shared bootstrap owner for standalone and custom consumer previews. */
16
+ export function writeRokuRefreshBootstrap({ root = process.cwd(), session, generation, outfile }) {
17
+ if (
18
+ !session?.id ||
19
+ !Number.isSafeInteger(generation) ||
20
+ generation < 1 ||
21
+ typeof outfile !== "string"
22
+ )
23
+ throw Error("A Roku refresh bootstrap requires a session, generation and outfile");
24
+ root = resolve(root);
25
+ outfile = resolve(root, outfile);
26
+ const require = createRequire(resolve(root, "package.json"));
27
+ mkdirSync(dirname(outfile), { recursive: true });
28
+ writeFileSync(
29
+ outfile,
30
+ `import Refresh from ${JSON.stringify(require.resolve("react-refresh/runtime"))};import {installRokuRefreshRuntime} from ${JSON.stringify(fileURLToPath(new URL("./refreshRuntime.mjs", import.meta.url)))};installRokuRefreshRuntime(Refresh,${JSON.stringify({ sessionId: session.id, generation })});\n`,
31
+ );
32
+ return outfile;
33
+ }
34
+
35
+ /** Inspect original source, before Babel helpers/registration are inserted.
36
+ * React and StyleSheet wrappers are allocations with known lifetimes. Unknown
37
+ * top-level calls, stores, contexts and resource constructors need a remount. */
38
+ export function isRefreshSafeSource(path, contents) {
39
+ const source = ts.createSourceFile(
40
+ path,
41
+ contents,
42
+ ts.ScriptTarget.Latest,
43
+ true,
44
+ ts.ScriptKind.TSX,
45
+ );
46
+ if (source.parseDiagnostics.length) return false;
47
+ const react = new Set(),
48
+ wrappers = new Set(),
49
+ styles = new Set();
50
+ for (const node of source.statements) {
51
+ if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) continue;
52
+ const module = node.moduleSpecifier.text,
53
+ clause = node.importClause;
54
+ if (!clause || clause.isTypeOnly) continue;
55
+ if (module === "react" && clause.name) react.add(clause.name.text);
56
+ const bindings = clause.namedBindings;
57
+ if (bindings && ts.isNamespaceImport(bindings) && module === "react")
58
+ react.add(bindings.name.text);
59
+ if (bindings && ts.isNamedImports(bindings))
60
+ for (const item of bindings.elements) {
61
+ if (item.isTypeOnly) continue;
62
+ const name = (item.propertyName ?? item.name).text;
63
+ if (module === "react" && ["memo", "forwardRef"].includes(name))
64
+ wrappers.add(item.name.text);
65
+ if (
66
+ ["react-native", "react-native-roku/react-native"].includes(module) &&
67
+ name === "StyleSheet"
68
+ )
69
+ styles.add(item.name.text);
70
+ }
71
+ }
72
+ const isWrapper = (call) =>
73
+ (ts.isIdentifier(call) && wrappers.has(call.text)) ||
74
+ (ts.isPropertyAccessExpression(call) &&
75
+ ts.isIdentifier(call.expression) &&
76
+ react.has(call.expression.text) &&
77
+ ["memo", "forwardRef"].includes(call.name.text));
78
+ const ownedComponents = new Set();
79
+ for (const node of source.statements) {
80
+ if (ts.isFunctionDeclaration(node) && node.name) ownedComponents.add(node.name.text);
81
+ if (ts.isVariableStatement(node))
82
+ for (const declaration of node.declarationList.declarations) {
83
+ const value = declaration.initializer;
84
+ if (
85
+ ts.isIdentifier(declaration.name) &&
86
+ value &&
87
+ (ts.isArrowFunction(value) ||
88
+ ts.isFunctionExpression(value) ||
89
+ (ts.isCallExpression(value) && isWrapper(value.expression)))
90
+ )
91
+ ownedComponents.add(declaration.name.text);
92
+ }
93
+ }
94
+ const pure = (node) => {
95
+ if (!node) return true;
96
+ if (
97
+ ts.isIdentifier(node) ||
98
+ ts.isLiteralExpression(node) ||
99
+ ts.isNoSubstitutionTemplateLiteral(node) ||
100
+ [ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(
101
+ node.kind,
102
+ ) ||
103
+ ts.isArrowFunction(node) ||
104
+ ts.isFunctionExpression(node)
105
+ )
106
+ return true;
107
+ if (
108
+ ts.isParenthesizedExpression(node) ||
109
+ ts.isAsExpression(node) ||
110
+ ts.isSatisfiesExpression(node) ||
111
+ ts.isNonNullExpression(node)
112
+ )
113
+ return pure(node.expression);
114
+ if (ts.isPrefixUnaryExpression(node))
115
+ return (
116
+ [
117
+ ts.SyntaxKind.PlusToken,
118
+ ts.SyntaxKind.MinusToken,
119
+ ts.SyntaxKind.ExclamationToken,
120
+ ts.SyntaxKind.TildeToken,
121
+ ].includes(node.operator) && pure(node.operand)
122
+ );
123
+ if (ts.isPropertyAccessExpression(node)) return pure(node.expression);
124
+ if (ts.isArrayLiteralExpression(node)) return node.elements.every(pure);
125
+ if (ts.isObjectLiteralExpression(node))
126
+ return node.properties.every(
127
+ (property) =>
128
+ ts.isShorthandPropertyAssignment(property) ||
129
+ ts.isMethodDeclaration(property) ||
130
+ (ts.isPropertyAssignment(property) &&
131
+ !ts.isComputedPropertyName(property.name) &&
132
+ pure(property.initializer)),
133
+ );
134
+ if (ts.isCallExpression(node)) {
135
+ const call = node.expression;
136
+ const known =
137
+ isWrapper(call) ||
138
+ (ts.isPropertyAccessExpression(call) &&
139
+ ts.isIdentifier(call.expression) &&
140
+ styles.has(call.expression.text) &&
141
+ call.name.text === "create");
142
+ return known && node.arguments.every(pure);
143
+ }
144
+ return false;
145
+ };
146
+ return source.statements.every((node) => {
147
+ if (
148
+ ts.isImportDeclaration(node) ||
149
+ ts.isExportDeclaration(node) ||
150
+ ts.isInterfaceDeclaration(node) ||
151
+ ts.isTypeAliasDeclaration(node) ||
152
+ ts.isFunctionDeclaration(node) ||
153
+ ts.isEmptyStatement(node)
154
+ )
155
+ return true;
156
+ if (ts.isExpressionStatement(node)) {
157
+ const value = node.expression;
158
+ if (ts.isStringLiteral(value)) return true;
159
+ // Conventional display names mutate only a freshly allocated local
160
+ // function/React wrapper. Imported objects, aliases and other assignments
161
+ // can affect resource lifetimes and still require a full reload.
162
+ return (
163
+ ts.isBinaryExpression(value) &&
164
+ value.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
165
+ ts.isPropertyAccessExpression(value.left) &&
166
+ ts.isIdentifier(value.left.expression) &&
167
+ ownedComponents.has(value.left.expression.text) &&
168
+ value.left.name.text === "displayName" &&
169
+ ts.isStringLiteral(value.right)
170
+ );
171
+ }
172
+ if (ts.isVariableStatement(node))
173
+ return node.declarationList.declarations.every((item) => pure(item.initializer));
174
+ if (ts.isExportAssignment(node)) return pure(node.expression);
175
+ return false;
176
+ });
177
+ }
178
+
179
+ /** A session owns stable Metro IDs and only advances its base on publication. */
180
+ export function createRokuMetroRefreshSession({
181
+ root = process.cwd(),
182
+ directory,
183
+ sourceRoots = [root],
184
+ }) {
185
+ root = resolve(root);
186
+ if (!directory) throw Error("A refresh session requires an owned directory");
187
+ directory = resolve(root, directory);
188
+ const id = randomUUID(),
189
+ candidates = new Map(),
190
+ purity = new Map();
191
+ let assign,
192
+ base,
193
+ disposed = false;
194
+ const active = () => {
195
+ if (disposed) throw Error("The Roku refresh session is retired");
196
+ };
197
+ const session = {
198
+ id,
199
+ directory,
200
+ createModuleIdFactory(original) {
201
+ active();
202
+ assign ??= original();
203
+ return () => assign;
204
+ },
205
+ classify(path, source) {
206
+ if (
207
+ !source ||
208
+ !/\.[cm]?[jt]sx?$/.test(path) ||
209
+ !sourceRoots.some((parent) => {
210
+ const base = resolve(root, parent);
211
+ return (
212
+ inside(base, path) &&
213
+ !relative(base, path)
214
+ .split(/[\\/]/)
215
+ .some((part) => ["node_modules", ".roku", ".local", "generated"].includes(part))
216
+ );
217
+ })
218
+ )
219
+ return false;
220
+ const key = path + sha(source);
221
+ if (!purity.has(key)) purity.set(key, isRefreshSafeSource(path, source));
222
+ return purity.get(key);
223
+ },
224
+ stage({ generation, graph, identity, outputDirectory }) {
225
+ active();
226
+ if (
227
+ !Number.isSafeInteger(generation) ||
228
+ generation < 1 ||
229
+ graph.sessionId !== id ||
230
+ graph.generation !== generation
231
+ )
232
+ throw Error("Invalid Roku refresh generation");
233
+ let reason = !base
234
+ ? "initial-generation"
235
+ : base.generation !== generation - 1
236
+ ? "publication-gap"
237
+ : base.identity !== identity
238
+ ? "configuration-assets-or-runtime-changed"
239
+ : base.graph.runtimeSha256 !== graph.runtimeSha256 ||
240
+ base.graph.bootstrapSha256 !== graph.bootstrapSha256 ||
241
+ JSON.stringify(base.graph.bindings) !== JSON.stringify(graph.bindings)
242
+ ? "metro-startup-changed"
243
+ : null;
244
+ const previous = new Map((base?.graph.modules ?? []).map((module) => [module.id, module]));
245
+ const current = new Map(graph.modules.map((module) => [module.id, module]));
246
+ if (
247
+ !reason &&
248
+ (previous.size !== current.size ||
249
+ graph.modules.some((module) => previous.get(module.id)?.source !== module.source))
250
+ )
251
+ reason = "dependency-graph-changed";
252
+ const changed = graph.modules.filter(
253
+ (module) => previous.get(module.id)?.sha256 !== module.sha256,
254
+ );
255
+ if (!reason && changed.some((module) => !module.safe || !previous.get(module.id)?.safe))
256
+ reason = "resource-lifetime-changed";
257
+ let plan = { type: "reload", reason, sessionId: id, generation };
258
+ if (!reason) {
259
+ const inverse = Object.fromEntries(graph.modules.map((module) => [module.id, []]));
260
+ for (const module of graph.modules)
261
+ for (const dependency of module.dependencies) {
262
+ if (!Object.hasOwn(inverse, dependency))
263
+ throw Error("Unattested Metro refresh dependency");
264
+ inverse[dependency].push(module.id);
265
+ }
266
+ const updateId = sha(
267
+ JSON.stringify([id, base.generation, generation, changed.map((module) => module.sha256)]),
268
+ );
269
+ const prefix = `export function apply(){const __rnrRefresh=globalThis.__RNR_ROKU_REFRESH__;const {${graph.bindings.join(",")}}=__rnrRefresh.beginPatch(${JSON.stringify({ sessionId: id, fromGeneration: base.generation, generation, updateId })});\n`;
270
+ const suffix = "\n}\n";
271
+ const chunks = [];
272
+ const sourceMap = refreshSourceMaps(graph);
273
+ const limit = graph.maxModuleBytes - (sourceMap ? 256 : 0);
274
+ let chunk = prefix;
275
+ let parts = [];
276
+ for (const module of changed) {
277
+ const code = module.code.replace(/\);\s*$/, "," + JSON.stringify(inverse) + ");") + "\n";
278
+ if (Buffer.byteLength(prefix + code + suffix) > limit) {
279
+ reason = "refresh-factory-exceeds-budget";
280
+ break;
281
+ }
282
+ if (Buffer.byteLength(chunk + code + suffix) > limit) {
283
+ chunks.push({ contents: chunk + suffix, parts });
284
+ chunk = prefix;
285
+ parts = [];
286
+ }
287
+ parts.push({ module, line: chunk.split("\n").length });
288
+ chunk += code;
289
+ }
290
+ chunks.push({ contents: chunk + suffix, parts });
291
+ const target = resolve(outputDirectory, "refresh");
292
+ mkdirSync(target, { recursive: true });
293
+ const paths = reason
294
+ ? []
295
+ : chunks.map(({ contents, parts }, index) => {
296
+ const name = `update-${updateId}-${index}.mjs`;
297
+ if (sourceMap) {
298
+ writeFileSync(resolve(target, name + ".map"), sourceMap(name, parts));
299
+ contents += `\n//# sourceMappingURL=${name}.map\n`;
300
+ }
301
+ if (Buffer.byteLength(contents) > graph.maxModuleBytes)
302
+ throw Error("Metro refresh module exceeds its budget");
303
+ writeFileSync(resolve(target, name), contents);
304
+ return "/refresh/" + name;
305
+ });
306
+ plan = reason
307
+ ? { ...plan, reason }
308
+ : {
309
+ type: "refresh",
310
+ sessionId: id,
311
+ fromGeneration: base.generation,
312
+ generation,
313
+ updateId,
314
+ paths,
315
+ moduleIds: changed.map((module) => module.id),
316
+ changed: changed.map((module) => module.source),
317
+ };
318
+ }
319
+ candidates.set(generation, { generation, graph, identity, plan });
320
+ return plan;
321
+ },
322
+ plan(generation) {
323
+ active();
324
+ return candidates.get(generation)?.plan ?? null;
325
+ },
326
+ discard(generation) {
327
+ active();
328
+ candidates.delete(generation);
329
+ },
330
+ publish(generation) {
331
+ active();
332
+ const candidate = candidates.get(generation);
333
+ if (!candidate || (base && generation <= base.generation))
334
+ throw Error("Unprepared Roku refresh publication");
335
+ base = candidate;
336
+ candidates.clear();
337
+ },
338
+ dispose() {
339
+ disposed = true;
340
+ candidates.clear();
341
+ purity.clear();
342
+ base = assign = null;
343
+ },
344
+ };
345
+ return session;
346
+ }
@@ -0,0 +1,146 @@
1
+ const { createHash } = require("node:crypto");
2
+ const { readFileSync } = require("node:fs");
3
+ const { createRequire } = require("node:module");
4
+ const { resolve } = require("node:path");
5
+ const { runtimeInputs, resolveRuntime } = require("./index.mjs");
6
+ const { prepareHermesYoga } = require("./yoga.mjs");
7
+ const { prepareIntlDataModules } = require("./intl.mjs");
8
+ const {
9
+ prepareNativewindInterop,
10
+ prepareNativewindPreferences,
11
+ prepareNativewindInputState,
12
+ } = require("./nativewind.mjs");
13
+ const { prepareReactEntry } = require("./reactProfile.cjs");
14
+ const { createRokuImageAssets } = require("./assets.cjs");
15
+
16
+ /** Compose with the application's Babel transformer; never replace its Babel policy. */
17
+ exports.withRokuBabelTransformer = function withRokuBabelTransformer(
18
+ upstream,
19
+ {
20
+ root = process.cwd(),
21
+ generatedDirectory,
22
+ plugins = [],
23
+ imageAssets,
24
+ preparedSourcesPath,
25
+ fastRefresh,
26
+ } = {},
27
+ ) {
28
+ const brand = Symbol.for("react-native-roku.metro-transformer");
29
+ const inherited = upstream?.[brand];
30
+ if (inherited) {
31
+ upstream = inherited.upstream ?? inherited;
32
+ plugins = [...plugins, ...(inherited.plugins ?? [])];
33
+ generatedDirectory ??= inherited.generatedDirectory;
34
+ imageAssets ??= inherited.imageAssets;
35
+ preparedSourcesPath ??= inherited.preparedSourcesPath;
36
+ fastRefresh ??= inherited.fastRefresh;
37
+ }
38
+ if (typeof upstream?.transform !== "function")
39
+ throw new TypeError("A Roku Babel transformer requires an upstream transform function");
40
+ const require = createRequire(resolve(root, "package.json"));
41
+ const platformRequire = createRequire(__filename);
42
+ const syntaxPlugins = [...new Set(plugins.map((plugin) => require.resolve(plugin)))];
43
+ const images = imageAssets ? createRokuImageAssets({ ...imageAssets, root }) : null;
44
+ const preparedBytes = preparedSourcesPath ? readFileSync(preparedSourcesPath) : null;
45
+ const preparedSources = preparedBytes ? JSON.parse(preparedBytes) : {};
46
+ const transformer = {
47
+ ...upstream,
48
+ transform(args) {
49
+ if (args.options.platform !== "roku") return upstream.transform.call(upstream, args);
50
+ const path = resolve(args.options.projectRoot ?? root, args.filename);
51
+ let src = prepareReactEntry(args.src, path, args.options.dev === true);
52
+ const prepared = preparedSources[path];
53
+ if (prepared) {
54
+ if (createHash("sha256").update(args.src).digest("hex") !== prepared.sha256)
55
+ throw Error(`Roku image source changed during preparation: ${path}`);
56
+ src = prepared.contents;
57
+ }
58
+ if (/@formatjs[/\\]intl-collator[/\\](?:index|polyfill(?:-force)?)\.js$/.test(path))
59
+ src = prepareIntlDataModules(path, generatedDirectory, { source: src }).contents;
60
+ else if (
61
+ /yoga-layout-prebuilt[/\\]yoga-layout[/\\]build[/\\]Release[/\\]nbind\.js$/.test(path)
62
+ )
63
+ // Metro hashes args.src. Rereading this file could cache newer bytes under
64
+ // the hash of an older snapshot during an editor save.
65
+ src = prepareHermesYoga(path, { source: src }).contents;
66
+ else if (/react-native-css-interop[/\\]dist[/\\]runtime[/\\]native[/\\]api\.js$/.test(path))
67
+ src = prepareNativewindInterop(src, resolveRuntime("interop/nativewind"));
68
+ else if (
69
+ /react-native-css-interop[/\\]dist[/\\]runtime[/\\]native[/\\]native-interop\.js$/.test(
70
+ path,
71
+ )
72
+ )
73
+ src = prepareNativewindInputState(src);
74
+ else if (
75
+ /react-native-css-interop[/\\]dist[/\\]runtime[/\\]native[/\\]appearance-observables\.js$/.test(
76
+ path,
77
+ )
78
+ )
79
+ src = prepareNativewindPreferences(src);
80
+ const transform = (src) =>
81
+ upstream.transform.call(
82
+ upstream,
83
+ src === args.src && !syntaxPlugins.length && !(fastRefresh && args.options.dev)
84
+ ? args
85
+ : {
86
+ ...args,
87
+ src,
88
+ ...(fastRefresh && args.options.dev
89
+ ? { options: { ...args.options, hot: true } }
90
+ : {}),
91
+ ...(syntaxPlugins.length
92
+ ? { plugins: [...syntaxPlugins, ...(args.plugins ?? [])] }
93
+ : {}),
94
+ },
95
+ );
96
+ return images && src.includes("data:image/")
97
+ ? images.prepareEmbeddedSource(path, src, { inline: true }).then(transform)
98
+ : transform(src);
99
+ },
100
+ getCacheKey(...args) {
101
+ const hash = createHash("sha256");
102
+ hash.update(upstream.getCacheKey?.apply(upstream, args) ?? "");
103
+ hash.update(JSON.stringify(runtimeInputs()));
104
+ hash.update(process.versions.node);
105
+ if (preparedBytes) {
106
+ if (!readFileSync(preparedSourcesPath).equals(preparedBytes))
107
+ throw Error("Roku prepared image snapshot changed during compilation");
108
+ hash.update(preparedBytes);
109
+ }
110
+ for (const plugin of syntaxPlugins) hash.update(plugin).update(readFileSync(plugin));
111
+ hash.update(
112
+ JSON.stringify({
113
+ root: resolve(root),
114
+ generatedDirectory: generatedDirectory ? resolve(generatedDirectory) : null,
115
+ imageAssets: imageAssets ?? null,
116
+ preparedSourcesPath: preparedSourcesPath ?? null,
117
+ fastRefresh: fastRefresh ?? false,
118
+ }),
119
+ );
120
+ // Yoga's finite signature discovery also executes these trusted build-time
121
+ // inputs. Their changes must invalidate a previously prepared binding.
122
+ for (const name of ["entry-common.js", "YGEnums.js"]) {
123
+ const specifier = "yoga-layout-prebuilt/yoga-layout/dist/" + name;
124
+ const paths = new Set([platformRequire.resolve(specifier)]);
125
+ try {
126
+ paths.add(require.resolve(specifier));
127
+ } catch (error) {
128
+ if (error.code !== "MODULE_NOT_FOUND") throw error;
129
+ }
130
+ for (const path of paths) hash.update(readFileSync(path));
131
+ }
132
+ return hash.digest("hex");
133
+ },
134
+ };
135
+ Object.defineProperty(transformer, brand, {
136
+ value: {
137
+ upstream,
138
+ plugins: syntaxPlugins,
139
+ generatedDirectory,
140
+ imageAssets,
141
+ preparedSourcesPath,
142
+ fastRefresh,
143
+ },
144
+ });
145
+ return transformer;
146
+ };