react-native-roku 0.0.0-stage → 0.2.0-preview.3

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 +328 -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 +368 -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,615 @@
1
+ import { createRokuDevWorkspace } from "./devWorkspace.mjs";
2
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync, rmSync } from "node:fs";
3
+ import { resolve, dirname, relative } from "node:path";
4
+ import { createRequire } from "node:module";
5
+ import { pathToFileURL } from "node:url";
6
+ import { spawnSync } from "node:child_process";
7
+ import { build } from "esbuild";
8
+ import { buildRokuReactModules, buildRokuMetroModules } from "./frontend.mjs";
9
+ import {
10
+ doctorEnvironment,
11
+ rokuBuildProfile,
12
+ installedPackage,
13
+ toolchain,
14
+ } from "./environment.mjs";
15
+ import { rokuPlugin } from "./esbuild.mjs";
16
+ import { appReactCompiler } from "./reactCompiler.mjs";
17
+ import { prepareNativeComponents } from "./index.mjs";
18
+ import { normalizeRokuBuildIdentity } from "./identity.mjs";
19
+ import { prepareRokuFontAssets } from "./fontVariants.mjs";
20
+ import { fontVariantFamily } from "../src/layout/fontVariants.mjs";
21
+ import { fontFaceFamily, prepareFontFamilies } from "../src/layout/fontFaces.mjs";
22
+ import { createRokuImageAssets } from "./assets.cjs";
23
+ import { buildSurfaceAssets } from "./surfaces.mjs";
24
+ import { createHash } from "node:crypto";
25
+ import { runtimeInputs } from "./index.mjs";
26
+ import { createRokuMetroRefreshSession, writeRokuRefreshBootstrap } from "./metroRefresh.mjs";
27
+ export { prepareRokuFontAssets } from "./fontVariants.mjs";
28
+ const json = (path) => JSON.parse(readFileSync(path, "utf8"));
29
+ const write = (path, text) => {
30
+ mkdirSync(dirname(path), { recursive: true });
31
+ writeFileSync(path, text);
32
+ };
33
+ const developmentConfigFiles = [
34
+ "roku.config.json",
35
+ "package.json",
36
+ "pnpm-lock.yaml",
37
+ "pnpm-workspace.yaml",
38
+ "tsconfig.json",
39
+ "tsconfig.react.json",
40
+ "transformer.js",
41
+ "transformer.cjs",
42
+ ...["metro", "babel"].flatMap((name) =>
43
+ ["js", "cjs", "mjs"].map((extension) => `${name}.config.${extension}`),
44
+ ),
45
+ ];
46
+ const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
47
+ export function readRokuConfig(root = process.cwd()) {
48
+ const path = resolve(root, "roku.config.json");
49
+ if (!existsSync(path))
50
+ throw Error("Missing roku.config.json. Start with react-native-roku init.");
51
+ const value = json(path),
52
+ name = value.name;
53
+ if (typeof name !== "string" || !/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
54
+ throw Error("Roku configuration needs an identifier containing letters, digits or underscores");
55
+ if (value.entryMode && !["component", "registry", "mount"].includes(value.entryMode))
56
+ throw Error("Unknown Roku entryMode");
57
+ if (value.bundler !== undefined && !["esbuild", "metro"].includes(value.bundler))
58
+ throw Error("Unknown Roku frontend bundler; choose esbuild or metro");
59
+ if (value.reactCompiler !== undefined && typeof value.reactCompiler !== "boolean")
60
+ throw Error("reactCompiler must be a boolean");
61
+ if (value.reactCompiler && value.bundler === "metro")
62
+ throw Error("Configure React Compiler in the Metro Babel config");
63
+ for (const field of ["displayName", "storageNamespace"])
64
+ if (
65
+ value[field] !== undefined &&
66
+ (typeof value[field] !== "string" || !value[field].trim() || /[\r\n]/.test(value[field]))
67
+ )
68
+ throw Error(`Roku ${field} must be a nonempty single-line string`);
69
+ const entry = value.entry ?? "src/App.tsx";
70
+ if (typeof entry !== "string" || !existsSync(resolve(root, entry)))
71
+ throw Error(`Roku entry is missing: ${entry}`);
72
+ const fonts = value.fonts ?? {
73
+ defaultFamily: "Inter",
74
+ assets: {
75
+ Inter: "@expo-google-fonts/inter/400Regular/Inter_400Regular.ttf",
76
+ },
77
+ };
78
+ if (
79
+ typeof fonts.defaultFamily !== "string" ||
80
+ !fonts.defaultFamily.trim() ||
81
+ !fonts.assets ||
82
+ typeof fonts.assets !== "object" ||
83
+ Array.isArray(fonts.assets) ||
84
+ !Object.keys(fonts.assets).length ||
85
+ !Object.values(fonts.assets).every((value) => typeof value === "string" && value.length > 0)
86
+ )
87
+ throw Error("The default font must have a configured asset");
88
+ fontFaceFamily(
89
+ fonts.defaultFamily,
90
+ {},
91
+ fonts.assets,
92
+ prepareFontFamilies(fonts.assets, fonts.families),
93
+ );
94
+ fontVariantFamily(fonts.defaultFamily, fonts.variants);
95
+ const viewport = value.viewport ?? { width: 1920, height: 1080 };
96
+ if (
97
+ ![viewport.width, viewport.height].every(
98
+ (number) => typeof number === "number" && Number.isFinite(number) && number > 0,
99
+ )
100
+ )
101
+ throw Error("Roku viewport dimensions must be finite and positive");
102
+ const background = value.background ?? "#101014";
103
+ if (!/^#[a-fA-F0-9]{6}$/.test(background))
104
+ throw Error("Roku background must be a six-digit hex color");
105
+ return {
106
+ ...value,
107
+ name,
108
+ entry,
109
+ fonts,
110
+ viewport,
111
+ background,
112
+ displayName: value.displayName ?? name,
113
+ entryMode: value.entryMode ?? "component",
114
+ bundler: value.bundler ?? "esbuild",
115
+ };
116
+ }
117
+ export function resolveProjectFont(root, specifier) {
118
+ const require = createRequire(resolve(root, "package.json"));
119
+ return specifier.startsWith(".") || specifier.startsWith("/")
120
+ ? resolve(root, specifier)
121
+ : require.resolve(specifier);
122
+ }
123
+ /** Generate only SDK mechanics. Existing applications can supply their own mount export. */
124
+ export function generateSdkEntry({
125
+ directory,
126
+ name = "RokuApplication",
127
+ displayName = name,
128
+ mountModule = "./application.mjs",
129
+ mountExport = "mountApplication",
130
+ mountOptions = {},
131
+ fontsModule = "./fontAssets",
132
+ defaultFamily = "Inter",
133
+ fontFamilies = {},
134
+ componentsModule = "./nativeComponents",
135
+ viewport = { width: 1920, height: 1080 },
136
+ background = "#101014",
137
+ storageNamespace = name,
138
+ svgAtlasModule,
139
+ cornerMasksModule,
140
+ staticAssetsModule,
141
+ buildIdentity,
142
+ }) {
143
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
144
+ throw Error("The native application identifier must contain letters, digits or underscores");
145
+ const anchor = `${name}Anchor`,
146
+ scene = `${name}Scene`;
147
+ const identity =
148
+ buildIdentity && normalizeRokuBuildIdentity({ ...buildIdentity, application: name });
149
+ if (identity)
150
+ write(resolve(directory, "build-identity.json"), JSON.stringify(identity, null, 2) + "\n");
151
+ const assetImport = staticAssetsModule
152
+ ? `import {staticAssets} from ${JSON.stringify(staticAssetsModule)};\n`
153
+ : "";
154
+ const assetValidation = staticAssetsModule
155
+ ? 'if(staticAssets.some(asset=>!asset.uri.startsWith("pkg:/images/")))throw Error("Invalid packaged image URI");'
156
+ : "";
157
+ write(
158
+ resolve(directory, "RokuAnchor.ts"),
159
+ `import {defineAnchorNode} from "@roku-sdk/rsg-ts";\nimport {createRokuHost} from "react-native-roku/sdk-host";\nimport * as components from ${JSON.stringify(componentsModule)};\nimport {fontAssets} from ${JSON.stringify(fontsModule)};\nimport {${mountExport} as mount} from ${JSON.stringify(mountModule)};\n${svgAtlasModule ? `import {svgAtlas} from ${JSON.stringify(svgAtlasModule)};` : ""}\n${cornerMasksModule ? `import {cornerMasks} from ${JSON.stringify(cornerMasksModule)};` : ""}\n${assetImport}export default defineAnchorNode({componentName:${JSON.stringify(anchor)},extends:"Group",inputFields:{},outputFields:{}},()=>{${assetValidation}${identity ? `console.log("RNR_BUILD",${JSON.stringify(JSON.stringify(identity))});` : ""}return createRokuHost({onReady:info=>console.log("RNR_HOST_READY",JSON.stringify({application:${JSON.stringify(name)},...info})),onMemorySnapshot:info=>console.log("RNR_HOST_MEMORY",JSON.stringify(info,(_key,value)=>typeof value==="bigint"?value.toString():value)),onError:(error,phase)=>console.error("ROKU_HOST_ERROR",phase,error.message),components,fonts:{defaultFamily:${JSON.stringify(defaultFamily)},assets:fontAssets,families:${JSON.stringify(fontFamilies)}},viewport:${JSON.stringify(viewport)},storageNamespace:${JSON.stringify(storageNamespace)},${svgAtlasModule ? "svgAtlas," : ""}${cornerMasksModule ? "cornerMasks," : ""}mount:context=>mount({...context,...${JSON.stringify(mountOptions)},onError:(error:Error,kind:string)=>console.error("ROKU_RENDER_ERROR",kind,error.message)})});});\n`,
160
+ );
161
+ write(
162
+ resolve(directory, "entry.ts"),
163
+ `import "./native/${scene}.xml";\nimport {main,registerAnchorNode} from "@roku-sdk/rsg-ts";\nimport Anchor from "./RokuAnchor";\nmain(()=>registerAnchorNode(Anchor));\n`,
164
+ );
165
+ write(
166
+ resolve(directory, `native/${scene}.xml`),
167
+ `<?xml version="1.0" encoding="utf-8"?><component name="${scene}" extends="Scene" backExitsScene="true"><interface><field id="exitRequested" type="boolean" value="false" /></interface><children><${anchor} id="reactRoot" /></children><script type="text/brightscript" uri="${scene}.brs" /></component>`,
168
+ );
169
+ write(
170
+ resolve(directory, `native/${scene}.brs`),
171
+ `sub init()\n m.top.backgroundColor = "0x${background.slice(1)}FF"\n m.top.findNode("reactRoot").setFocus(true)\nend sub\n`,
172
+ );
173
+ return {
174
+ anchor,
175
+ scene,
176
+ entry: resolve(directory, "entry.ts"),
177
+ mainSource: rokuMainSource(scene),
178
+ };
179
+ }
180
+ export async function prepareRokuProject(
181
+ root = process.cwd(),
182
+ { outputDirectory, frontend = true, profile = "production", refresh } = {},
183
+ ) {
184
+ const compilation = rokuBuildProfile(profile);
185
+ outputDirectory ??= resolve(root, ".roku", compilation.development ? "development" : ".");
186
+ const config = readRokuConfig(root),
187
+ generated = resolve(outputDirectory, "src/generated");
188
+ if (config.entryMode === "mount")
189
+ throw Error(
190
+ "A custom mount entry uses generateSdkEntry and createRokuSdkConfiguration in its existing build pipeline",
191
+ );
192
+ mkdirSync(generated, { recursive: true });
193
+ prepareNativeComponents(generated);
194
+ const preparedFonts = prepareRokuFontAssets({
195
+ assets: Object.fromEntries(
196
+ Object.entries(config.fonts.assets).map(([family, specifier]) => [
197
+ family,
198
+ resolveProjectFont(root, specifier),
199
+ ]),
200
+ ),
201
+ variants: config.fonts.variants,
202
+ families: config.fonts.families,
203
+ outputDirectory: resolve(generated, "fonts"),
204
+ });
205
+ const assets = Object.entries(preparedFonts.assets);
206
+ const fontImports = [];
207
+ for (const [index, [, path]] of assets.entries()) {
208
+ fontImports.push(
209
+ `import font${index} from ${JSON.stringify("./" + relative(generated, path).split("\\").join("/"))};`,
210
+ );
211
+ }
212
+ write(
213
+ resolve(generated, "fontAssets.ts"),
214
+ fontImports.join("\n") +
215
+ `\nexport const fontAssets={${assets.map(([family], index) => `${JSON.stringify(family)}:font${index}`).join(",")}};\n`,
216
+ );
217
+ const key = JSON.stringify(config.name),
218
+ entry = JSON.stringify(resolve(root, config.entry));
219
+ if (refresh && (config.bundler !== "metro" || !compilation.development))
220
+ throw Error("Fast Refresh requires the development Metro frontend");
221
+ const imageDirectory = refresh ? resolve(refresh.session.directory, "images") : generated;
222
+ const images = createRokuImageAssets({ root, generatedDirectory: imageDirectory, reset: true });
223
+ let imageMetafile;
224
+ let refreshGraph;
225
+ const contents = `import {AppRegistry} from "react-native-roku/app-registry";import {mountRegisteredApplication} from "react-native-roku/application";import type {RokuHostContext} from "react-native-roku/host";\nexport function mountApplication(context:RokuHostContext){return mountRegisteredApplication(context,{appKey:${key},webRuntime:typeof document==='undefined'?'portable':'host',load(){const entry=require(${entry});${config.entryMode === "registry" ? "" : `AppRegistry.registerComponent(${key},()=>entry.default);`}}});}\n`;
226
+ if (frontend) {
227
+ await buildSurfaceAssets(root, generated);
228
+ const entryPath = refresh
229
+ ? resolve(refresh.session.directory, "application-entry.ts")
230
+ : resolve(generated, "application-entry.ts");
231
+ write(entryPath, contents);
232
+ if (config.bundler === "metro") {
233
+ const result = await buildRokuMetroModules({
234
+ root,
235
+ entry: entryPath,
236
+ outfile: resolve(generated, "application.mjs"),
237
+ profile,
238
+ workDirectory: refresh
239
+ ? resolve(refresh.session.directory, "metro")
240
+ : resolve(outputDirectory, "metro"),
241
+ imageAssets: { generatedDirectory: imageDirectory },
242
+ refresh,
243
+ });
244
+ imageMetafile = result.metafile;
245
+ refreshGraph = result.refreshGraph;
246
+ write(resolve(generated, "frontend.metro.json"), JSON.stringify(result, null, 2));
247
+ } else {
248
+ const result = await buildRokuReactModules({
249
+ absWorkingDir: root,
250
+ entryPoints: [entryPath],
251
+ outfile: resolve(generated, "application.mjs"),
252
+ bundle: true,
253
+ format: "esm",
254
+ platform: "neutral",
255
+ target: "es2021",
256
+ jsx: "automatic",
257
+ tsconfig: existsSync(resolve(root, "tsconfig.react.json"))
258
+ ? resolve(root, "tsconfig.react.json")
259
+ : undefined,
260
+ define: compilation.defines,
261
+ plugins: [
262
+ images.esbuildPlugin(),
263
+ rokuPlugin({ root, generatedDirectory: generated }),
264
+ ...(config.reactCompiler
265
+ ? [appReactCompiler(root, generated, profile === "production")]
266
+ : []),
267
+ ],
268
+ metafile: true,
269
+ sourcemap: true,
270
+ });
271
+ imageMetafile = result.metafile;
272
+ write(resolve(generated, "frontend.metafile.json"), JSON.stringify(result.metafile, null, 2));
273
+ }
274
+ }
275
+ const usedImageSources = new Set(
276
+ Object.values(imageMetafile?.outputs ?? {}).flatMap((output) =>
277
+ Object.entries(output.inputs)
278
+ .filter(([, input]) => input.bytesInOutput > 0)
279
+ .map(([path]) => path),
280
+ ),
281
+ );
282
+ const imageAssets = images.writeSdkModule(resolve(generated, "imageAssets.ts"), usedImageSources);
283
+ write(
284
+ resolve(generated, "application.d.mts"),
285
+ 'import type {RokuHostContext,MountedRokuApplication} from "react-native-roku/host";export declare function mountApplication(context:RokuHostContext):MountedRokuApplication;\n',
286
+ );
287
+ const native = generateSdkEntry({
288
+ directory: generated,
289
+ name: config.name,
290
+ defaultFamily: config.fonts.defaultFamily,
291
+ fontFamilies: preparedFonts.families,
292
+ viewport: config.viewport,
293
+ background: config.background,
294
+ storageNamespace: config.storageNamespace ?? config.name,
295
+ staticAssetsModule: "./imageAssets",
296
+ ...(frontend ? { cornerMasksModule: "./surfaceAssets" } : {}),
297
+ });
298
+ write(resolve(outputDirectory, "pkg/source/Main.brs"), native.mainSource);
299
+
300
+ write(
301
+ resolve(outputDirectory, "roku-config.ts"),
302
+ `import type {RokuConfig} from "@roku-sdk/rsg-ts/roku-config";export default {outDir:"dist/sdk",app:{entryPoint:"src/generated/entry.ts",images:{convertToWebp:false,generateHd:false},manifestEntries:{title:${JSON.stringify(config.displayName)},major_version:0,minor_version:1,build_version:0,ui_resolutions:"fhd",rsg_version:"2.0",run_as_process:1,sdk_instant_resume:1}}} satisfies RokuConfig;\n`,
303
+ );
304
+ write(
305
+ resolve(outputDirectory, "tsconfig.json"),
306
+ JSON.stringify(
307
+ {
308
+ extends: "@roku-sdk/rsg-ts/tsconfig.json",
309
+ compilerOptions: {
310
+ lib: ["ES2022", "DOM"],
311
+ types: ["node", "react", "@roku-sdk/interfaces/global"],
312
+ rootDir: root,
313
+ composite: false,
314
+ incremental: false,
315
+ noEmit: true,
316
+ strict: true,
317
+ jsx: "react-jsx",
318
+ jsxImportSource: "@roku-sdk/solid",
319
+ },
320
+ include: ["src", "roku-config.ts"],
321
+ },
322
+ null,
323
+ 2,
324
+ ),
325
+ );
326
+ write(
327
+ resolve(outputDirectory, "build-profile.json"),
328
+ JSON.stringify(
329
+ {
330
+ schema: "react-native-roku-profile/v1",
331
+ profile: compilation.name,
332
+ },
333
+ null,
334
+ 2,
335
+ ) + "\n",
336
+ );
337
+ return {
338
+ config,
339
+ directory: outputDirectory,
340
+ generated,
341
+ native,
342
+ profile: compilation.name,
343
+ fonts: preparedFonts,
344
+ imageAssets: Object.fromEntries(imageAssets),
345
+ imageDirectory,
346
+ ...(refreshGraph ? { refreshGraph } : {}),
347
+ };
348
+ }
349
+ export async function buildRokuProject(root = process.cwd(), { profile = "production" } = {}) {
350
+ const result = await prepareRokuProject(root, { profile });
351
+ write(
352
+ resolve(result.directory, "package.json"),
353
+ JSON.stringify({
354
+ name: "roku-generated-host",
355
+ private: true,
356
+ type: "module",
357
+ }),
358
+ );
359
+ const command = resolve(root, "node_modules/@roku-sdk/tooling/bin/rk.mjs");
360
+ const built = spawnSync(process.execPath, [command, "build", "--debug", "--local"], {
361
+ cwd: result.directory,
362
+ stdio: "inherit",
363
+ });
364
+ if (built.status !== 0) throw Error(`Roku SDK build exited ${built.status}`);
365
+ const bundle = resolve(result.directory, "dist/sdk/bundle"),
366
+ zip = resolve(
367
+ root,
368
+ "dist",
369
+ profile === "development" ? "roku-app-development.zip" : "roku-app.zip",
370
+ );
371
+ copyFileSync(
372
+ resolve(result.directory, "build-profile.json"),
373
+ resolve(bundle, "build-profile.json"),
374
+ );
375
+ mkdirSync(dirname(zip), { recursive: true });
376
+ rmSync(zip, { force: true });
377
+ const zipped = spawnSync("zip", ["-q", "-r", zip, "."], {
378
+ cwd: bundle,
379
+ stdio: "inherit",
380
+ });
381
+ if (zipped.status !== 0) throw Error("Roku ZIP creation failed");
382
+ return { bundle, zip, profile: result.profile };
383
+ }
384
+ export function doctorRokuProject(root = process.cwd()) {
385
+ const checks = doctorEnvironment(root).checks;
386
+ let config;
387
+ try {
388
+ config = readRokuConfig(root);
389
+ checks.push({ name: "configuration and entry", status: "passed" });
390
+ } catch (error) {
391
+ checks.push({ name: "configuration and entry", status: "failed", message: error.message });
392
+ }
393
+ const check = (name, work) => {
394
+ try {
395
+ work();
396
+ checks.push({ name, status: "passed" });
397
+ } catch (error) {
398
+ checks.push({ name, status: "failed", message: error.message });
399
+ }
400
+ };
401
+ if (config)
402
+ check("packaged fonts", () => {
403
+ for (const specifier of Object.values(config.fonts.assets))
404
+ if (!existsSync(resolveProjectFont(root, specifier)))
405
+ throw Error("A font asset is missing");
406
+ });
407
+ if (config?.bundler === "metro")
408
+ for (const [name, version] of Object.entries(toolchain.optionalPackages.metro))
409
+ check(`Metro: ${name}`, () => {
410
+ const expected = version.startsWith("npm:")
411
+ ? version.slice(version.lastIndexOf("@") + 1)
412
+ : version;
413
+ if (installedPackage(root, name).version !== expected)
414
+ throw Error(`Install the reviewed optional Metro tool cohort: ${name}@${version}`);
415
+ });
416
+ return {
417
+ status: checks.every((value) => value.status === "passed") ? "passed" : "failed",
418
+ checks,
419
+ deviceQualified: false,
420
+ qualification: "Host/build readiness only; physical Roku qualification remains pending",
421
+ };
422
+ }
423
+
424
+ export async function buildRokuPreview(
425
+ root = process.cwd(),
426
+ { outputDirectory = resolve(root, ".roku/preview"), profile = "development", refresh } = {},
427
+ ) {
428
+ const result = await prepareRokuProject(root, {
429
+ outputDirectory: resolve(outputDirectory, "project"),
430
+ profile,
431
+ refresh,
432
+ });
433
+ const { config, generated } = result;
434
+ for (const name of Object.keys(result.imageAssets)) {
435
+ const target = resolve(outputDirectory, "assets", name);
436
+ mkdirSync(dirname(target), { recursive: true });
437
+ copyFileSync(resolve(result.imageDirectory, "assets", name), target);
438
+ }
439
+ const cornerMasks = [0, 1, 2, 3].map((index) => `surfaces/corner-${index}.png`);
440
+ mkdirSync(resolve(outputDirectory, "surfaces"), { recursive: true });
441
+ for (const path of cornerMasks)
442
+ copyFileSync(resolve(generated, path), resolve(outputDirectory, path));
443
+ const graphics = { effects: true, composedMasks: true };
444
+ const fonts = {};
445
+ for (const [index, [family, path]] of Object.entries(result.fonts.assets).entries()) {
446
+ const target = resolve(outputDirectory, `fonts/font-${index}.ttf`);
447
+ mkdirSync(dirname(target), { recursive: true });
448
+ copyFileSync(path, target);
449
+ fonts[family] = `/fonts/font-${index}.ttf`;
450
+ }
451
+ let bootstrap = "";
452
+ if (refresh) {
453
+ const runtime = writeRokuRefreshBootstrap({
454
+ root,
455
+ ...refresh,
456
+ outfile: resolve(outputDirectory, "refresh-bootstrap.mjs"),
457
+ });
458
+ bootstrap = `import ${JSON.stringify(runtime)};`;
459
+ const identity = digest(
460
+ JSON.stringify({
461
+ config: developmentConfigFiles.map((name) => [
462
+ name,
463
+ existsSync(resolve(root, name)) ? digest(readFileSync(resolve(root, name))) : null,
464
+ ]),
465
+ runtime: runtimeInputs(),
466
+ fonts: Object.entries(result.fonts.assets).map(([name, path]) => [
467
+ name,
468
+ digest(readFileSync(path)),
469
+ ]),
470
+ images: Object.keys(result.imageAssets)
471
+ .sort()
472
+ .map((name) => [
473
+ name,
474
+ digest(readFileSync(resolve(result.imageDirectory, "assets", name))),
475
+ ]),
476
+ }),
477
+ );
478
+ refresh.session.stage({
479
+ generation: refresh.generation,
480
+ graph: result.refreshGraph,
481
+ identity,
482
+ outputDirectory,
483
+ });
484
+ }
485
+ const source = `${bootstrap}import {CanvasSceneGraph,createCanvasTextMetrics,createCanvasTextRaster,createCanvasTextEntry} from "react-native-roku/preview";import {NativeSystemState} from "react-native-roku/system";import {mountApplication} from ${JSON.stringify(resolve(generated, "application.mjs"))};
486
+ const canvas=document.querySelector('canvas'),scene=new CanvasSceneGraph(canvas),text=createCanvasTextMetrics(scene,{defaultFamily:${JSON.stringify(config.fonts.defaultFamily)},assets:${JSON.stringify(fonts)},families:${JSON.stringify(result.fonts.families)}}),system=new NativeSystemState({appState:'active',reduceMotion:false,screenReader:false,colorScheme:'dark'});const errors=[];
487
+ const keyboard=createCanvasTextEntry();const app=mountApplication({scene,text,system,textEntry:keyboard,textRaster:createCanvasTextRaster(scene,text),graphics:${JSON.stringify(graphics)},viewport:${JSON.stringify(config.viewport)},onError(error){errors.push(error.message);document.querySelector('#status').textContent=error.message;}});
488
+ globalThis.__RNR_ROKU_REFRESH__?.setApplication(app,()=>{document.querySelector('#status').textContent='Host preview · focus observations are fixtures · device qualification pending';});
489
+ const map={ArrowUp:'up',ArrowDown:'down',ArrowLeft:'left',ArrowRight:'right',Enter:'select',Escape:'back'},keys=[];for(const type of ['keydown','keyup']){const handler=event=>{const key=map[event.key];if(key&&!stopped&&!keyboard.isOpen()){event.preventDefault();app.remote({key,phase:type==='keyup'?'up':event.repeat?'repeat':'down'});}};keys.push([type,handler]);document.addEventListener(type,handler);}
490
+ let stopped=false,frame,seen=-1;function observe(){if(stopped)return;const id=scene.focusRequests.at(-1);if(id&&seen!==scene.focusRequestSequence){const node=[...scene.nodes.values()].find(value=>value.fields.id===id);if(node){seen=scene.focusRequestSequence;scene.emit(node,'focusedChild',id);}}frame=requestAnimationFrame(observe);}observe();
491
+ app.whenCommitted().then(()=>document.querySelector('#status').textContent='Host preview · focus observations are fixtures · device qualification pending',error=>document.querySelector('#status').textContent=error.message);
492
+ let closing;const stop=()=>{if(closing)return closing;stopped=true;cancelAnimationFrame(frame);for(const [type,handler]of keys)document.removeEventListener(type,handler);window.removeEventListener('pagehide',stop);globalThis.__RNR_ROKU_REFRESH__?.dispose();closing=Promise.resolve(app.dispose()).finally(()=>{keyboard.dispose();text.dispose();scene.dispose();});return closing;};
493
+ window.__ROKU_DEV__={snapshot:()=>({texts:[...scene.nodes.values()].map(node=>node.fields.text).filter(Boolean),nodes:scene.nodes.size,listeners:scene.listenerCount,errors,disposed:stopped,refresh:globalThis.__RNR_ROKU_REFRESH__?.snapshot()}),remote:event=>stopped||keyboard.isOpen()?false:app.remote(event),dispose:stop};
494
+ window.addEventListener('pagehide',stop,{once:true});`;
495
+ await build({
496
+ absWorkingDir: root,
497
+ stdin: {
498
+ contents: source,
499
+ resolveDir: root,
500
+ sourcefile: "roku-preview-entry.ts",
501
+ },
502
+ outfile: resolve(outputDirectory, "preview.js"),
503
+ bundle: true,
504
+ format: "esm",
505
+ platform: "browser",
506
+ target: "es2022",
507
+ sourcemap: true,
508
+ define: rokuBuildProfile(profile).defines,
509
+ });
510
+ write(
511
+ resolve(outputDirectory, "index.html"),
512
+ `<!doctype html><html><meta charset="utf-8"><title>Roku development preview</title><body style="margin:0;background:#101014;color:white;font:16px system-ui"><p id="status">Loading…</p><canvas tabindex="0" width="${config.viewport.width}" height="${config.viewport.height}" style="width:100%;height:auto"></canvas><script type="module" src="/preview.js"></script></body></html>`,
513
+ );
514
+ return outputDirectory;
515
+ }
516
+ export async function createRokuProjectDevServer(
517
+ root = process.cwd(),
518
+ { profile = "development", port: requestedPort, onBuild = () => {} } = {},
519
+ ) {
520
+ rokuBuildProfile(profile);
521
+ const { createRokuDevServer } = await import("./dev.mjs");
522
+ const config = readRokuConfig(root);
523
+ const port = requestedPort ?? Number(process.env.ROKU_DEV_PORT ?? config.dev?.port ?? 9389);
524
+ if (!Number.isInteger(port) || (port < 1024 && requestedPort !== 0) || port < 0 || port > 65535)
525
+ throw Error("ROKU_DEV_PORT must be 1024–65535");
526
+ const workspace = createRokuDevWorkspace(resolve(root, ".roku/dev"), { label: config.name });
527
+ const session = createRokuMetroRefreshSession({
528
+ root,
529
+ directory: resolve(workspace.directory, "frontend"),
530
+ });
531
+ const server = await createRokuDevServer({
532
+ port,
533
+ watchPaths: [
534
+ resolve(root, "src"),
535
+ ...developmentConfigFiles.map((name) => resolve(root, name)),
536
+ ],
537
+ build: async ({ generation }) => {
538
+ session.discard(generation);
539
+ const refresh =
540
+ profile === "development" && readRokuConfig(root).bundler === "metro"
541
+ ? { session, generation }
542
+ : undefined;
543
+ const directory = await buildRokuPreview(root, {
544
+ outputDirectory: workspace.generation(generation),
545
+ profile,
546
+ refresh,
547
+ });
548
+ return { directory, ...(refresh ? { refresh: session.plan(generation) } : {}) };
549
+ },
550
+ onBuild: (state) => {
551
+ if (state.state === "ready") {
552
+ if (session.plan(state.generation)) session.publish(state.generation);
553
+ workspace.publish(state.generation);
554
+ }
555
+ onBuild(state);
556
+ },
557
+ }).catch((error) => {
558
+ workspace.dispose();
559
+ session.dispose();
560
+ throw error;
561
+ });
562
+ const close = server.close;
563
+ return {
564
+ ...server,
565
+ workspaceDirectory: workspace.directory,
566
+ async close() {
567
+ await close();
568
+ session.dispose();
569
+ workspace.dispose();
570
+ },
571
+ };
572
+ }
573
+ export async function devRokuProject(root = process.cwd(), { profile = "development" } = {}) {
574
+ const server = await createRokuProjectDevServer(root, {
575
+ profile,
576
+ onBuild: (state) => console.log(JSON.stringify(state)),
577
+ });
578
+ console.log(`Roku development preview: ${server.url}`);
579
+ await new Promise((resolve) => {
580
+ const stop = () => {
581
+ void server.close().then(resolve);
582
+ };
583
+ process.once("SIGINT", stop);
584
+ process.once("SIGTERM", stop);
585
+ });
586
+ }
587
+
588
+ function rokuMainSource(scene) {
589
+ return `sub Main()\n screen=CreateObject("roSGScreen")\n port=CreateObject("roMessagePort")\n screen.setMessagePort(port)\n scene=screen.CreateScene("${scene}")\n scene.observeField("exitRequested",port)\n screen.show()\n while true\n message=wait(0,port)\n if type(message)="roSGScreenEvent"\n if message.isScreenClosed() then return\n else if type(message)="roSGNodeEvent"\n if message.getField()="exitRequested" and message.getData()=true then return\n end if\n end while\nend sub\n`;
590
+ }
591
+
592
+ export function createRokuSdkConfiguration(root, preBuild) {
593
+ const config = readRokuConfig(root);
594
+ return {
595
+ outDir: "dist/sdk",
596
+ pipeline: { build: { preBuild } },
597
+ app: {
598
+ entryPoint: "src/generated/entry.ts",
599
+ images: { convertToWebp: false, generateHd: false },
600
+ logger: { baseLogLevel: "INFO", currentLogLevel: "INFO" },
601
+ manifestEntries: {
602
+ title: config.displayName,
603
+ major_version: 0,
604
+ minor_version: 1,
605
+ build_version: 0,
606
+ ui_resolutions: "fhd",
607
+ rsg_version: "2.0",
608
+ run_as_process: 1,
609
+ sdk_instant_resume: 1,
610
+ splash_color: `0x${config.background.slice(1)}FF`,
611
+ splash_min_time: 0,
612
+ },
613
+ },
614
+ };
615
+ }