@bake-native/core 0.0.0 → 0.1.0-rc.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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/THIRD_PARTY_NOTICES.txt +548 -0
  3. package/bake-prelude.js +189 -0
  4. package/batch-contract.json +21 -0
  5. package/batch-wire.js +674 -0
  6. package/compat.json +64 -0
  7. package/controls.css +108 -0
  8. package/determinism.js +175 -0
  9. package/devtools.d.ts +13 -0
  10. package/devtools.js +73 -0
  11. package/dialogs.js +59 -0
  12. package/direct-style.js +105 -0
  13. package/direct-table.js +261 -0
  14. package/dist/bake.mjs +2211 -0
  15. package/dist/build-CMsvCcZ0.mjs +1 -0
  16. package/dist/build-CkLSZw06.mjs +5514 -0
  17. package/dist/build-tools-Dxyl6XAf.mjs +80 -0
  18. package/dist/client-Cm7o6dQd.mjs +17544 -0
  19. package/dist/compiler.mjs +4 -0
  20. package/dist/config-B1W8gfZY.mjs +12 -0
  21. package/dist/dev-Cskd8Hl4.mjs +986 -0
  22. package/dist/direct-report-Bdda-k_Y.mjs +153 -0
  23. package/dist/direct-report-Du44nNWl.mjs +1 -0
  24. package/dist/index.d.mts +176 -0
  25. package/dist/index.mjs +1 -0
  26. package/dist/intl-ROnAp2qO.mjs +75 -0
  27. package/dist/jiti-stub-CKcaShwE.mjs +5 -0
  28. package/dist/native-views-BuzB9x5H.mjs +7849 -0
  29. package/dist/octane/package.json +5 -0
  30. package/dist/package-KkUSMoji.mjs +2784 -0
  31. package/dist/react/package.json +13 -0
  32. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  33. package/dist/run-D2aPm54a.mjs +6632 -0
  34. package/dist/scope-8W2aIuQ9.mjs +262 -0
  35. package/dist/screens/BakeNativeScreen.native.ts +9 -0
  36. package/dist/screens/package.json +5 -0
  37. package/dom-exception.js +31 -0
  38. package/element-api.js +158 -0
  39. package/first-screen.js +30 -0
  40. package/fonts/Geist-Italic-Variable.ttf +0 -0
  41. package/fonts/Geist-Variable.ttf +0 -0
  42. package/fonts/GeistMono-Italic-Variable.ttf +0 -0
  43. package/fonts/GeistMono-Variable.ttf +0 -0
  44. package/fonts/OFL.txt +93 -0
  45. package/fonts/README.md +27 -0
  46. package/fonts/geist-italic.css +8 -0
  47. package/fonts/geist-mono-italic.css +8 -0
  48. package/fonts/geist-mono.css +8 -0
  49. package/fonts/geist.css +8 -0
  50. package/header-icons.json +53 -0
  51. package/host-runtime.js +508 -0
  52. package/image-props.js +17 -0
  53. package/index.d.ts +8 -0
  54. package/index.js +7 -0
  55. package/licenses/Apache-2.0.txt +73 -0
  56. package/locale-entry.d.ts +1 -0
  57. package/locale-entry.js +1 -0
  58. package/locale.d.ts +28 -0
  59. package/locale.js +124 -0
  60. package/markup-support.js +87 -0
  61. package/media-element.js +115 -0
  62. package/native-args-entry.js +2 -0
  63. package/native-args.d.ts +7 -0
  64. package/native-args.js +155 -0
  65. package/native-entry.js +1 -0
  66. package/native-globals.d.ts +156 -0
  67. package/native-scenarios.d.ts +17 -0
  68. package/native-scenarios.js +46 -0
  69. package/native-support.json +349 -0
  70. package/native.d.ts +52 -0
  71. package/native.js +237 -0
  72. package/package.json +142 -4
  73. package/page-elements.js +123 -0
  74. package/runtime-provides.json +412 -0
  75. package/safe-area.d.ts +1 -0
  76. package/safe-area.js +44 -0
  77. package/swift-ui/modifiers.js +164 -0
  78. package/tab-icons.js +62 -0
  79. package/templates/create/tabs/AGENTS.md +22 -0
  80. package/templates/create/tabs/README.md +43 -0
  81. package/templates/create/tabs/_gitignore +13 -0
  82. package/templates/create/tabs/android/app/build.gradle.kts +79 -0
  83. package/templates/create/tabs/android/app/src/main/AndroidManifest.xml +39 -0
  84. package/templates/create/tabs/android/app/src/main/kotlin/MainActivity.kt +35 -0
  85. package/templates/create/tabs/android/app/src/main/res/values/themes.xml +8 -0
  86. package/templates/create/tabs/android/build.gradle.kts +5 -0
  87. package/templates/create/tabs/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  88. package/templates/create/tabs/android/gradle/wrapper/gradle-wrapper.properties +9 -0
  89. package/templates/create/tabs/android/gradle.properties +3 -0
  90. package/templates/create/tabs/android/gradlew +248 -0
  91. package/templates/create/tabs/android/settings.gradle.kts +47 -0
  92. package/templates/create/tabs/bake.config.ts +10 -0
  93. package/templates/create/tabs/ios/App/App.swift +30 -0
  94. package/templates/create/tabs/ios/build.sh +23 -0
  95. package/templates/create/tabs/ios/project.yml +57 -0
  96. package/templates/create/tabs/macos/Package.swift +24 -0
  97. package/templates/create/tabs/macos/Sources/__SWIFT_NAME__/App.swift +146 -0
  98. package/templates/create/tabs/macos/build.sh +4 -0
  99. package/templates/create/tabs/package.json +23 -0
  100. package/templates/create/tabs/pnpm-workspace.yaml +6 -0
  101. package/templates/create/tabs/src/App.tsrx +92 -0
  102. package/templates/create/tabs/src/App.tsx +67 -0
  103. package/templates/create/tabs/src/styles.css +32 -0
  104. package/templates/create/tabs/tsconfig.json +5 -0
  105. package/templates/create/tabs/windows/Cargo.toml +29 -0
  106. package/templates/create/tabs/windows/build.rs +9 -0
  107. package/templates/create/tabs/windows/src/main.rs +52 -0
  108. package/templates/create/tabs/windows/src/shell.rs +316 -0
  109. package/templates/module/__NAME__.kt +20 -0
  110. package/templates/module/__NAME__.native.ts +24 -0
  111. package/templates/module/__NAME__.swift +25 -0
  112. package/templates/module/__NAME__.web.ts +13 -0
  113. package/templates/module/__NAME__Test.kt +26 -0
  114. package/templates/module/__NAME__Tests.swift +25 -0
  115. package/templates/module/__SNAKE__.rs +43 -0
  116. package/text.d.ts +20 -0
  117. package/text.js +100 -0
  118. package/transform-entry.js +1 -0
  119. package/transform.d.ts +15 -0
  120. package/transform.js +98 -0
  121. package/tsconfig.native.json +16 -0
  122. package/ui/scope.js +103 -0
  123. package/ui/swift.js +106 -0
  124. package/ui/ui.css +272 -0
  125. package/view-ref-writer.js +268 -0
  126. package/view-ref.d.ts +26 -0
  127. package/view-ref.js +85 -0
  128. package/views/Video.native.ts +68 -0
  129. package/views/generated/VideoViewAndroid.h +68 -0
  130. package/views/generated/VideoViewJSI.h +94 -0
  131. package/views/generated/VideoViewSpec.kt +113 -0
  132. package/views/generated/apple/VideoViewJSI/VideoViewJSIApple.cpp +40 -0
  133. package/views/generated/apple/VideoViewJSI/include/VideoViewJSIApple.h +28 -0
  134. package/views/generated/apple/VideoViewSpec/VideoViewInterop.swift +39 -0
  135. package/views/generated/apple/VideoViewSpec/VideoViewSpec.swift +186 -0
  136. package/views/generated/video_view_spec.rs +189 -0
  137. package/views.d.ts +24 -0
  138. package/views.js +45 -0
  139. package/virtual-window.js +35 -0
  140. package/visibility.js +75 -0
  141. package/web-crypto.js +84 -0
  142. package/web-fetch.js +1071 -0
  143. package/README.md +0 -3
@@ -0,0 +1,2784 @@
1
+ import { $ as RUNTIME_PROVIDES, H as mergeNativeDeps, K as readNativeDeps, P as readLock, Ut as packageRoot$1, W as nativeDepLibraries, Wt as readPackageJson, _ as specsSchema, ct as SYSTEM_MODULES, d as calledSpecs, g as snake, h as rustSpec, it as memberSignatures, l as appModuleFiles, o as viewFiles, ot as satisfies, p as kotlinSpec, q as unitPath, rt as defaultRuntimeRange, t as readViewSpec, u as appModuleSpecs, v as swiftBakeNativeImports, y as swiftSpec } from "./native-views-BuzB9x5H.mjs";
2
+ import { chmodSync, closeSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createHash } from "node:crypto";
6
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
7
+ import { tmpdir } from "node:os";
8
+ // notices.mjs
9
+ const here = dirname(fileURLToPath(import.meta.url));
10
+ const packageRoot = existsSync(join(here, "licenses")) ? here : dirname(here);
11
+ const NOTICES = "THIRD_PARTY_NOTICES.txt";
12
+ const NOTICES_JSON = "THIRD_PARTY_NOTICES.json";
13
+ const read = (file) => readFileSync(file, "utf8").replace(/\r\n/g, "\n");
14
+ const LICENSE_FILE = /^(licen[cs]e|copying|copyright|notice|unlicense)([-_.].*)?$/i;
15
+ /** A package's or crate's own license files: [{ title, text }]. */
16
+ function licenseFiles(dir, extra = []) {
17
+ const names = readdirSync(dir).filter((f) => LICENSE_FILE.test(f) && statSync(join(dir, f)).isFile());
18
+ for (const f of extra) if (f && !names.includes(f) && existsSync(join(dir, f))) names.push(f);
19
+ return names.sort().map((f) => ({
20
+ title: f,
21
+ text: read(join(dir, f))
22
+ }));
23
+ }
24
+ /** A license text this package ships (licenses/<id>.txt), for a component that has none of its own. */
25
+ const canonicalLicense = (id) => ({
26
+ title: `${id} (@bake-native/core licenses/${id}.txt)`,
27
+ text: read(join(packageRoot, "licenses", `${id}.txt`))
28
+ });
29
+ /**
30
+ * Third-party files in the npm packages' own sources (no build bundles them), by package.
31
+ * `files`: package-relative paths. `texts`: { file } (package-relative), { zip, entry } (a file
32
+ * inside a zip in the package, read by the release tool), { canonical } (licenses/<id>.txt) or
33
+ * { title, text }. tools/release/third-party.mjs lists them in the package's notices; `bake build`
34
+ * lists one in an app's when the app's bundle contains one of its files.
35
+ */
36
+ const ASSETS = {
37
+ "@bake-native/core": [
38
+ {
39
+ name: "Geist and Geist Mono fonts",
40
+ version: {
41
+ file: "fonts/README.md",
42
+ pattern: "version (\\d+\\.\\d+\\.\\d+)"
43
+ },
44
+ license: "OFL-1.1",
45
+ url: "https://github.com/vercel/geist-font",
46
+ files: [
47
+ "fonts/Geist-Variable.ttf",
48
+ "fonts/Geist-Italic-Variable.ttf",
49
+ "fonts/GeistMono-Variable.ttf",
50
+ "fonts/GeistMono-Italic-Variable.ttf"
51
+ ],
52
+ texts: [{ file: "fonts/OFL.txt" }]
53
+ },
54
+ {
55
+ name: "Gradle Wrapper",
56
+ version: {
57
+ file: "templates/create/tabs/android/gradle/wrapper/gradle-wrapper.properties",
58
+ pattern: "gradle-([\\d.]+)-bin\\.zip"
59
+ },
60
+ license: "Apache-2.0",
61
+ url: "https://github.com/gradle/gradle",
62
+ files: ["templates/create/tabs/android/gradlew", "templates/create/tabs/android/gradle/wrapper/gradle-wrapper.jar"],
63
+ texts: [{
64
+ zip: "templates/create/tabs/android/gradle/wrapper/gradle-wrapper.jar",
65
+ entry: "META-INF/LICENSE",
66
+ title: "gradle-wrapper.jar META-INF/LICENSE"
67
+ }]
68
+ },
69
+ {
70
+ name: "Material Icons and Material Symbols (24x24 SVG path data)",
71
+ version: null,
72
+ license: "Apache-2.0",
73
+ url: "https://github.com/google/material-design-icons",
74
+ files: ["tab-icons.js", "header-icons.json"],
75
+ texts: [{
76
+ title: "Notice",
77
+ text: "The icon geometry in tab-icons.js and header-icons.json (24x24 SVG paths) comes from Google's\nMaterial Icons and Material Symbols, licensed under the Apache License, Version 2.0."
78
+ }, { canonical: "Apache-2.0" }]
79
+ }
80
+ ],
81
+ "@bake-native/react": [{
82
+ name: "Radix UI Primitives (the native modules in radix/ follow the published ones)",
83
+ version: null,
84
+ license: "MIT",
85
+ url: "https://github.com/radix-ui/primitives",
86
+ files: [
87
+ "radix/dismissable-layer.js",
88
+ "radix/focus-scope.js",
89
+ "radix/portal.js",
90
+ "radix/presence.js",
91
+ "radix/primitive.js"
92
+ ],
93
+ texts: [{ file: "radix/LICENSE" }]
94
+ }]
95
+ };
96
+ /**
97
+ * An ASSETS entry as a component of the package in `dir`. `zip(file, entry)` reads a zip entry
98
+ * (only the release tool needs one: no app bundle contains the Gradle wrapper).
99
+ */
100
+ function assetComponent(asset, dir, { where = asset.files, zip } = {}) {
101
+ const version = asset.version && existsSync(join(dir, asset.version.file)) ? read(join(dir, asset.version.file)).match(new RegExp(asset.version.pattern))?.[1] ?? null : null;
102
+ const texts = asset.texts.flatMap((t) => {
103
+ if (t.canonical) return [canonicalLicense(t.canonical)];
104
+ if (t.text) return [{
105
+ title: t.title,
106
+ text: t.text
107
+ }];
108
+ if (t.zip) {
109
+ if (!zip) throw new Error(`${asset.name}: its license text is inside ${t.zip}, which only the release tool reads`);
110
+ const text = zip(join(dir, t.zip), t.entry);
111
+ return text ? [{
112
+ title: t.title,
113
+ text
114
+ }] : [];
115
+ }
116
+ return existsSync(join(dir, t.file)) ? [{
117
+ title: t.file,
118
+ text: read(join(dir, t.file))
119
+ }] : [];
120
+ });
121
+ return {
122
+ name: asset.name,
123
+ version,
124
+ license: asset.license,
125
+ url: asset.url,
126
+ where,
127
+ texts
128
+ };
129
+ }
130
+ const packageCache = /* @__PURE__ */ new Map();
131
+ /** The nearest directory at or above `dir` with a package.json that has a name: { dir, pkg } or null. */
132
+ function owningPackage(dir) {
133
+ if (packageCache.has(dir)) return packageCache.get(dir);
134
+ let found = null;
135
+ const file = join(dir, "package.json");
136
+ if (existsSync(file)) try {
137
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
138
+ if (typeof pkg.name === "string" && pkg.name) found = {
139
+ dir,
140
+ pkg
141
+ };
142
+ } catch {}
143
+ if (!found && dirname(dir) !== dir) found = owningPackage(dirname(dir));
144
+ packageCache.set(dir, found);
145
+ return found;
146
+ }
147
+ const real = (p) => {
148
+ try {
149
+ return realpathSync(p);
150
+ } catch {
151
+ return resolve(p);
152
+ }
153
+ };
154
+ /**
155
+ * The npm packages, and the ASSETS files of them, that the modules `ids` of a bundle come from.
156
+ * `ids`: absolute module paths as the bundler reports them (virtual \0 ids and queries are
157
+ * ignored) and the source files of the fonts and other assets it copied. The app's own package
158
+ * (`root`) is not listed. `where`: the output file the bundle is (app.hbc, assets/index-x.js).
159
+ * Returns { components, problems }: a package without a license text is a problem (the caller
160
+ * decides whether it fails).
161
+ */
162
+ function bundleComponents(ids, { root, where }) {
163
+ const own = real(root);
164
+ const byDir = /* @__PURE__ */ new Map();
165
+ for (const raw of ids) {
166
+ if (typeof raw !== "string" || raw.startsWith("\0")) continue;
167
+ const id = raw.split("?")[0];
168
+ if (!isAbsolute(id) || !existsSync(id)) continue;
169
+ const owner = owningPackage(dirname(real(id)));
170
+ if (!owner || owner.dir === own) continue;
171
+ (byDir.get(owner.dir) ?? byDir.set(owner.dir, {
172
+ ...owner,
173
+ files: /* @__PURE__ */ new Set()
174
+ }).get(owner.dir)).files.add(relative(owner.dir, real(id)).split("\\").join("/"));
175
+ }
176
+ const components = [];
177
+ const problems = [];
178
+ for (const { dir, pkg, files } of byDir.values()) {
179
+ for (const asset of ASSETS[pkg.name] ?? []) {
180
+ const used = asset.files.filter((f) => files.has(f));
181
+ if (used.length) components.push(assetComponent(asset, dir, { where: used.map((f) => /\.(ttf|otf|woff2?)$/i.test(f) ? `${pkg.name}/${f}` : `${where} (${pkg.name}/${f})`) }));
182
+ }
183
+ const texts = licenseFiles(dir);
184
+ const license = typeof pkg.license === "string" ? pkg.license : pkg.license?.type ?? null;
185
+ if (!texts.length) problems.push(`${pkg.name}@${pkg.version}: no license file in ${dir} (license ${license ?? "not declared"})`);
186
+ components.push({
187
+ name: pkg.name,
188
+ version: pkg.version ?? null,
189
+ license,
190
+ url: `https://www.npmjs.com/package/${pkg.name}${pkg.version ? `/v/${pkg.version}` : ""}`,
191
+ where: [where],
192
+ texts
193
+ });
194
+ }
195
+ return {
196
+ components: sortComponents(components),
197
+ problems
198
+ };
199
+ }
200
+ const sortComponents = (components) => components.sort((a, b) => a.name.localeCompare(b.name) || String(a.version).localeCompare(String(b.version), void 0, { numeric: true }));
201
+ /** Components of several parts as one list: one entry per name and version, every place it is in. */
202
+ function mergeComponents(...parts) {
203
+ const out = /* @__PURE__ */ new Map();
204
+ for (const c of parts.flat()) {
205
+ const key = `${c.name}\0${c.version ?? ""}`;
206
+ const have = out.get(key);
207
+ if (!have) out.set(key, {
208
+ ...c,
209
+ where: [...c.where]
210
+ });
211
+ else {
212
+ for (const w of c.where) if (!have.where.includes(w)) have.where.push(w);
213
+ if (!have.texts.length) have.texts = c.texts;
214
+ }
215
+ }
216
+ return sortComponents([...out.values()]);
217
+ }
218
+ /** The same components, each said to be in `where` (a runtime's components inside an app output). */
219
+ const placedAt = (components, where) => components.map((c) => ({
220
+ ...c,
221
+ where: [where]
222
+ }));
223
+ const label = (c) => c.version ? `${c.name} ${c.version}` : c.name;
224
+ /** The list, then each component with its license texts. Identical texts are printed once. */
225
+ function renderComponents(components) {
226
+ const rule = "=".repeat(80);
227
+ const out = [];
228
+ for (const c of components) out.push(`- ${label(c)} [${c.license}]: ${c.where.join(", ")}`);
229
+ const seen = /* @__PURE__ */ new Map();
230
+ for (const c of components) {
231
+ out.push("", rule, label(c), `License: ${c.license}`);
232
+ if (c.url) out.push(`Source: ${c.url}`);
233
+ out.push(`In: ${c.where.join(", ")}`);
234
+ for (const t of c.texts) {
235
+ const text = t.text.trim();
236
+ out.push("", `--- ${t.title} ---`);
237
+ if (!text) continue;
238
+ const digest = createHash("sha256").update(text).digest("hex");
239
+ if (seen.has(digest)) out.push(`(The same text as ${seen.get(digest)} above.)`);
240
+ else {
241
+ seen.set(digest, `${t.title} of ${label(c)}`);
242
+ out.push(text);
243
+ }
244
+ }
245
+ }
246
+ return out;
247
+ }
248
+ /** THIRD_PARTY_NOTICES.txt of an app output (`title`: what it is, e.g. "MyApp.app"). */
249
+ function renderOutput({ title, generator, components }) {
250
+ return [
251
+ `THIRD-PARTY NOTICES: ${title}`,
252
+ `Generated by ${generator} from the components in this output. Do not edit.`,
253
+ "",
254
+ "This output contains the components below, each licensed by its authors under its own terms",
255
+ "(reproduced after the list).",
256
+ "",
257
+ ...renderComponents(components)
258
+ ].join("\n") + "\n";
259
+ }
260
+ /** Writes THIRD_PARTY_NOTICES.txt and .json into `dir`; returns their paths. */
261
+ function writeOutputNotices(dir, { title, generator, components }) {
262
+ mkdirSync(dir, { recursive: true });
263
+ const txt = join(dir, NOTICES);
264
+ const json = join(dir, NOTICES_JSON);
265
+ writeFileSync(txt, renderOutput({
266
+ title,
267
+ generator,
268
+ components
269
+ }));
270
+ writeFileSync(json, JSON.stringify({
271
+ format: 1,
272
+ title,
273
+ generator,
274
+ components
275
+ }, null, 1) + "\n");
276
+ return {
277
+ txt,
278
+ json
279
+ };
280
+ }
281
+ /** The components of a THIRD_PARTY_NOTICES.json; throws when it is not one. */
282
+ function readNoticesJson(file) {
283
+ let doc;
284
+ try {
285
+ doc = JSON.parse(readFileSync(file, "utf8"));
286
+ } catch (e) {
287
+ throw new Error(`${file} cannot be read (${e.message})`);
288
+ }
289
+ if (doc?.format !== 1 || !Array.isArray(doc.components)) throw new Error(`${file} is not a THIRD_PARTY_NOTICES.json (format 1)`);
290
+ return doc.components;
291
+ }
292
+ /**
293
+ * bake.config.ts `notices`: the app's own entries, [{ name, version?, license, url?, file }] with
294
+ * `file` a license text relative to the app. Throws one error naming every problem.
295
+ */
296
+ function appEntries(raw, root) {
297
+ if (raw === void 0) return [];
298
+ if (!Array.isArray(raw)) throw new Error("bake.config.ts notices must be a list of { name, license, file, version?, url? }");
299
+ const errors = [];
300
+ const out = [];
301
+ raw.forEach((e, i) => {
302
+ const at = `notices[${i}]${typeof e?.name === "string" ? ` (${e.name})` : ""}`;
303
+ if (!e || typeof e !== "object" || Array.isArray(e)) return errors.push(`${at} must be an object`);
304
+ for (const key of Object.keys(e)) if (![
305
+ "name",
306
+ "version",
307
+ "license",
308
+ "url",
309
+ "file"
310
+ ].includes(key)) errors.push(`${at}: unknown key ${key} (name, version, license, url, file)`);
311
+ for (const key of [
312
+ "name",
313
+ "license",
314
+ "file"
315
+ ]) if (typeof e[key] !== "string" || !e[key].trim()) errors.push(`${at}: ${key} is required`);
316
+ for (const key of ["version", "url"]) if (e[key] !== void 0 && typeof e[key] !== "string") errors.push(`${at}: ${key} must be a string`);
317
+ if (typeof e.file !== "string") return;
318
+ const file = resolve(root, e.file);
319
+ if (!existsSync(file) || !statSync(file).isFile()) return errors.push(`${at}: file ${e.file} not found (a license text, relative to bake.config.ts)`);
320
+ const text = read(file);
321
+ if (!text.trim()) return errors.push(`${at}: ${e.file} is empty`);
322
+ out.push({
323
+ name: e.name,
324
+ version: e.version ?? null,
325
+ license: e.license,
326
+ url: e.url ?? "",
327
+ where: ["the app"],
328
+ texts: [{
329
+ title: e.file,
330
+ text
331
+ }]
332
+ });
333
+ });
334
+ if (errors.length) throw new Error(`bake.config.ts notices:\n ${errors.join("\n ")}`);
335
+ return out;
336
+ }
337
+ // src/tool-run.ts
338
+ /** Default time limit of each external tool `bake` runs, in seconds. Generous: a hit means the tool
339
+ * is stuck, not slow. BAKE_TOOL_TIMEOUT_<NAME> (bake-css-lint -> BAKE_TOOL_TIMEOUT_BAKE_CSS_LINT) sets
340
+ * one tool's limit, BAKE_TOOL_TIMEOUT every tool's; 0 turns the limit off. */
341
+ const TOOL_TIMEOUTS = {
342
+ "bake-css-lint": 300,
343
+ hermesc: 600,
344
+ "bake-frame": 600,
345
+ "bake-snap": 600
346
+ };
347
+ const DEFAULT_TIMEOUT = 300;
348
+ /** Thrown when a tool exits non-zero, is killed, or runs past its limit. `stdout` / `stderr` carry
349
+ * what it wrote (as execFileSync's errors do). */
350
+ var ToolError = class extends Error {
351
+ tool;
352
+ args;
353
+ stdout;
354
+ stderr;
355
+ status;
356
+ timedOut;
357
+ constructor(message, tool, args, stdout, stderr, status, timedOut = false) {
358
+ super(message);
359
+ this.tool = tool;
360
+ this.args = args;
361
+ this.stdout = stdout;
362
+ this.stderr = stderr;
363
+ this.status = status;
364
+ this.timedOut = timedOut;
365
+ this.name = "ToolError";
366
+ }
367
+ };
368
+ /** The time limit of `tool`, in seconds (0: none). */
369
+ function toolTimeout(tool) {
370
+ const key = "BAKE_TOOL_TIMEOUT_" + tool.toUpperCase().replace(/[^A-Z0-9]/g, "_");
371
+ for (const raw of [process.env[key], process.env.BAKE_TOOL_TIMEOUT]) {
372
+ if (raw === void 0 || raw === "") continue;
373
+ const n = Number(raw);
374
+ if (Number.isFinite(n) && n >= 0) return n;
375
+ throw new Error(`${raw === process.env[key] ? key : "BAKE_TOOL_TIMEOUT"}=${raw} is not a number of seconds`);
376
+ }
377
+ return TOOL_TIMEOUTS[tool] ?? DEFAULT_TIMEOUT;
378
+ }
379
+ /** Runs an external tool (bake-css-lint, hermesc, bake-frame, bake-snap) to completion and returns its
380
+ * stdout. Every tool call of `bake` goes through here so that none can hang a build:
381
+ * - stdin is a file (with `input`) or closed, never a pipe whose EOF depends on every copy of its
382
+ * write end being closed;
383
+ * - stdout and stderr are drained by node into buffers of `maxBuffer` (overflow is an error, not
384
+ * a stall);
385
+ * - the tool is killed after its time limit (toolTimeout) with an error naming the tool, its
386
+ * arguments and the elapsed time.
387
+ * The same code runs on macOS, Linux and Windows. */
388
+ function execTool(file, args, opts = {}) {
389
+ return execToolBuffer(file, args, opts).toString("utf8");
390
+ }
391
+ /** execTool, with stdout as bytes (bake snap passes them through). */
392
+ function execToolBuffer(file, args, opts = {}) {
393
+ const tool = basename(file).replace(/\.exe$/i, "").replace(/-\d+-\d+$/, "");
394
+ const limit = opts.timeoutSec ?? toolTimeout(tool);
395
+ let dir = null;
396
+ let fd = null;
397
+ if (opts.input !== void 0) {
398
+ dir = mkdtempSync(join(tmpdir(), "bake-tool-"));
399
+ const path = join(dir, "stdin");
400
+ writeFileSync(path, opts.input);
401
+ fd = openSync(path, "r");
402
+ }
403
+ const t0 = Date.now();
404
+ let r;
405
+ try {
406
+ r = spawnSync(file, [...args], {
407
+ cwd: opts.cwd,
408
+ env: opts.env ?? process.env,
409
+ stdio: [
410
+ fd ?? "ignore",
411
+ opts.stdout ?? "pipe",
412
+ opts.stderr ?? "pipe"
413
+ ],
414
+ maxBuffer: opts.maxBuffer ?? 256 << 20,
415
+ timeout: limit > 0 ? limit * 1e3 : void 0,
416
+ killSignal: "SIGKILL"
417
+ });
418
+ } finally {
419
+ if (fd !== null) closeSync(fd);
420
+ if (dir) rmSync(dir, {
421
+ recursive: true,
422
+ force: true
423
+ });
424
+ }
425
+ const elapsed = ((Date.now() - t0) / 1e3).toFixed(1);
426
+ const out = r.stdout ?? Buffer.alloc(0);
427
+ const stdout = out.toString("utf8");
428
+ const stderr = r.stderr ? r.stderr.toString("utf8") : "";
429
+ const command = [file, ...args].join(" ");
430
+ const fail = (message, timedOut = false) => new ToolError(message, tool, args, stdout, stderr, r.status, timedOut);
431
+ const code = r.error?.code;
432
+ if (code === "ETIMEDOUT") throw fail(`${tool} did not finish within ${limit} s (killed after ${elapsed} s): ${command}\n(raise the limit with BAKE_TOOL_TIMEOUT_${tool.toUpperCase().replace(/[^A-Z0-9]/g, "_")}=<seconds>, 0 = none)` + (stderr ? `\n${stderr}` : ""), true);
433
+ if (code === "ENOBUFS") throw fail(`${tool} wrote more than ${opts.maxBuffer ?? 256 << 20} bytes to stdout or stderr: ${command}`);
434
+ if (r.error) throw fail(`${tool} could not run (${r.error.message}): ${command}`);
435
+ if (r.status !== 0) throw fail(`${tool} ${r.signal ? `was killed by ${r.signal}` : `exited with ${r.status}`} after ${elapsed} s: ${command}` + (stderr ? `\n${stderr}` : ""));
436
+ return out;
437
+ }
438
+ // src/compat.ts
439
+ const COMPAT = readPackageJson("compat.json");
440
+ const executable$1 = (name) => process.platform === "win32" ? name + ".exe" : name;
441
+ const hostKey = () => `${process.platform}-${process.arch}`;
442
+ /** The environment variable that names a tool's binary: BAKE_HERMESC, BAKE_CSS_LINT, BAKE_FRAME, … */
443
+ const toolEnv = (name) => `BAKE_${name.replace(/^bake-/, "").replaceAll("-", "_").toUpperCase()}`;
444
+ /** A host's toolchain package in the table (this host by default), or undefined. */
445
+ const toolchainFor = (table = COMPAT, key = hostKey()) => table.toolchain[key];
446
+ /** The reasons a toolchain does not match the table; [] when it does. */
447
+ function compatIssues(table, facts) {
448
+ const v = table["@bake-native/core"];
449
+ const issues = [];
450
+ const packages = Object.values(table.toolchain).map((t) => t.package);
451
+ if (facts.packageVersion !== void 0 && facts.packageVersion !== v) issues.push(`@bake-native/core ${facts.packageVersion} carries the version table of ${v} (compat.json): the install is mixed. Reinstall @bake-native/core.`);
452
+ if (facts.hermesc) {
453
+ const { path, bytecode, package: pkg } = facts.hermesc;
454
+ const want = table.hermes.bytecode;
455
+ const fix = `Use the hermesc of @bake-native/core ${v} (the optional dependency ${packages.join(" / ")} @${v}), or one built from Hermes ${table.hermes.commit.slice(0, 12)} (pnpm hermes), via --hermesc or BAKE_HERMESC.`;
456
+ if (bytecode === null) issues.push(`hermesc ${path} does not report an HBC bytecode version (hermesc -version): not a Hermes compiler? ${fix}`);
457
+ else if (bytecode !== want) issues.push(`hermesc ${path} emits Hermes bytecode v${bytecode}; runtime ${table.runtime.version} runs only v${want}, so the app would refuse app.hbc. ${fix}`);
458
+ if (pkg && pkg.version !== v) issues.push(`hermesc comes from ${pkg.name} ${pkg.version}, but @bake-native/core is ${v}: the two are released together. Install ${pkg.name}@${v}.`);
459
+ }
460
+ for (const { name, path, version } of facts.tools ?? []) {
461
+ const fix = `Use the ${name} of @bake-native/core ${v} (the optional dependency ${toolchainFor(table)?.package ?? packages.join(" / ")}@${v}) or one built from the same BakeNative release, via ${toolEnv(name)}.`;
462
+ if (!version) {
463
+ issues.push(`${name} ${path} does not report what it was built for (${name} --version): built before the version table, or not ${name}? ${fix}`);
464
+ continue;
465
+ }
466
+ if (version.version !== v) issues.push(`${name} ${path} was built for @bake-native/core ${version.version}, not ${v}: the two are released together. ${fix}`);
467
+ if (version.schemaDigest !== table.schemaDigest) issues.push(`${name} ${path} has host schema ${version.schemaDigest}; @bake-native/core ${v} has ${table.schemaDigest}. ${fix}`);
468
+ if (version.batchDigest !== table.batchDigest) issues.push(`${name} ${path} reads renderer batch schema ${version.batchDigest}; @bake-native/core ${v} writes ${table.batchDigest}. ${fix}`);
469
+ }
470
+ if (facts.hostProtocol !== void 0 && facts.hostProtocol < table.minHostProtocol) issues.push(`the bundle would declare host protocol ${facts.hostProtocol}; rebuild the bundle with \`bake build\` for host protocol ${table.minHostProtocol} or later.`);
471
+ if (facts.hostProtocol !== void 0 && facts.hostProtocol > table.hostProtocol) issues.push(`the bundle would declare host protocol ${facts.hostProtocol}; runtime ${table.runtime.version} understands up to ${table.hostProtocol}.`);
472
+ if (facts.octane !== void 0 && facts.octane !== table.octane) issues.push(`the app has octane ${facts.octane}; @bake-native/core ${v} builds for octane ${table.octane} (its compiler integration and renderer target that version). Install octane@${table.octane}.`);
473
+ return issues;
474
+ }
475
+ /** The directory of this host's installed toolchain package (`<dir>/bin/<tool>`), or null when
476
+ * the table has none for this host or the package manager did not install it. */
477
+ function toolchainDir() {
478
+ const entry = toolchainFor();
479
+ if (!entry) return null;
480
+ try {
481
+ return dirname(fileURLToPath(import.meta.resolve(`${entry.package}/package.json`)));
482
+ } catch {
483
+ return null;
484
+ }
485
+ }
486
+ /** A tool from this host's installed toolchain package, or null. */
487
+ function packagedTool(name) {
488
+ const dir = toolchainDir();
489
+ if (!dir) return null;
490
+ const bin = join(dir, "bin", executable$1(name));
491
+ return existsSync(bin) ? bin : null;
492
+ }
493
+ /** The hermesc of this host's toolchain package, or null. */
494
+ const packagedHermesc = () => packagedTool("hermesc");
495
+ /** Why this host's toolchain package does not supply a tool, and what to do instead. */
496
+ function missingToolReason(name) {
497
+ const v = COMPAT["@bake-native/core"];
498
+ const entry = toolchainFor();
499
+ const instead = `set ${toolEnv(name)} to the path of ${executable$1(name)} built from the same BakeNative release`;
500
+ if (!entry) return `@bake-native/core ${v} has no toolchain package for ${hostKey()} (only ${Object.keys(COMPAT.toolchain).join(", ")}): ${instead}.`;
501
+ if (!entry.tools.includes(name)) {
502
+ const hosts = Object.entries(COMPAT.toolchain).filter(([, t]) => t.tools.includes(name)).map(([key]) => key);
503
+ return `${entry.package} does not include ${name} (it links the Hermes VM, built for ${hosts.join(" and ") || "no host"} only): ` + (name === "bake-frame" ? `use one of those toolchains or ${instead}. For an unbaked native build, disable app-wide Octane Strong mode (compiler.strong in bake.config.ts) and omit --bake.` : `${instead}.`);
504
+ }
505
+ if (!toolchainDir()) return `${entry.package}@${v} is not installed: @bake-native/core brings it as an optional dependency, which --no-optional / --omit=optional or a lockfile made on another platform leaves out. Reinstall @bake-native/core with optional dependencies (npm install --include=optional), or ${instead}.`;
506
+ return `${entry.package} is installed without bin/${executable$1(name)} (a broken install): reinstall @bake-native/core, or ${instead}.`;
507
+ }
508
+ /** A version probe answers at once; 60 s covers a cold disk and a busy machine. */
509
+ const PROBE_TIMEOUT = 60;
510
+ const versionCache = /* @__PURE__ */ new Map();
511
+ /** What a Rust tool says it was built for (`<tool> --version`), null when it does not say. */
512
+ function toolVersion(path, env = process.env) {
513
+ if (!versionCache.has(path)) {
514
+ let parsed = null;
515
+ try {
516
+ const out = execTool(path, ["--version"], {
517
+ env,
518
+ timeoutSec: PROBE_TIMEOUT
519
+ });
520
+ const v = JSON.parse(out.trim().split("\n").pop() ?? "");
521
+ if (v && typeof v.version === "string") parsed = v;
522
+ } catch {}
523
+ versionCache.set(path, parsed);
524
+ }
525
+ return versionCache.get(path);
526
+ }
527
+ const bytecodeCache = /* @__PURE__ */ new Map();
528
+ /** The HBC bytecode version a hermesc emits (`hermesc -version`), null when it does not say. */
529
+ function hermescBytecode(path) {
530
+ if (!bytecodeCache.has(path)) {
531
+ let out = "";
532
+ try {
533
+ out = execTool(path, ["-version"], { timeoutSec: PROBE_TIMEOUT });
534
+ } catch (e) {
535
+ out = String(e.stdout ?? "");
536
+ }
537
+ const m = out.match(/HBC bytecode version:\s*(\d+)/);
538
+ bytecodeCache.set(path, m ? Number(m[1]) : null);
539
+ }
540
+ return bytecodeCache.get(path);
541
+ }
542
+ /** The @bake-native/toolchain-* package a binary lives in (`<pkg>/bin/<tool>`), or null. */
543
+ function hermescPackage(path) {
544
+ const manifest = join(dirname(dirname(path)), "package.json");
545
+ if (!existsSync(manifest)) return null;
546
+ try {
547
+ const { name, version } = JSON.parse(readFileSync(manifest, "utf8"));
548
+ return typeof name === "string" && Object.values(COMPAT.toolchain).some((t) => t.package === name) ? {
549
+ name,
550
+ version
551
+ } : null;
552
+ } catch {
553
+ return null;
554
+ }
555
+ }
556
+ /** Throws one error naming every mismatch between the toolchain and the version table. */
557
+ function assertCompatible(facts) {
558
+ const issues = compatIssues(COMPAT, facts);
559
+ if (issues.length) throw new Error(`toolchain does not match @bake-native/core ${COMPAT["@bake-native/core"]}'s version table (@bake-native/core/compat.json):\n ${issues.join("\n ")}`);
560
+ }
561
+ // src/toolchain.ts
562
+ const repo = resolve(packageRoot$1, "../..");
563
+ const executable = (name) => process.platform === "win32" ? name + ".exe" : name;
564
+ /** The universal renderer every native target compiles against. */
565
+ const NATIVE_RENDERER = {
566
+ module: "bake:renderer",
567
+ target: "universal",
568
+ text: "host",
569
+ capabilities: [
570
+ "scoped-styles",
571
+ "visibility",
572
+ "class-name-alias",
573
+ "signal-bindings"
574
+ ]
575
+ };
576
+ /** hermesc: $BAKE_HERMESC, else this host's @bake-native/toolchain-<platform>-<arch> package (the optional
577
+ * dependency an npm install brings), else bin/hermesc (`pnpm hermes` on macOS) or windows/x64/hermesc.exe
578
+ * (`pnpm hermes` on Windows) under $BAKE_HERMES_ARTIFACTS, then under the monorepo's
579
+ * native/hermes/artifacts (a worktree without its own Hermes build points BAKE_HERMES_ARTIFACTS at
580
+ * another checkout's, as the bake's DLL lookup in bakeEnv does). */
581
+ function defaultHermesc() {
582
+ if (process.env.BAKE_HERMESC) return process.env.BAKE_HERMESC;
583
+ const packaged = packagedHermesc();
584
+ if (packaged) return packaged;
585
+ return [process.env.BAKE_HERMES_ARTIFACTS, join(repo, "native/hermes/artifacts")].filter((dir) => !!dir).flatMap((d) => [join(d, "bin", executable("hermesc")), ...process.platform === "win32" ? [join(d, "windows/x64/hermesc.exe")] : []]).find((p) => existsSync(p)) ?? null;
586
+ }
587
+ const toolBins = /* @__PURE__ */ new Map();
588
+ /** Cargo re-links ("uplifts") a binary into target/<profile>/ on every `cargo build`, even a
589
+ * fresh one, so with several `bake build` processes running at once one can execute a tool while
590
+ * another replaces it (a failed bake-css-lint / ENOENT). Run a copy keyed by size and mtime
591
+ * instead: cargo never touches it, and the copy is made once per distinct binary. */
592
+ function privateToolCopy(bin) {
593
+ for (let attempt = 0;; attempt++) try {
594
+ const st = statSync(bin);
595
+ const ext = bin.endsWith(".exe") ? ".exe" : "";
596
+ const dir = join(dirname(bin), ".bake-tools");
597
+ const copy = join(dir, `${basename(bin, ext)}-${st.size}-${Math.floor(st.mtimeMs)}${ext}`);
598
+ if (!existsSync(copy)) {
599
+ mkdirSync(dir, { recursive: true });
600
+ const tmp = `${copy}.${process.pid}.tmp`;
601
+ copyFileSync(bin, tmp);
602
+ chmodSync(tmp, 493);
603
+ renameSync(tmp, copy);
604
+ }
605
+ return copy;
606
+ } catch (e) {
607
+ if (attempt >= 20) throw e;
608
+ execFileSync(process.execPath, ["-e", "setTimeout(() => {}, 50)"]);
609
+ }
610
+ }
611
+ /** A source checkout: @bake-native/core is packages/core of a repository with the Rust core. */
612
+ const checkout = () => existsSync(join(repo, "native/rust/Cargo.toml"));
613
+ /** A Rust tool `bake` runs (bake-css-lint, bake-frame, bake-snap), resolved in this order:
614
+ * 1. the environment variable naming it (BAKE_CSS_LINT, BAKE_FRAME, BAKE_SNAP)
615
+ * 2. this host's @bake-native/toolchain-<platform>-<arch> package (the optional dependency an npm
616
+ * install brings). In a source checkout the workspace's own packages/toolchain-* directory is
617
+ * release staging, not an install, and is skipped (it would shadow the code being edited).
618
+ * 3. in a source checkout only: `cargo build` of the tool
619
+ * The binary must report the version and schema digests of compat.json (`<tool> --version`). */
620
+ function nativeTool(name) {
621
+ return nativeTools([name])[0];
622
+ }
623
+ /** Several tools at once (`nativeTool` each): the ones a source checkout has to build come from
624
+ * one `cargo build` per feature set (the linter without Hermes, the Hermes tools together), not
625
+ * one per tool. */
626
+ function nativeTools(names) {
627
+ const found = /* @__PURE__ */ new Map();
628
+ const build = [];
629
+ for (const name of names) {
630
+ let bin = toolBins.get(name) ?? (process.env[toolEnv(name)] || void 0);
631
+ if (!bin) {
632
+ const dir = toolchainDir();
633
+ if (!(dir !== null && checkout() && resolve(dir).toLowerCase().startsWith(join(repo, "packages").toLowerCase()))) bin = packagedTool(name) ?? void 0;
634
+ }
635
+ if (bin) found.set(name, bin);
636
+ else build.push(name);
637
+ }
638
+ if (build.length) {
639
+ if (!checkout()) throw new Error(`${build[0]} is not available: ${missingToolReason(build[0])} (Inside an BakeNative source checkout, bake builds it with cargo instead.)`);
640
+ const plain = build.filter((name) => !hermesFeature(name));
641
+ const hermes = build.filter(hermesFeature);
642
+ for (const group of [plain, hermes]) if (group.length) for (const [name, bin] of cargoBuildTools(group)) found.set(name, bin);
643
+ }
644
+ return names.map((name) => {
645
+ const bin = found.get(name);
646
+ if (toolBins.get(name) !== bin) {
647
+ assertCompatible({ tools: [{
648
+ name,
649
+ path: bin,
650
+ version: toolVersion(bin, toolProcessEnv())
651
+ }] });
652
+ toolBins.set(name, bin);
653
+ }
654
+ return bin;
655
+ });
656
+ }
657
+ /** The tools that embed Hermes, built with their `host-hermes` feature (everything but the linter). */
658
+ const hermesFeature = (name) => name !== "bake-css-lint";
659
+ /** `cargo build` of the tools `names` (one feature set) in one run, in the checkout (so its .cargo/config.toml,
660
+ * which keeps each checkout's build files apart under a shared CARGO_TARGET_DIR, applies):
661
+ * name -> a private copy of the binary. */
662
+ function cargoBuildTools(names) {
663
+ const args = [
664
+ "build",
665
+ "--locked",
666
+ "--release",
667
+ "--manifest-path",
668
+ join(repo, "native/rust/Cargo.toml"),
669
+ "--target",
670
+ "host-tuple",
671
+ "--message-format=json-render-diagnostics"
672
+ ];
673
+ for (const name of names) {
674
+ args.push("-p", name, "--bin", name);
675
+ if (hermesFeature(name)) args.push("--features", `${name}/host-hermes`);
676
+ }
677
+ let output;
678
+ try {
679
+ output = execFileSync("cargo", args, {
680
+ encoding: "utf8",
681
+ maxBuffer: 16 << 20,
682
+ cwd: repo
683
+ });
684
+ } catch (e) {
685
+ if (e.code === "ENOENT") throw new Error(`${names.join(", ")}: cargo is not on PATH, and a source checkout builds these tools with it. Put the Rust toolchain on PATH (rustup), or name a built binary with ${names.map(toolEnv).join(" / ")}.`);
686
+ throw e;
687
+ }
688
+ const messages = output.split("\n").filter(Boolean).map((line) => JSON.parse(line));
689
+ const bins = /* @__PURE__ */ new Map();
690
+ for (const name of names) {
691
+ const artifact = messages.find((m) => m.reason === "compiler-artifact" && m.target.name === name && m.executable);
692
+ if (!artifact) throw new Error(`cargo did not produce ${executable(name)}`);
693
+ bins.set(name, privateToolCopy(artifact.executable));
694
+ }
695
+ return bins;
696
+ }
697
+ /** The environment to run a native tool in. On Windows bake-frame links hermesvm.dll (import
698
+ * library): the toolchain package ships it next to bake-frame.exe; a cargo-built or BAKE_FRAME
699
+ * bake-frame finds it through the Hermes artifacts (BAKE_HERMES_ARTIFACTS, else a source checkout's
700
+ * native/hermes/artifacts) put first on PATH here. */
701
+ function toolProcessEnv() {
702
+ if (process.platform !== "win32") return process.env;
703
+ const artifacts = process.env.BAKE_HERMES_ARTIFACTS ?? (checkout() ? join(repo, "native/hermes/artifacts") : null);
704
+ if (!artifacts) return process.env;
705
+ const dir = join(artifacts, "windows/x64");
706
+ const key = Object.keys(process.env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
707
+ return {
708
+ ...process.env,
709
+ [key]: `${dir};${process.env[key] ?? ""}`
710
+ };
711
+ }
712
+ // src/native-impl-check.mjs
713
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
714
+ /** Source text without comments and string literals (so a commented-out member does not count). */
715
+ function stripComments(text) {
716
+ return text.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/[^\n]*/g, "").replace(/"(?:[^"\\\n]|\\.)*"/g, "\"\"");
717
+ }
718
+ /**
719
+ * The declaration headers that `start` matches in `code`: from each match to the `{` that opens the
720
+ * body at bracket depth 0 (a Kotlin constructor's default lambda `{ ... }` is inside parentheses).
721
+ */
722
+ function headers(code, start) {
723
+ const out = [];
724
+ const re = new RegExp(start.source, "g");
725
+ for (let m; m = re.exec(code);) {
726
+ let depth = 0;
727
+ let i = m.index;
728
+ for (; i < code.length; i++) {
729
+ const c = code[i];
730
+ if (c === "(" || c === "[" || c === "<") depth++;
731
+ else if (c === ")" || c === "]" || c === ">" && code[i - 1] !== "-") depth = Math.max(0, depth - 1);
732
+ else if (c === "{" && depth === 0) break;
733
+ }
734
+ out.push(code.slice(m.index, i));
735
+ }
736
+ return out;
737
+ }
738
+ /** Some declaration matching `start` has `adopts` in its header. */
739
+ const declares = (start, adopts) => ({ test: (code) => headers(code, start).some((h) => adopts.test(h)) });
740
+ const LANGS = {
741
+ swift: {
742
+ conforms: (name) => declares(/\b(?:class|struct|actor|extension)\s+[\w.]+/, new RegExp(`:[^]*\\b${esc(name)}Spec\\b`)),
743
+ declares: (m) => m.kind === "constant" ? new RegExp(`\\b(?:var|let)\\s+\`?${esc(m.name)}\`?\\b`) : new RegExp(`\\bfunc\\s+\`?${esc(m.name)}\`?\\s*\\(`),
744
+ contract: (spec) => swiftSpec(spec, { imports: [] }),
745
+ line: (m) => m.kind === "constant" ? new RegExp(`^\\s*var \`?${esc(m.name)}\`?:`) : new RegExp(`^\\s*func \`?${esc(m.name)}\`?\\(`),
746
+ expected: (name) => `a class, struct or actor that conforms to ${name}Spec (public final class ${name}Module: ${name}Spec)`
747
+ },
748
+ kotlin: {
749
+ conforms: (name) => declares(new RegExp(`\\bclass\\s+${esc(name)}Module\\b`), new RegExp(`\\)?\\s*:[^]*\\b${esc(name)}Spec\\s*\\(`)),
750
+ declares: (m) => m.kind === "constant" ? new RegExp(`\\b(?:val|var)\\s+\`?${esc(m.name)}\`?\\b`) : new RegExp(`\\bfun\\s+\`?${esc(m.name)}\`?\\s*\\(`),
751
+ contract: (spec) => kotlinSpec(spec, "dev.bakenative.generated"),
752
+ line: (m) => m.kind === "constant" ? new RegExp(`^\\s*abstract val \`?${esc(m.name)}\`?:`) : new RegExp(`^\\s*abstract (?:suspend )?fun \`?${esc(m.name)}\`?\\(`),
753
+ expected: (name) => `class ${name}Module(...) : ${name}Spec()`
754
+ },
755
+ rust: {
756
+ conforms: (name) => declares(/\bimpl\b/, new RegExp(`\\b${esc(name)}Spec\\s+for\\b`)),
757
+ declares: (m) => new RegExp(`\\bfn\\s+(?:r#)?${esc(snake(m.name))}\\s*\\(`),
758
+ contract: (spec) => rustSpec(spec),
759
+ line: (m) => new RegExp(`^\\s*fn (?:r#)?${esc(snake(m.name))}\\(`),
760
+ expected: (name) => `impl ${name}Spec for YourType`
761
+ }
762
+ };
763
+ const TARGET_LANG = {
764
+ ios: "swift",
765
+ mac: "swift",
766
+ android: "kotlin",
767
+ windows: "rust"
768
+ };
769
+ /**
770
+ * What `files` ([{ path, text }]: one target's implementation files) lack against `spec` (the
771
+ * parsed spec): [{ file, line, message }], empty when they match. `target`: ios | mac | android |
772
+ * windows.
773
+ */
774
+ function implementationIssues(spec, files, target) {
775
+ const lang = TARGET_LANG[target];
776
+ if (!lang || !files.length) return [];
777
+ const L = LANGS[lang];
778
+ const texts = files.map((f) => ({
779
+ path: f.path,
780
+ code: stripComments(f.text)
781
+ }));
782
+ const issues = [];
783
+ const conformsRe = L.conforms(spec.name);
784
+ if (!texts.some((t) => conformsRe.test(t.code))) {
785
+ issues.push({
786
+ file: files[0].path,
787
+ line: 1,
788
+ message: `no ${target} implementation file declares ${L.expected(spec.name)}`
789
+ });
790
+ return issues;
791
+ }
792
+ let contract = null;
793
+ for (const m of spec.members) {
794
+ const re = L.declares(m);
795
+ if (texts.some((t) => re.test(t.code))) continue;
796
+ contract ??= L.contract(spec).split("\n");
797
+ const want = contract.find((l) => L.line(m).test(l))?.trim();
798
+ issues.push({
799
+ file: files[0].path,
800
+ line: 1,
801
+ message: `${spec.name}.${m.name} (${m.kind}) is not implemented${want ? `: the contract declares \`${want}\`` : ""}`
802
+ });
803
+ }
804
+ return issues;
805
+ }
806
+ /** The host family of each native target (one build unit per family). */
807
+ const FAMILY = {
808
+ ios: "apple",
809
+ mac: "apple",
810
+ android: "android",
811
+ windows: "windows"
812
+ };
813
+ /** The first-party modules: { name, spec, targets, build } by module name. */
814
+ const FIRST_PARTY = Object.fromEntries(Object.entries(SYSTEM_MODULES).map(([spec, m]) => [m.native, {
815
+ name: m.native,
816
+ spec,
817
+ targets: m.targets ?? [],
818
+ build: m.build ?? {}
819
+ }]));
820
+ /**
821
+ * The build units of `names` on `target`, sorted by module name. Throws (naming each) for a name
822
+ * that is not a first-party module or that has no build unit on the target.
823
+ */
824
+ function moduleUnits(target, names) {
825
+ const family = FAMILY[target];
826
+ if (!family) throw new Error(`no first-party module registration for target ${target} (${Object.keys(FAMILY).join(", ")})`);
827
+ const sorted = [...new Set(names)].sort();
828
+ const problems = [];
829
+ const units = [];
830
+ for (const name of sorted) {
831
+ const m = FIRST_PARTY[name];
832
+ if (!m) {
833
+ problems.push(`${name} is not a first-party module (${Object.keys(FIRST_PARTY).join(", ")})`);
834
+ continue;
835
+ }
836
+ const unit = m.build[family];
837
+ if (!unit || !m.targets.includes(target)) {
838
+ problems.push(`${name}: the ${target} host does not implement it`);
839
+ continue;
840
+ }
841
+ units.push({
842
+ name,
843
+ unit
844
+ });
845
+ }
846
+ if (problems.length) throw new Error(`first-party modules for ${target}: ${problems.join("; ")}`);
847
+ return units;
848
+ }
849
+ const list = (units) => units.map((u) => u.name).join(", ") || "none";
850
+ const header = (c, target, units) => `${c} Generated by \`bake native link\` from the first-party modules the app's ${target} bundles use\n${c} (manifest.json requires.modules): ${list(units)}. Do not edit; rebuild the app instead.\n`;
851
+ /**
852
+ * The registration files for `names` on `target`: [{ path, text }], paths relative to the output
853
+ * directory. `bakenative`: the BakeNative checkout (its Package.swift) relative to the output directory,
854
+ * with forward slashes (apple and windows reference it by path).
855
+ */
856
+ /**
857
+ * `app`: the app's own modules the bundles use that have source in native/<name> (from `bake add`
858
+ * or written by the app; src/registry.mjs appModules): [{ name, module, locked, files: [{ path,
859
+ * text }] }]. Their sources for this target are copied into the registration on every build; a
860
+ * locked (registry) module is created by the generated code, a first-party name the app has its
861
+ * own module for is the app's. `appModules`: the app modules the bundles call (requires.native-
862
+ * Modules / optionalNativeModules); with `specs` (module name -> parsed spec, every native/<name>)
863
+ * they give the generated contracts and BakeNativeBundleModules.root(...)
864
+ * (docs/design/native-module-specs.md).
865
+ * `prebuilt` (ios, mac): `bakenative` is the prebuilt runtime an npm install brings
866
+ * (src/apple-runtime.ts), a Swift package with the host products only (BakeNativeKit, BakeNativeAppKit).
867
+ * A bundle that needs more of the BakeNative package (a first-party module the app has no copy of,
868
+ * a native view) is refused with what to do.
869
+ * `out`: the directory the files go to; the native dependencies' local paths (binary targets,
870
+ * jniLibs, source folders, path crates) are written relative to it.
871
+ * @param {string} target @param {string[]} names @param {{ bakenative?: string, prebuilt?: boolean, views?: { name: string, unit: any, signature?: string }[], minSdk?: number, app?: { name: string, module: string, locked?: boolean, files: { path: string, text: string }[], deps?: any }[], appModules?: { required: string[], optional: string[] }, specs?: Map<string, any>, out?: string }} [opts]
872
+ */
873
+ function registrationFiles(target, names, { bakenative, prebuilt = false, views = [], minSdk = 29, app = [], appModules, specs = /* @__PURE__ */ new Map(), out } = {}) {
874
+ const own = new Set(app.map((m) => m.module));
875
+ const units = moduleUnits(target, names.filter((n) => !own.has(n)));
876
+ const mods = appUnits(target, app);
877
+ const family = FAMILY[target];
878
+ if (family !== "android" && !bakenative) throw new Error(`registration for ${target} needs the BakeNative checkout path (bakenative)`);
879
+ const v = [...new Map(views.map((x) => [x.name, x])).values()].sort((a, b) => a.name < b.name ? -1 : 1);
880
+ if (family === "apple" && prebuilt) {
881
+ const problems = [];
882
+ if (units.length) problems.push(`the bundle uses ${list(units)} without a copy in the app: add ${units.length === 1 ? "it" : "them"} with \`bake add ${units.map((u) => u.name.toLowerCase()).join(" ")}\``);
883
+ if (v.length) problems.push(`the bundle renders the native view${v.length === 1 ? "" : "s"} ${v.map((x) => x.name).join(", ")}, whose glue compiles against the core's headers`);
884
+ if (problems.length) throw new Error(`the prebuilt Apple runtime has the ${target} host only (${target === "ios" ? "BakeNativeKit" : "BakeNativeAppKit"}): ${problems.join("; ")}. Or build against an BakeNative source checkout: bake native link --target ${target} --bakenative <checkout>`);
885
+ }
886
+ const called = calledSpecs(specs, appModules);
887
+ const auto = mods.filter((m) => m.locked);
888
+ const params = [...new Map([...called, ...mods.filter((m) => !m.locked && !called.some((c) => c.spec.name === m.module)).map((m) => ({
889
+ spec: specs.get(m.module),
890
+ optional: true
891
+ }))].filter((c) => c.spec && !auto.some((a) => a.module === c.spec.name)).map((c) => [c.spec.name, c])).values()].sort((a, b) => a.spec.name < b.spec.name ? -1 : 1);
892
+ const contracts = [...new Map([...auto.map((m) => specs.get(m.module)), ...params.map((c) => c.spec)].filter(Boolean).map((s) => [s.name, s])).values()];
893
+ const ownFiles = appModuleFiles(family, target, params, contracts);
894
+ const deps = targetNativeDeps(target, mods, v);
895
+ const where = (abs) => {
896
+ if (!out) throw new Error(`registration for ${target}: native dependencies with local paths need the output directory (out)`);
897
+ return unitPath(out, abs);
898
+ };
899
+ if (family === "apple") return [...appleFiles(target, units, bakenative, v, mods, auto, deps, where), ...ownFiles];
900
+ if (family === "android") return [...androidFiles(target, units, v, minSdk, mods, auto, deps, where), ...ownFiles];
901
+ return [...windowsFiles(target, units, bakenative, v, mods, auto, contracts, deps, where), ...ownFiles];
902
+ }
903
+ /**
904
+ * The native dependencies (src/native-deps.mjs) of the app modules with an implementation on
905
+ * `target` and of the app views linked there, merged for its host family: { modules, all,
906
+ * libraries }. `modules`: the modules' only (the BakeNativeAppModules target); `all`: with the
907
+ * views' (a package declares each once); `libraries`: the third-party ones, for the notices.
908
+ * Two that declare one library differently throw a NativeDepsError.
909
+ * @returns {{ modules: any, all: any, libraries: any[] }}
910
+ */
911
+ function targetNativeDeps(target, app, views = []) {
912
+ const family = FAMILY[target];
913
+ const modDeps = app.filter((m) => m.deps && targetFiles(m.files, target).length).map((m) => m.deps);
914
+ const viewDeps = family === "windows" ? [] : views.filter((v) => v.unit?.app && v.unit.deps).map((v) => v.unit.deps);
915
+ const all = mergeNativeDeps([...modDeps, ...viewDeps], family);
916
+ return {
917
+ modules: { [family]: mergeNativeDeps(modDeps, family) },
918
+ all: { [family]: all },
919
+ libraries: nativeDepLibraries(all, family)
920
+ };
921
+ }
922
+ /** The implementation files of `file` names on `target` (not tests). */
923
+ const LANG = {
924
+ ios: (p) => /\.swift$/.test(p) && !/\.mac\.swift$/.test(p),
925
+ mac: (p) => /\.swift$/.test(p) && !/\.ios\.swift$/.test(p),
926
+ android: (p) => /\.kt$/.test(p),
927
+ windows: (p) => /\.rs$/.test(p)
928
+ };
929
+ const TEST = /(Tests?\.swift|Test\.kt|_test\.rs)$/;
930
+ /**
931
+ * The build unit of a view the app declares itself (`native/views/<Name>.native.ts`, its
932
+ * implementation at package.json "bakenative".views.<Name>.<family>), for `target`: on Apple the
933
+ * generated registration compiles it as three targets of its own package (the JSI glue, the
934
+ * generated base, the app's implementation). Android copies commandless Kotlin views and their
935
+ * contracts into its registration module. Windows registers built-in views only.
936
+ */
937
+ function appViewUnit(root, entry, target) {
938
+ const family = FAMILY[target];
939
+ const build = entry.build?.[family];
940
+ if (entry.source !== "app" || !build || family !== "apple" && family !== "android") return build;
941
+ const spec = readViewSpec(readFileSync(join(root, entry.file), "utf8"), entry.file);
942
+ if (family === "android" && spec.commands.length) throw new Error(`${entry.file}: app-declared Android native views cannot declare commands. Use props and events for Android, or branch on import.meta.env.BAKE_TARGET.`);
943
+ const dir = join(root, build.path);
944
+ if (!existsSync(dir)) throw new Error(`${entry.file}: package.json "bakenative".views.${spec.name}.${family} is ${build.path}, which does not exist`);
945
+ const walk = (d) => readdirSync(d).sort().flatMap((e) => statSync(join(d, e)).isDirectory() ? walk(join(d, e)) : [relative(dir, join(d, e)).split("\\").join("/")]);
946
+ const files = targetFiles(walk(dir).map((path) => ({ path })), target).map((f) => ({
947
+ path: f.path,
948
+ text: readFileSync(join(dir, f.path), "utf8")
949
+ }));
950
+ const decl = new RegExp(`\\bclass\\s+(\\w+)\\s*:\\s*[^{]*\\b${spec.name}ViewSpec\\b`);
951
+ const file = files.find((f) => decl.test(stripComments(f.text)));
952
+ const cls = file && decl.exec(stripComments(file.text))[1];
953
+ const language = family === "android" ? "Kotlin" : "Swift";
954
+ const deps = readNativeDeps(root, join(root, entry.file), { family });
955
+ if (!cls) throw new Error(`${build.path}: no ${target} ${language} file declares a class that subclasses ${spec.name}ViewSpec`);
956
+ if (family === "android") {
957
+ const pkg = /^\s*package\s+([\w.]+)/m.exec(file.text)?.[1];
958
+ const base = viewFiles(spec, { source: basename(entry.file) }).find((f) => f.path === `${spec.name}ViewSpec.kt`);
959
+ return {
960
+ app: true,
961
+ class: pkg ? `${pkg}.${cls}` : cls,
962
+ files: [base, ...files],
963
+ deps
964
+ };
965
+ }
966
+ return {
967
+ app: true,
968
+ product: `BakeNativeAppView${spec.name}`,
969
+ specModule: `BakeNativeAppView${spec.name}Spec`,
970
+ class: cls,
971
+ spec,
972
+ files,
973
+ deps
974
+ };
975
+ }
976
+ /** A module's implementation files on `target` (paths relative to its folder; no tests). */
977
+ function targetFiles(files, target) {
978
+ const pick = LANG[target];
979
+ return pick ? files.filter((f) => pick(f.path) && !TEST.test(f.path) && !f.path.split("/").includes("tests")) : [];
980
+ }
981
+ /**
982
+ * The app modules on `target`: [{ name, module, files, class?, rust? }] sorted by module name,
983
+ * with only this target's implementation files. Throws for a module without any, and (Android)
984
+ * for a Kotlin module class it cannot find, (Windows) for more than one Rust file.
985
+ */
986
+ function appUnits(target, app) {
987
+ LANG[target];
988
+ const out = [];
989
+ for (const m of [...app].sort((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0)) {
990
+ const files = targetFiles(m.files, target);
991
+ if (!files.length && m.locked) throw new Error(`native/${m.name}: ${m.module} has no ${target} implementation`);
992
+ if (!files.length) continue;
993
+ const unit = {
994
+ name: m.name,
995
+ module: m.module,
996
+ locked: !!m.locked,
997
+ files,
998
+ deps: m.deps ?? null
999
+ };
1000
+ if (target === "android") {
1001
+ const decl = new RegExp(`\\bclass\\s+${m.module}Module\\b`);
1002
+ const file = files.find((f) => decl.test(f.text));
1003
+ if (!file) throw new Error(`native/${m.name}: no Kotlin file declares class ${m.module}Module`);
1004
+ const pkg = /^\s*package\s+([\w.]+)/m.exec(file.text)?.[1];
1005
+ unit.class = pkg ? `${pkg}.${m.module}Module` : `${m.module}Module`;
1006
+ unit.context = new RegExp(`\\bclass\\s+${m.module}Module\\s*\\([^)]*\\bContext\\b`).test(file.text);
1007
+ }
1008
+ if (target === "windows") {
1009
+ if (files.length !== 1) throw new Error(`native/${m.name}: one Rust file per module (has ${files.map((f) => f.path).join(", ")})`);
1010
+ unit.rust = `app_${m.name.replaceAll("-", "_")}`;
1011
+ }
1012
+ out.push(unit);
1013
+ }
1014
+ return out;
1015
+ }
1016
+ /** The app modules' files under `dir` of the registration: <dir>/<name>/<path>. */
1017
+ function appSources(mods, dir) {
1018
+ return mods.flatMap((m) => m.files.map((f) => ({
1019
+ path: `${dir}/${m.name}/${f.path}`,
1020
+ text: f.text.replace(/\r\n/g, "\n")
1021
+ })));
1022
+ }
1023
+ const q = (v) => JSON.stringify(v);
1024
+ /** One Apple target's native dependencies (merged, src/native-deps.mjs): its dependency entries
1025
+ * (package products, binary targets) and its linker settings (system frameworks). */
1026
+ function appleTargetDeps(d) {
1027
+ if (!d) return {
1028
+ entries: [],
1029
+ settings: ""
1030
+ };
1031
+ return {
1032
+ entries: [...d.apple.packages.flatMap((p) => p.products.map((pr) => `.product(name: ${q(pr)}, package: ${q(p.identity)})`)), ...d.apple.binaryTargets.map((b) => q(b.name))],
1033
+ settings: d.apple.frameworks.length ? `, linkerSettings: [${d.apple.frameworks.map((f) => `.linkedFramework(${q(f)})`).join(", ")}]` : ""
1034
+ };
1035
+ }
1036
+ function appleFiles(target, units, bakenative, views, mods, auto = [], deps = null, where = null) {
1037
+ const host = target === "ios" ? "BakeNativeKit" : "BakeNativeAppKit";
1038
+ const own = views.filter((v) => v.unit.app);
1039
+ const products = [
1040
+ host,
1041
+ ...units.map((u) => u.unit.product),
1042
+ ...views.filter((v) => !v.unit.app).map((v) => v.unit.product),
1043
+ ...own.length ? ["BakeNativeNativeViews"] : []
1044
+ ];
1045
+ const all = deps?.all.apple ?? {
1046
+ packages: [],
1047
+ binaryTargets: []
1048
+ };
1049
+ const mine = appleTargetDeps(deps?.modules);
1050
+ const packages = all.packages.map((p) => `,\n .package(url: ${q(p.url)}, ${p.exact ? `exact: ${q(p.exact)}` : `from: ${q(p.from)}`})`).join("");
1051
+ const binaries = all.binaryTargets.map((b) => b.path ? `\n .binaryTarget(name: ${q(b.name)}, path: ${q(where(b.path))}),` : `\n .binaryTarget(name: ${q(b.name)}, url: ${q(b.url)}, checksum: ${q(b.checksum)}),`).join("");
1052
+ const pkg = `// swift-tools-version: 6.0
1053
+ ${header("//", target, units)}// The app target depends on the product BakeNativeAppModules and registers BakeNativeBundleModules.entries
1054
+ // in its app-layer module registry. A module the bundles do not use is not linked.
1055
+ import PackageDescription
1056
+ ${own.length ? `import Foundation\n\nlet bakeNativePath = ${JSON.stringify(bakenative)}\n${appViewIncludes}` : ""}
1057
+ let package = Package(
1058
+ name: "BakeNativeAppModules",
1059
+ platforms: [.macOS("14.0"), .iOS("16.0")],
1060
+ products: [.library(name: "BakeNativeAppModules", targets: ["BakeNativeAppModules"])],
1061
+ dependencies: [.package(name: "BakeNative", path: ${JSON.stringify(bakenative)})${packages}],
1062
+ targets: [
1063
+ .target(name: "BakeNativeAppModules", dependencies: [
1064
+ ${products.map((p) => ` .product(name: "${p}", package: "BakeNative"),`).join("\n")}${own.map((v) => `\n "${v.unit.product}",`).join("")}${mine.entries.map((e) => `\n ${e},`).join("")}
1065
+ ]${mine.settings}),${own.map((v) => appViewTargets(v.unit)).join("")}${binaries}
1066
+ ]${own.length ? ",\n cxxLanguageStandard: .cxx17" : ""}
1067
+ )
1068
+ `;
1069
+ const swift = `${header("//", target, units)}${swiftBakeNativeImports([host])}
1070
+ ${[...units, ...views].map((u) => `import ${u.unit.product}`).join("\n")}${units.length + views.length ? "\n" : ""}
1071
+ /// The first-party modules this app's bundles use, one entry each (a fresh instance per root).
1072
+ public enum BakeNativeAppModules: BakeNativeModuleProvider {
1073
+ public static let names: [String] = [${[...units.map((u) => u.name), ...auto.map((m) => m.module)].map((n) => JSON.stringify(n)).join(", ")}]
1074
+ public static var entries: [BakeNativeModuleEntry] { [${[...units.map((u) => `.module { ${u.unit.class}() }`), ...auto.map((m) => `.module { ${m.module}Module() }`)].join(", ")}] }
1075
+ }
1076
+
1077
+ /// The registry a screen takes: \`BakeNativeView(..., modules: BakeNativeBundleModules.root())\` (a static
1078
+ /// link, no lookup by name; a fresh instance of each module per root). An app with its own modules
1079
+ /// compiles the generated BakeNativeBundleModules.swift next to this package into its target, whose
1080
+ /// \`root(...)\` takes them.
1081
+ public enum BakeNativeBundleModules {
1082
+ public static var entries: [BakeNativeModuleEntry] { BakeNativeAppModules.entries }
1083
+
1084
+ public static func root() -> BakeNativeModuleRegistry { BakeNativeModuleRegistry(entries: entries) }
1085
+ }
1086
+ ${appleViews(views)}`;
1087
+ return [
1088
+ {
1089
+ path: "Package.swift",
1090
+ text: pkg
1091
+ },
1092
+ {
1093
+ path: "Sources/BakeNativeAppModules/BakeNativeAppModules.swift",
1094
+ text: swift
1095
+ },
1096
+ ...own.flatMap((v) => appViewSources(v.unit)),
1097
+ ...appSources(mods, "Sources/BakeNativeAppModules/App")
1098
+ ];
1099
+ }
1100
+ /** Header search paths of the app views' JSI glue: JSI (Hermes headers), BakeNativeViews.h and the
1101
+ * C ABI, in the BakeNative checkout the package depends on. */
1102
+ const appViewIncludes = `
1103
+ /// The BakeNative checkout (the dependency's path) and the headers the views' JSI glue includes.
1104
+ let bakeNativeDir = URL(fileURLWithPath: bakeNativePath, relativeTo: URL(fileURLWithPath: Context.packageDirectory + "/")).standardizedFileURL.path
1105
+ let viewHeaders: [String] = ["native/hermes/artifacts/include", "native/hermes/BakeNativeJSI/include", "native/rust/apple/Sources/CBakeNativeRust/include"]
1106
+ .flatMap { ["-I", bakeNativeDir + "/" + $0] }
1107
+ `;
1108
+ /** One app view as three targets: `<Name>ViewJSI` (C++, the module the interop imports), the
1109
+ * generated base `BakeNativeAppView<Name>Spec` (Swift with C++ interop) and the app's
1110
+ * implementation `BakeNativeAppView<Name>`. */
1111
+ function appViewTargets(u) {
1112
+ const n = u.spec.name;
1113
+ const at = `Sources/AppViews/${n}`;
1114
+ const d = appleTargetDeps(u.deps);
1115
+ return `
1116
+ .target(name: "${n}ViewJSI", path: "${at}/JSI", cxxSettings: [.unsafeFlags(viewHeaders)]),
1117
+ .target(name: "${u.specModule}", dependencies: [.product(name: "BakeNativeNativeViews", package: "BakeNative"), "${n}ViewJSI"], path: "${at}/Spec",
1118
+ swiftSettings: [.interoperabilityMode(.Cxx), .unsafeFlags(["-Xfrontend", "-disable-cxx-interop-requirement-at-import"])]),
1119
+ .target(name: "${u.product}", dependencies: [.product(name: "BakeNativeNativeViews", package: "BakeNative"), "${u.specModule}"${d.entries.map((e) => `, ${e}`).join("")}], path: "${at}/View"${d.settings}),`;
1120
+ }
1121
+ /** An app view's files in the package: the generated Apple glue and the implementation. */
1122
+ function appViewSources(u) {
1123
+ const n = u.spec.name;
1124
+ const at = `Sources/AppViews/${n}`;
1125
+ const gen = viewFiles(u.spec);
1126
+ const pick = (p) => gen.find((f) => f.path === p)?.text ?? "";
1127
+ return [
1128
+ {
1129
+ path: `Sources/AppViews/${n}ViewJSI.h`,
1130
+ text: pick(`${n}ViewJSI.h`)
1131
+ },
1132
+ {
1133
+ path: `${at}/JSI/${n}ViewJSIApple.cpp`,
1134
+ text: pick(`apple/${n}ViewJSI/${n}ViewJSIApple.cpp`)
1135
+ },
1136
+ {
1137
+ path: `${at}/JSI/include/${n}ViewJSIApple.h`,
1138
+ text: pick(`apple/${n}ViewJSI/include/${n}ViewJSIApple.h`)
1139
+ },
1140
+ {
1141
+ path: `${at}/Spec/${n}ViewSpec.swift`,
1142
+ text: pick(`apple/${n}ViewSpec/${n}ViewSpec.swift`)
1143
+ },
1144
+ {
1145
+ path: `${at}/Spec/${n}ViewInterop.swift`,
1146
+ text: pick(`apple/${n}ViewSpec/${n}ViewInterop.swift`)
1147
+ },
1148
+ ...u.files.map((f) => ({
1149
+ path: `${at}/View/${f.path}`,
1150
+ text: f.text.replace(/\r\n/g, "\n")
1151
+ }))
1152
+ ];
1153
+ }
1154
+ /** The views half (plain Swift, no Objective-C): the host view calls `BakeNativeAppViews.views()`
1155
+ * through the static link, never by name (docs/design/native-views.md, "Registration"). */
1156
+ function appleViews(views) {
1157
+ return `
1158
+ /// The native views this app's bundles use (manifest.json requires.views): the host registers
1159
+ /// each type directly; a view the bundles do not use is not linked.
1160
+ public enum BakeNativeAppViews {
1161
+ public static let names: [String] = [${views.map((v) => JSON.stringify(v.name)).join(", ")}]
1162
+ public static func views() -> [any BakeNativeNativeViewType.Type] { [${views.map((v) => `${v.unit.class}.self`).join(", ")}] }
1163
+ }
1164
+ `;
1165
+ }
1166
+ /** `minSdk`: bake.config.ts android.minSdk. The module declares it (a host app below it fails the
1167
+ * manifest merge instead of running effects its API level cannot draw) and `min-sdk` holds it
1168
+ * for the app's Gradle build (`minSdk` of the app template). */
1169
+ function androidFiles(target, units, views, minSdk, mods, auto = [], deps = null, where = null) {
1170
+ const native = views.filter((v) => v.unit.bridge);
1171
+ const own = views.filter((v) => v.unit.app).map(({ name, unit }) => ({
1172
+ name,
1173
+ files: unit.files
1174
+ }));
1175
+ const projects = [...units, ...views.filter((v) => !v.unit.app)];
1176
+ const includes = native.map((v) => `rootProject.project(${JSON.stringify(v.unit.project)}).projectDir.resolve(${JSON.stringify(v.unit.jsi)})`).join(", ");
1177
+ const nd = deps?.all.android ?? {
1178
+ maven: [],
1179
+ jniLibs: [],
1180
+ sources: []
1181
+ };
1182
+ const libraries = nd.maven.map((m) => ` implementation(${q(m.coordinate)})`);
1183
+ const sourceDirs = [...nd.sources.map((d) => ` getByName("main").kotlin.srcDir(${q(where(d))})`), ...nd.jniLibs.map((j) => ` getByName("main").jniLibs.srcDir(${q(where(j.path))})`)];
1184
+ const sourceSets = sourceDirs.length ? `\n sourceSets {\n${sourceDirs.join("\n")}\n }` : "";
1185
+ const defaults = native.length ? `
1186
+ defaultConfig {
1187
+ minSdk = ${minSdk}
1188
+ ndk {
1189
+ abiFilters += providers.gradleProperty("bakenative.abis").orElse("arm64-v8a").get()
1190
+ .split(',').map { it.trim() }.filter { it.isNotEmpty() }
1191
+ }
1192
+ externalNativeBuild {
1193
+ cmake {
1194
+ // kolibri's Prefab package and Hermes need the shared C++ runtime.
1195
+ arguments += listOf(
1196
+ "-DANDROID_STL=c++_shared",
1197
+ "-DBAKENATIVE_ANDROID=" + rootProject.project(":bakenative").projectDir.invariantSeparatorsPath,
1198
+ "-DBAKE_VIEW_INCLUDES=" + listOf(${includes}).joinToString(";") { it.invariantSeparatorsPath },
1199
+ )
1200
+ }
1201
+ }
1202
+ }
1203
+ externalNativeBuild {
1204
+ cmake {
1205
+ path = file("src/main/cpp/CMakeLists.txt")
1206
+ version = "3.22.1"
1207
+ }
1208
+ }` : `
1209
+ defaultConfig { minSdk = ${minSdk} }`;
1210
+ const gradle = `${header("//", target, units)}// A library module of the host app's build: include it (settings.gradle.kts) with the module
1211
+ // projects it names and depend on it from the app. BakeNativeView registers what BakeNativeAppModules
1212
+ // returns with the core built-ins. A module the bundles do not use is not in the APK.
1213
+ plugins {
1214
+ alias(libs.plugins.android.library)
1215
+ ${native.length ? " alias(libs.plugins.kolibri)\n" : ""}}
1216
+
1217
+ android {
1218
+ namespace = "dev.bakenative.generated"
1219
+ compileSdk = 37${defaults}${sourceSets}
1220
+ }
1221
+
1222
+ dependencies {
1223
+ implementation(project(":modules"))
1224
+ // BakeNativeAppViews returns dev.bakenative.views types (the host library).
1225
+ implementation(project(":bakenative"))
1226
+ ${projects.map((u) => ` implementation(project(${JSON.stringify(u.unit.project)}))`).join("\n")}${projects.length ? "\n" : ""}${libraries.map((l) => `${l}\n`).join("")}}
1227
+ `;
1228
+ const kotlin = `${header("//", target, units)}package dev.bakenative.generated
1229
+
1230
+ import android.content.Context
1231
+ import dev.bakenative.modules.BakeNativeModule
1232
+
1233
+ /**
1234
+ * The first-party modules this app's bundles use. BakeNativeView finds this object by name and
1235
+ * registers them with the core built-ins; build your own list with \`modules(context)\`.
1236
+ */
1237
+ object BakeNativeAppModules {
1238
+ @JvmField val names: List<String> = listOf(${[...units.map((u) => u.name), ...auto.map((m) => m.module)].map((n) => JSON.stringify(n)).join(", ")})
1239
+
1240
+ @JvmStatic fun modules(context: Context): List<BakeNativeModule> = listOf(${[...units.map((u) => `${u.unit.class}(context)`), ...auto.map((m) => `${m.class}(${m.context ? "context" : ""})`)].join(", ")})
1241
+ }
1242
+
1243
+ /** The native views this app's bundles use (manifest.json requires.views); the host registers them directly. */
1244
+ object BakeNativeAppViews {
1245
+ @JvmField val names: List<String> = listOf(${views.map((v) => JSON.stringify(v.name)).join(", ")})
1246
+
1247
+ /** Each view's spec signature: an BakeNativePackage's \`provides.views\` (what OTA bundles may require). */
1248
+ @JvmField val signatures: Map<String, String> = mapOf(${views.map((v) => `${JSON.stringify(v.name)} to ${JSON.stringify(v.signature ?? "")}`).join(", ")})
1249
+
1250
+ /** Fresh instances for one root: \`bakeNativeView.views.registerAll(BakeNativeAppViews.views())\` before \`load\`. */
1251
+ @JvmStatic fun views(): List<dev.bakenative.views.BakeNativeNativeView<*>> {
1252
+ ${native.length ? " dev.bakenative.views.NativeViews.load(\"bakeapp-views\") // their commands: src/main/cpp\n" : ""} return listOf(${views.map((v) => `${v.unit.class}()`).join(", ")})
1253
+ }
1254
+ }
1255
+ `;
1256
+ const files = [
1257
+ {
1258
+ path: "build.gradle.kts",
1259
+ text: gradle
1260
+ },
1261
+ {
1262
+ path: "src/main/kotlin/dev/bakenative/generated/BakeNativeAppModules.kt",
1263
+ text: kotlin
1264
+ },
1265
+ {
1266
+ path: "min-sdk",
1267
+ text: `${minSdk}\n`
1268
+ },
1269
+ ...appSources(mods, "src/main/kotlin/app"),
1270
+ ...appSources(own, "src/main/kotlin/app-views")
1271
+ ];
1272
+ if (!native.length) return files;
1273
+ files.push({
1274
+ path: "src/main/cpp/CMakeLists.txt",
1275
+ text: `${header("#", target, units)}# The app's view library: the commands of the native views the bundles use (JSI host functions ->
1276
+ # kolibri -> Kotlin). Links the host's prebuilt core and Hermes (build-rust.sh) and kolibri (Prefab).
1277
+ cmake_minimum_required(VERSION 3.22.1)
1278
+ project(bakeapp_views CXX)
1279
+ set(CMAKE_CXX_STANDARD 20)
1280
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
1281
+ find_package(kolibri-android REQUIRED CONFIG)
1282
+ add_library(bakeapp-views SHARED views.cpp)
1283
+ target_include_directories(bakeapp-views PRIVATE
1284
+ "\${BAKENATIVE_ANDROID}/src/main/cpp"
1285
+ "\${BAKENATIVE_ANDROID}/build/hermes-include"
1286
+ "\${BAKENATIVE_ANDROID}/../../hermes/BakeNativeJSI/include"
1287
+ "\${BAKENATIVE_ANDROID}/../../hermes/BakeNativeHermes/include"
1288
+ \${BAKE_VIEW_INCLUDES})
1289
+ target_link_directories(bakeapp-views PRIVATE "\${BAKENATIVE_ANDROID}/build/rustJniLibs/\${ANDROID_ABI}")
1290
+ target_link_libraries(bakeapp-views PRIVATE kolibri-android::kolibri bakenative bakehermes hermesvm)
1291
+ target_link_options(bakeapp-views PRIVATE "LINKER:--no-undefined")
1292
+ `
1293
+ });
1294
+ files.push({
1295
+ path: "src/main/cpp/views.cpp",
1296
+ text: `${header("//", target, units)}// The app's view library: JNI_OnLoad loads kolibri, registers the runtime natives and the engine
1297
+ // hook, and resolves each view's Kotlin entry points once (BakeNativeViewsAndroid.h).
1298
+ #include <jni.h>
1299
+ ${native.map((v) => `#include "${v.unit.bridge}"`).join("\n")}
1300
+
1301
+ namespace {
1302
+ void install(facebook::jsi::Runtime &rt, bake_engine *engine) {
1303
+ ${native.map((v, i) => ` ${v.unit.namespace}::install(rt, engine, ${i});`).join("\n")}
1304
+ }
1305
+ } // namespace
1306
+
1307
+ extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *) {
1308
+ jint version = bake::views::android::onLoad(vm, {{${native.map((v) => JSON.stringify(v.name)).join(", ")}}, install});
1309
+ JNIEnv *env = expo::kolibri::getEnv();
1310
+ ${native.map((v) => ` ${v.unit.namespace}::warm(env);`).join("\n")}
1311
+ return version;
1312
+ }
1313
+ `
1314
+ });
1315
+ return files;
1316
+ }
1317
+ /** native/rust/Cargo.toml [patch.crates-io], as [crate, path in native/rust]: the vendored crates
1318
+ * every crate built against the BakeNative checkout needs (a test keeps it equal to that file). */
1319
+ const CARGO_PATCHES = [["taffy", "vendor/taffy"]];
1320
+ function windowsFiles(target, units, bakenative, views, mods, auto = [], contracts = [], deps = null, where = null) {
1321
+ const crates = (deps?.all.windows.crates ?? []).map((c) => {
1322
+ const parts = [c.version ? `version = ${q(`=${c.version}`)}` : `path = ${q(where(c.path))}`];
1323
+ if (c.features.length) parts.push(`features = [${c.features.map(q).join(", ")}]`);
1324
+ if (c.defaultFeatures === false) parts.push("default-features = false");
1325
+ return `${c.name} = { ${parts.join(", ")} }\n`;
1326
+ }).join("");
1327
+ const features = [...units, ...views].map((u) => u.unit.feature);
1328
+ if (mods.length) features.push("generated");
1329
+ const toml = `${header("#", target, units)}# The host app depends on this crate; the features turn the modules on in bake-host-windows, whose
1330
+ # modules::builtins() registers them. A module the bundles do not use is not compiled in.
1331
+ [package]
1332
+ name = "bakenative-app-modules"
1333
+ version = "0.0.0"
1334
+ edition = "2024"
1335
+ publish = false
1336
+
1337
+ [lib]
1338
+ path = "lib.rs"
1339
+
1340
+ [dependencies]
1341
+ bake-runtime = { path = ${JSON.stringify(`${bakenative}/native/rust/crates/bake-runtime`)} }
1342
+
1343
+ [target.'cfg(windows)'.dependencies]
1344
+ bake-host-windows = { path = ${JSON.stringify(`${bakenative}/native/rust/crates/bake-host-windows`)}, features = [${features.map((name) => JSON.stringify(name)).join(", ")}] }
1345
+ ${crates}
1346
+ # The BakeNative workspace's patches (native/rust/Cargo.toml), for \`cargo check\` of this crate on its
1347
+ # own; a host whose crate depends on this one carries them itself (Cargo reads a root's patches).
1348
+ [patch.crates-io]
1349
+ ${CARGO_PATCHES.map(([name, path]) => `${name} = { path = ${JSON.stringify(`${bakenative}/native/rust/${path}`)} }`).join("\n")}
1350
+ `;
1351
+ const appMods = mods.map((m) => `
1352
+ #[cfg(windows)]
1353
+ #[path = ${JSON.stringify(`app/${m.name}/${m.files[0].path}`)}]
1354
+ mod ${m.rust};
1355
+ `).join("");
1356
+ const rs = `${header("//", target, units)}
1357
+ /// The first-party modules this crate turns on in bake-host-windows (sorted).
1358
+ pub const MODULES: &[&str] = &[${units.map((u) => JSON.stringify(u.name)).join(", ")}];
1359
+
1360
+ /// The native views this crate turns on (manifest.json requires.views, sorted).
1361
+ pub const VIEWS: &[&str] = &[${views.map((v) => JSON.stringify(v.name)).join(", ")}];
1362
+
1363
+ /// The app modules' contracts (generated from their specs) and \`bundle_modules::root(...)\`.
1364
+ pub mod bundle_modules;
1365
+ ${contracts.map((c) => `pub mod ${snake(c.name)}_spec;\n`).join("")}
1366
+ /// The app's own modules the bundles use (native/<name>, sorted by module name).
1367
+ pub const APP_MODULES: &[&str] = &[${auto.map((m) => JSON.stringify(m.module)).join(", ")}];
1368
+ ${appMods}
1369
+ /// Fresh instances of the app's own modules for one view: the host registers them next to the
1370
+ /// built-ins (\`options.modules.register_arc(m)\` for each).
1371
+ #[cfg(windows)]
1372
+ pub fn modules() -> Vec<std::sync::Arc<dyn bake_runtime::modules::NativeModule>> {
1373
+ vec![${auto.map((m) => `${snake(m.module)}_spec::${snake(m.module)}_module(${m.rust}::${m.module}Module::default())`).join(", ")}]
1374
+ }
1375
+ `;
1376
+ return [
1377
+ {
1378
+ path: "Cargo.toml",
1379
+ text: toml
1380
+ },
1381
+ {
1382
+ path: "lib.rs",
1383
+ text: rs
1384
+ },
1385
+ ...appSources(mods, "app")
1386
+ ];
1387
+ }
1388
+ /**
1389
+ * The BakeNative checkout as the registration in `out` references it: relative, forward slashes.
1390
+ * Taken between the real paths (`out` is created): SwiftPM and Gradle resolve `..` from the
1391
+ * package's real directory, so a lexical path is wrong when either side sits under a symlink
1392
+ * (/var -> /private/var, a home directory linked to another volume).
1393
+ */
1394
+ function checkoutRelative(out, checkout) {
1395
+ mkdirSync(out, { recursive: true });
1396
+ return (relative(realpathSync(out), realpathSync(checkout)) || ".").replaceAll("\\", "/");
1397
+ }
1398
+ /**
1399
+ * Writes `files` under `dir`, leaving a file whose content is already the same untouched (its
1400
+ * modification time too, so the host build does not redo it). Line endings do not count: a
1401
+ * committed registration checked out with CRLF (git core.autocrlf on Windows) is the same file,
1402
+ * and rewriting it with LF would show it as modified. Returns { written, unchanged }.
1403
+ */
1404
+ function writeRegistration(dir, files) {
1405
+ const written = [];
1406
+ const unchanged = [];
1407
+ for (const f of files) {
1408
+ const dest = join(dir, f.path);
1409
+ if (existsSync(dest) && readFileSync(dest, "utf8").replaceAll("\r\n", "\n") === f.text) {
1410
+ unchanged.push(f.path);
1411
+ continue;
1412
+ }
1413
+ mkdirSync(dirname(dest), { recursive: true });
1414
+ writeFileSync(dest, f.text);
1415
+ written.push(f.path);
1416
+ }
1417
+ const keep = new Set(files.map((f) => f.path));
1418
+ for (const prefix of APP_SOURCE_DIRS) {
1419
+ const base = join(dir, prefix);
1420
+ if (!existsSync(base)) continue;
1421
+ const stale = (d) => {
1422
+ for (const entry of readdirSync(d)) {
1423
+ const p = join(d, entry);
1424
+ const rel = relative(dir, p).replaceAll("\\", "/");
1425
+ if (statSync(p).isDirectory()) {
1426
+ stale(p);
1427
+ if (!readdirSync(p).length) rmSync(p, { recursive: true });
1428
+ } else if (!keep.has(rel)) {
1429
+ rmSync(p);
1430
+ written.push(rel);
1431
+ }
1432
+ }
1433
+ };
1434
+ stale(base);
1435
+ if (!readdirSync(base).length) rmSync(base, { recursive: true });
1436
+ }
1437
+ const isContract = (name) => /Spec\.(swift|kt)$|_spec\.rs$/.test(name);
1438
+ const contractDirs = new Set(files.filter((f) => isContract(f.path.split("/").pop()) || /(^|\/)(BakeNativeBundleModules\.(swift|kt)|bundle_modules\.rs)$/.test(f.path)).map((f) => f.path.split("/").slice(0, -1).join("/")));
1439
+ for (const d of contractDirs) {
1440
+ const abs = join(dir, d);
1441
+ if (!existsSync(abs)) continue;
1442
+ for (const entry of readdirSync(abs)) {
1443
+ const rel = d ? `${d}/${entry}` : entry;
1444
+ if (isContract(entry) && !keep.has(rel) && statSync(join(abs, entry)).isFile()) {
1445
+ rmSync(join(abs, entry));
1446
+ written.push(rel);
1447
+ }
1448
+ }
1449
+ }
1450
+ return {
1451
+ written,
1452
+ unchanged
1453
+ };
1454
+ }
1455
+ /** Where the registration keeps copies of the app's module sources (apple, android, windows). */
1456
+ const APP_SOURCE_DIRS = [
1457
+ "Sources/BakeNativeAppModules/App",
1458
+ "src/main/kotlin/app",
1459
+ "src/main/kotlin/app-views",
1460
+ "app"
1461
+ ];
1462
+ /** The native views of bundles (their manifest.json `requires.views` keys), as a sorted union. */
1463
+ function bundleViews(manifests) {
1464
+ const out = /* @__PURE__ */ new Set();
1465
+ for (const { manifest } of manifests) for (const name of Object.keys(manifest?.requires?.views ?? {})) out.add(name);
1466
+ return [...out].sort();
1467
+ }
1468
+ /** The app's own modules the bundles call: { required, optional }, sorted unions. */
1469
+ function bundleAppModules(manifests) {
1470
+ const required = /* @__PURE__ */ new Set();
1471
+ const optional = /* @__PURE__ */ new Set();
1472
+ for (const { manifest } of manifests) {
1473
+ for (const m of manifest?.requires?.nativeModules ?? []) required.add(m);
1474
+ for (const m of manifest?.requires?.optionalNativeModules ?? []) optional.add(m);
1475
+ }
1476
+ return {
1477
+ required: [...required].sort(),
1478
+ optional: [...optional].filter((m) => !required.has(m)).sort()
1479
+ };
1480
+ }
1481
+ /**
1482
+ * The first-party modules of bundles (their manifest.json `requires.modules`), as a sorted union.
1483
+ * Throws for a manifest written before `requires.modules` existed.
1484
+ */
1485
+ function bundleModules(manifests) {
1486
+ const out = /* @__PURE__ */ new Set();
1487
+ for (const { file, manifest } of manifests) {
1488
+ const m = manifest?.requires?.modules;
1489
+ if (!Array.isArray(m)) throw new Error(`${file} has no requires.modules (built by an older bake): rebuild the bundle`);
1490
+ for (const name of m) out.add(name);
1491
+ }
1492
+ return [...out].sort();
1493
+ }
1494
+ /**
1495
+ * The app modules for the registration (src/registry.mjs appModules, those the bundles use):
1496
+ * [{ name, module, locked, files: [{ path, text }], deps }]; `locked`: in bake-modules.json (a registry
1497
+ * module: the generated code creates it); `deps`: its native dependencies (src/native-deps.mjs) or null.
1498
+ * `target`: only its host family's dependency paths must exist.
1499
+ * @param {{ name: string, module: string, dir: string, files: { path: string }[] }[]} modules @param {string} [root] @param {string} [target]
1500
+ */
1501
+ function appModuleSources(modules, root, target) {
1502
+ let locked = {};
1503
+ try {
1504
+ locked = root ? readLock(root).modules : {};
1505
+ } catch {}
1506
+ return modules.map((m) => ({
1507
+ name: m.name,
1508
+ module: m.module,
1509
+ locked: m.name in locked,
1510
+ files: m.files.map((f) => ({
1511
+ path: f.path,
1512
+ text: readFileSync(join(m.dir, f.path), "utf8")
1513
+ })),
1514
+ deps: readNativeDeps(root ?? join(m.dir, "..", ".."), join(m.dir, `${m.module}.native.ts`), { family: target ? FAMILY[target] : null })
1515
+ }));
1516
+ }
1517
+ // xcframework.mjs
1518
+ /** Deployment targets: keep equal to Package.swift and build-hermes (--macos / --ios). */
1519
+ const IOS_MIN = "16.0";
1520
+ const MACOS_MIN = "14.0";
1521
+ /** One framework slice per entry. `mac` frameworks use the versioned bundle layout. */
1522
+ const SLICES = {
1523
+ ios: {
1524
+ sdk: "iphoneos",
1525
+ target: `arm64-apple-ios${IOS_MIN}`,
1526
+ triple: "arm64-apple-ios",
1527
+ platform: "iPhoneOS",
1528
+ os: "ios"
1529
+ },
1530
+ "ios-sim": {
1531
+ sdk: "iphonesimulator",
1532
+ target: `arm64-apple-ios${IOS_MIN}-simulator`,
1533
+ triple: "arm64-apple-ios-simulator",
1534
+ platform: "iPhoneSimulator",
1535
+ os: "ios"
1536
+ },
1537
+ mac: {
1538
+ sdk: "macosx",
1539
+ target: `arm64-apple-macos${MACOS_MIN}`,
1540
+ triple: "arm64-apple-macos",
1541
+ platform: "MacOSX",
1542
+ os: "mac"
1543
+ }
1544
+ };
1545
+ /** Slices per `bake` target. */
1546
+ const TARGET_SLICES = {
1547
+ ios: ["ios", "ios-sim"],
1548
+ mac: ["mac"]
1549
+ };
1550
+ /** Runtime module per OS: what host apps `import`. */
1551
+ const RUNTIME_MODULE = {
1552
+ ios: "BakeNativeKit",
1553
+ mac: "BakeNativeAppKit"
1554
+ };
1555
+ const sdkPaths = {};
1556
+ function sdkPath(sdk) {
1557
+ return sdkPaths[sdk] ??= execFileSync("xcrun", [
1558
+ "--sdk",
1559
+ sdk,
1560
+ "--show-sdk-path"
1561
+ ], { encoding: "utf8" }).trim();
1562
+ }
1563
+ /** Runs a tool, collecting output; rejects with the tail of the output on failure. */
1564
+ function run(cmd, args, { cwd, quiet = true } = {}) {
1565
+ return new Promise((resolvePromise, reject) => {
1566
+ const p = spawn(cmd, args, {
1567
+ cwd,
1568
+ stdio: [
1569
+ "ignore",
1570
+ "pipe",
1571
+ "pipe"
1572
+ ]
1573
+ });
1574
+ let out = "";
1575
+ p.stdout.on("data", (d) => {
1576
+ out += d;
1577
+ if (!quiet) process.stdout.write(d);
1578
+ });
1579
+ p.stderr.on("data", (d) => {
1580
+ out += d;
1581
+ if (!quiet) process.stderr.write(d);
1582
+ });
1583
+ p.on("error", reject);
1584
+ p.on("close", (code) => {
1585
+ if (code === 0) resolvePromise(out);
1586
+ else reject(/* @__PURE__ */ new Error(`${cmd} ${args.slice(0, 3).join(" ")}... failed (${code}):\n${out.split("\n").filter((l) => /error|undefined|Undefined|^\s+"_|referenced from/.test(l)).slice(0, 40).join("\n") || out.slice(-4e3)}`));
1587
+ });
1588
+ });
1589
+ }
1590
+ function listFiles(dir, ext) {
1591
+ const out = [];
1592
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
1593
+ const p = join(dir, e.name);
1594
+ if (e.isDirectory()) out.push(...listFiles(p, ext));
1595
+ else if (!ext || e.name.endsWith(ext)) out.push(p);
1596
+ }
1597
+ return out.sort();
1598
+ }
1599
+ function plist(dict) {
1600
+ const v = (x) => Array.isArray(x) ? `<array>${x.map(v).join("")}</array>` : `<string>${x}</string>`;
1601
+ return `<?xml version="1.0" encoding="UTF-8"?>
1602
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1603
+ <plist version="1.0">
1604
+ <dict>
1605
+ ${Object.entries(dict).map(([k, x]) => ` <key>${k}</key>${v(x)}`).join("\n")}
1606
+ </dict>
1607
+ </plist>
1608
+ `;
1609
+ }
1610
+ /**
1611
+ * Compiles one framework slice.
1612
+ * module Swift module = framework name
1613
+ * swift Swift sources (already staged: unique basenames)
1614
+ * cxx C++ sources, compiled with hidden visibility (never exported)
1615
+ * includes -I for C++ and for Swift's Clang importer (private module maps live here)
1616
+ * frameworkPaths -F (e.g. the runtime slice an app framework links against)
1617
+ * frameworks -framework to link
1618
+ * staticLibs [{ dir, name }] linked with -hidden-l: everything in them stays private
1619
+ * keepSymbols linker roots to retain despite dead stripping
1620
+ * resources directory copied into the framework's resources as `resourcesName`
1621
+ * localizations directory of compiled <lang>.lproj copied into the framework's resources
1622
+ * extraResources directory whose files are copied into the framework's resources (the
1623
+ * runtime's THIRD_PARTY_NOTICES.txt / .json)
1624
+ */
1625
+ async function buildFramework({ module, slice, swift, cxx = [], includes = [], frameworkPaths = [], frameworks = [], staticLibs = [], keepSymbols = [], resources, resourcesName, localizations, extraResources, bundleId, version, work, out, isStatic = false, swiftFlags = [] }) {
1626
+ const s = SLICES[slice];
1627
+ const sdk = sdkPath(s.sdk);
1628
+ const obj = join(work, "obj");
1629
+ rmSync(work, {
1630
+ recursive: true,
1631
+ force: true
1632
+ });
1633
+ mkdirSync(obj, { recursive: true });
1634
+ const objects = await Promise.all(cxx.map(async (src) => {
1635
+ const o = join(obj, basename(src).replace(/\.\w+$/, ".o"));
1636
+ await run("xcrun", [
1637
+ "--sdk",
1638
+ s.sdk,
1639
+ "clang++",
1640
+ "-target",
1641
+ s.target,
1642
+ "-isysroot",
1643
+ sdk,
1644
+ "-std=c++17",
1645
+ "-O2",
1646
+ "-fvisibility=hidden",
1647
+ "-fvisibility-inlines-hidden",
1648
+ "-fno-common",
1649
+ ...includes.flatMap((i) => ["-I", i]),
1650
+ "-c",
1651
+ src,
1652
+ "-o",
1653
+ o
1654
+ ]);
1655
+ return o;
1656
+ }));
1657
+ const mod = join(work, "mod");
1658
+ mkdirSync(mod, { recursive: true });
1659
+ const binary = join(work, module);
1660
+ const iface = join(mod, `${s.triple}.swiftinterface`);
1661
+ const privIface = join(mod, `${s.triple}.private.swiftinterface`);
1662
+ await run("xcrun", [
1663
+ "--sdk",
1664
+ s.sdk,
1665
+ "swiftc",
1666
+ "-module-name",
1667
+ module,
1668
+ "-parse-as-library",
1669
+ "-language-mode",
1670
+ "6",
1671
+ "-target",
1672
+ s.target,
1673
+ "-sdk",
1674
+ sdk,
1675
+ "-O",
1676
+ "-whole-module-optimization",
1677
+ "-num-threads",
1678
+ "8",
1679
+ "-enable-library-evolution",
1680
+ "-verify-emitted-module-interface",
1681
+ "-emit-module",
1682
+ "-emit-module-path",
1683
+ join(work, `${module}.swiftmodule`),
1684
+ "-emit-module-interface-path",
1685
+ iface,
1686
+ "-emit-private-module-interface-path",
1687
+ privIface,
1688
+ "-module-cache-path",
1689
+ join(dirname(work), "module-cache"),
1690
+ "-emit-library",
1691
+ "-o",
1692
+ binary,
1693
+ ...includes.flatMap((i) => ["-I", i]),
1694
+ ...swiftFlags,
1695
+ ...frameworkPaths.flatMap((f) => ["-F", f]),
1696
+ ...isStatic ? [
1697
+ "-static",
1698
+ ...objects,
1699
+ ...swift
1700
+ ] : linkFlags()
1701
+ ]);
1702
+ function linkFlags() {
1703
+ return [
1704
+ ...frameworks.flatMap((f) => ["-framework", f]),
1705
+ "-Xlinker",
1706
+ "-install_name",
1707
+ "-Xlinker",
1708
+ s.os === "mac" ? `@rpath/${module}.framework/Versions/A/${module}` : `@rpath/${module}.framework/${module}`,
1709
+ "-Xlinker",
1710
+ "-dead_strip",
1711
+ ...staticLibs.length || cxx.length ? [
1712
+ "-Xlinker",
1713
+ "-unexported_symbol",
1714
+ "-Xlinker",
1715
+ "__Z*"
1716
+ ] : [],
1717
+ ...keepSymbols.flatMap((symbol) => [
1718
+ "-Xlinker",
1719
+ "-u",
1720
+ "-Xlinker",
1721
+ symbol
1722
+ ]),
1723
+ ...staticLibs.flatMap((l) => [
1724
+ "-L",
1725
+ l.dir,
1726
+ "-Xlinker",
1727
+ `-hidden-l${l.name}`
1728
+ ]),
1729
+ ...staticLibs.length || cxx.length ? ["-lc++"] : [],
1730
+ ...objects,
1731
+ ...swift
1732
+ ];
1733
+ }
1734
+ const fw = join(out, `${module}.framework`);
1735
+ rmSync(fw, {
1736
+ recursive: true,
1737
+ force: true
1738
+ });
1739
+ const root = s.os === "mac" ? join(fw, "Versions/A") : fw;
1740
+ const res = s.os === "mac" ? join(root, "Resources") : root;
1741
+ mkdirSync(join(root, "Modules", `${module}.swiftmodule`), { recursive: true });
1742
+ mkdirSync(res, { recursive: true });
1743
+ cpSync(binary, join(root, module));
1744
+ for (const f of readdirSync(mod)) cpSync(join(mod, f), join(root, "Modules", `${module}.swiftmodule`, f));
1745
+ const info = {
1746
+ CFBundleDevelopmentRegion: "en",
1747
+ CFBundleExecutable: module,
1748
+ CFBundleIdentifier: bundleId,
1749
+ CFBundleInfoDictionaryVersion: "6.0",
1750
+ CFBundleName: module,
1751
+ CFBundlePackageType: "FMWK",
1752
+ CFBundleShortVersionString: version,
1753
+ CFBundleVersion: version,
1754
+ CFBundleSupportedPlatforms: [s.platform],
1755
+ ...s.os === "mac" ? { LSMinimumSystemVersion: MACOS_MIN } : { MinimumOSVersion: IOS_MIN }
1756
+ };
1757
+ writeFileSync(join(res, "Info.plist"), plist(info));
1758
+ if (resources) cpSync(resources, join(res, resourcesName ?? basename(resources)), { recursive: true });
1759
+ if (localizations) for (const l of readdirSync(localizations)) cpSync(join(localizations, l), join(res, l), { recursive: true });
1760
+ if (extraResources) for (const f of readdirSync(extraResources)) cpSync(join(extraResources, f), join(res, f), { recursive: true });
1761
+ if (s.os === "mac") {
1762
+ symlinkSync("A", join(fw, "Versions/Current"));
1763
+ for (const name of [
1764
+ module,
1765
+ "Modules",
1766
+ "Resources"
1767
+ ]) symlinkSync(`Versions/Current/${name}`, join(fw, name));
1768
+ }
1769
+ return {
1770
+ framework: fw,
1771
+ interface: iface,
1772
+ privateInterface: privIface,
1773
+ resources: res
1774
+ };
1775
+ }
1776
+ async function createXCFramework(frameworks, output) {
1777
+ rmSync(output, {
1778
+ recursive: true,
1779
+ force: true
1780
+ });
1781
+ await run("xcodebuild", [
1782
+ "-create-xcframework",
1783
+ ...frameworks.flatMap((f) => ["-framework", f]),
1784
+ "-output",
1785
+ output
1786
+ ]);
1787
+ return output;
1788
+ }
1789
+ /**
1790
+ * Zips an xcframework for remote hosting; returns { zip, checksum } (the SHA-256 that
1791
+ * `swift package compute-checksum` prints). With `reuse`, an existing zip newer than the
1792
+ * xcframework is kept, so every package shipping the same runtime gets the same checksum.
1793
+ */
1794
+ async function zipForSwiftPM(xcframework, { reuse = false } = {}) {
1795
+ const zip = `${xcframework}.zip`;
1796
+ if (!(reuse && existsSync(zip) && statSync(zip).mtimeMs >= statSync(join(xcframework, "Info.plist")).mtimeMs)) {
1797
+ rmSync(zip, { force: true });
1798
+ await run("ditto", [
1799
+ "-c",
1800
+ "-k",
1801
+ "--sequesterRsrc",
1802
+ "--keepParent",
1803
+ xcframework,
1804
+ zip
1805
+ ]);
1806
+ }
1807
+ return {
1808
+ zip,
1809
+ checksum: createHash("sha256").update(readFileSync(zip)).digest("hex")
1810
+ };
1811
+ }
1812
+ /** The runtime slice directory inside an xcframework (where `<Module>.framework` lives). */
1813
+ function xcframeworkSlice(xcframework, slice) {
1814
+ const want = {
1815
+ ios: "ios-arm64",
1816
+ "ios-sim": "ios-arm64-simulator",
1817
+ mac: "macos-arm64"
1818
+ }[slice];
1819
+ const dir = join(xcframework, want);
1820
+ if (!existsSync(dir)) throw new Error(`${xcframework} has no ${want} slice`);
1821
+ return dir;
1822
+ }
1823
+ /** Swift identifier for a product name ("my-app" -> "MyApp"). */
1824
+ function productName(raw) {
1825
+ const name = raw.replace(/[^A-Za-z0-9]+(.)?/g, (_, c) => c ? c.toUpperCase() : "").replace(/^[a-z]/, (c) => c.toUpperCase());
1826
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) throw new Error(`"${raw}" is not usable as a Swift module name`);
1827
+ if (/^BakeNative/.test(name)) throw new Error(`product name "${name}" clashes with the BakeNative runtime modules`);
1828
+ return name;
1829
+ }
1830
+ /** The generated entry point: one line in the host app shows the screen. */
1831
+ function appEntrySwift(product, os, { runtimeImport = true, moduleClasses = [], viewClasses = [] } = {}) {
1832
+ const runtime = RUNTIME_MODULE[os];
1833
+ const head = `// Generated by \`bake build --xcframework\`. Do not edit.
1834
+ ${runtimeImport ? `@_exported import ${runtime}\n` : ""}import Foundation
1835
+ import SwiftUI
1836
+ `;
1837
+ const bundle = `
1838
+ private final class BundleToken {}
1839
+
1840
+ /// ${product}: an BakeNative app (app.hbc + app.baked + app.css) shipped inside ${product}.framework.
1841
+ public enum ${product} {
1842
+ /// The app bundle inside the framework's resources.
1843
+ public static var bundle: BakeNativeBundle {
1844
+ let resources = Bundle(for: BundleToken.self).resourceURL ?? Bundle(for: BundleToken.self).bundleURL
1845
+ return BakeNativeBundle(directory: resources.appendingPathComponent("BakeNativeApp", isDirectory: true))
1846
+ }
1847
+
1848
+ /// The first-party modules the bundle uses (manifest.json \`requires.modules\`), compiled into
1849
+ /// this framework; every view below registers them. Pass them to \`modules:\` of your own views.
1850
+ public static func modules() -> [BakeNativeModule] { [${moduleClasses.map((c) => `${c}()`).join(", ")}] }
1851
+
1852
+ /// The native views the bundle renders (manifest.json \`requires.views\`), compiled into this
1853
+ /// framework: a static list, no lookup by name. Pass them to \`views:\` of your own views.
1854
+ @MainActor public static func views() -> [any BakeNativeNativeViewType.Type] { [${viewClasses.map((c) => `${c}.self`).join(", ")}] }
1855
+ `;
1856
+ if (os === "ios") return `${head}import UIKit
1857
+ ${bundle}
1858
+ /// A UIKit view showing the app. It starts once it has a width; call \`stop()\` when it goes away for good.
1859
+ @MainActor public static func makeView(hydration: HydrationStrategy = .load,
1860
+ options: BakeNativeView.Options = BakeNativeView.Options()) -> BakeNativeView {
1861
+ let view = BakeNativeView(bundle: bundle, hydration: hydration, options: options, modules: modules(), views: views())
1862
+ view.launch()
1863
+ return view
1864
+ }
1865
+
1866
+ /// A view controller showing the app (push or present it from any flow).
1867
+ @MainActor public static func makeViewController(hydration: HydrationStrategy = .load,
1868
+ options: BakeNativeView.Options = BakeNativeView.Options()) -> BakeNativeViewController {
1869
+ BakeNativeViewController(bundle: bundle, hydration: hydration, options: options, modules: modules(), views: views())
1870
+ }
1871
+ }
1872
+
1873
+ /// SwiftUI: \`${product}View()\`.
1874
+ public struct ${product}View: View {
1875
+ let hydration: HydrationStrategy
1876
+ let options: BakeNativeView.Options
1877
+ public init(hydration: HydrationStrategy = .load, options: BakeNativeView.Options = BakeNativeView.Options()) {
1878
+ self.hydration = hydration
1879
+ self.options = options
1880
+ }
1881
+ public var body: some View {
1882
+ BakeNativeSurface(bundle: ${product}.bundle, hydration: hydration, options: options, modules: ${product}.modules(),
1883
+ views: ${product}.views())
1884
+ }
1885
+ }
1886
+ `;
1887
+ return `${head}import AppKit
1888
+ ${bundle}
1889
+ /// An AppKit view (scroll view) showing the app.
1890
+ @MainActor public static func makeView(hydration: HydrationStrategy = .load) -> BakeNativeView {
1891
+ let view = BakeNativeView(hydration: hydration, modules: modules(), views: views())
1892
+ let bundle = bundle
1893
+ DispatchQueue.main.async { view.launch(bundle) } // once it has a size
1894
+ return view
1895
+ }
1896
+ }
1897
+
1898
+ /// SwiftUI: \`${product}View()\`.
1899
+ public struct ${product}View: View {
1900
+ let hydration: HydrationStrategy
1901
+ public init(hydration: HydrationStrategy = .load) { self.hydration = hydration }
1902
+ public var body: some View {
1903
+ BakeNativeView(bundle: ${product}.bundle, hydration: hydration, modules: ${product}.modules(), views: ${product}.views())
1904
+ }
1905
+ }
1906
+ `;
1907
+ }
1908
+ /** Files of a built target directory that go into the framework (`BakeNativeApp/`). */
1909
+ const BUNDLE_FILES = [
1910
+ "app.hbc",
1911
+ "app.css",
1912
+ "app.baked",
1913
+ "manifest.json",
1914
+ "THIRD_PARTY_NOTICES.txt",
1915
+ "THIRD_PARTY_NOTICES.json"
1916
+ ];
1917
+ /**
1918
+ * The third-party notices the runtime xcframework's `slices` carry (THIRD_PARTY_NOTICES.json in
1919
+ * each framework's resources, written by tools/build-xcframework): [{ slice, framework, file }].
1920
+ * Throws when a slice has none (a runtime built before the notices).
1921
+ */
1922
+ function runtimeNoticeFiles(xcframework, slices) {
1923
+ return slices.map((slice) => {
1924
+ const dir = xcframeworkSlice(xcframework, slice);
1925
+ const framework = readdirSync(dir).find((f) => f.endsWith(".framework"));
1926
+ const file = framework && [join(dir, framework, "Resources/THIRD_PARTY_NOTICES.json"), join(dir, framework, "THIRD_PARTY_NOTICES.json")].find((f) => existsSync(f));
1927
+ if (!file) throw new Error(`${xcframework} (${slice}) carries no THIRD_PARTY_NOTICES.json: rebuild the runtime with this BakeNative (tools/build-xcframework) or reinstall @bake-native/core`);
1928
+ return {
1929
+ slice,
1930
+ framework,
1931
+ file
1932
+ };
1933
+ });
1934
+ }
1935
+ function copyBundleFiles(bundleDir, resources) {
1936
+ const manifest = join(bundleDir, "manifest.json");
1937
+ const files = new Set(BUNDLE_FILES.filter((file) => existsSync(join(bundleDir, file))));
1938
+ if (existsSync(manifest)) for (const { file } of Object.values(JSON.parse(readFileSync(manifest, "utf8")).frames ?? {})) {
1939
+ if (!/^app(?:\.[a-zA-Z0-9-]+)?\.baked$/.test(file)) throw new Error(`Invalid locale frame in ${manifest}: ${file}`);
1940
+ files.add(file);
1941
+ }
1942
+ for (const file of files) cpSync(join(bundleDir, file), join(resources, file));
1943
+ }
1944
+ /**
1945
+ * <Product>.xcframework for one `bake` target (ios: device + simulator; mac): the bundle in
1946
+ * `bundleDir` as resources + the generated entry point, linked against the runtime
1947
+ * (`runtime` = BakeNative.xcframework) or, with `embedRuntime`, compiled together with it.
1948
+ */
1949
+ async function buildAppXCFramework({ product, target, bundleDir, runtime, embedRuntime, work, outDir, version, modules = [], views = [] }) {
1950
+ const os = target;
1951
+ const resources = join(work, "BakeNativeApp");
1952
+ rmSync(resources, {
1953
+ recursive: true,
1954
+ force: true
1955
+ });
1956
+ mkdirSync(resources, { recursive: true });
1957
+ copyBundleFiles(bundleDir, resources);
1958
+ if (existsSync(join(bundleDir, "assets"))) cpSync(join(bundleDir, "assets"), join(resources, "assets"), { recursive: true });
1959
+ if (existsSync(join(bundleDir, "fonts"))) cpSync(join(bundleDir, "fonts"), join(resources, "fonts"), { recursive: true });
1960
+ if (!existsSync(join(resources, "app.hbc"))) throw new Error(`${bundleDir}/app.hbc is missing (hermesc did not run?)`);
1961
+ const firstParty = firstPartySources(os, modules);
1962
+ if (views.length && !embedRuntime) throw new Error(`native views (${views.join(", ")}) need --embed-runtime for now: the runtime framework does not export the C ABI their JSI glue calls`);
1963
+ const nativeViews = viewSources(os, views, join(work, "views"));
1964
+ const entry = join(work, `${product}.swift`);
1965
+ writeFileSync(entry, appEntrySwift(product, os, {
1966
+ runtimeImport: !embedRuntime,
1967
+ moduleClasses: firstParty.classes,
1968
+ viewClasses: nativeViews.classes
1969
+ }));
1970
+ return createXCFramework(await Promise.all(TARGET_SLICES[target].map(async (slice) => {
1971
+ const common = {
1972
+ module: product,
1973
+ slice,
1974
+ resources,
1975
+ resourcesName: "BakeNativeApp",
1976
+ bundleId: `dev.bakenative.app.${product}`,
1977
+ version,
1978
+ work: join(work, "build", slice),
1979
+ out: join(work, "frameworks", slice)
1980
+ };
1981
+ if (embedRuntime) {
1982
+ const spec = await embedRuntime(slice, product, join(work, "stage", slice));
1983
+ return (await buildFramework({
1984
+ ...common,
1985
+ ...spec,
1986
+ swift: [
1987
+ ...spec.swift,
1988
+ ...firstParty.swift,
1989
+ ...nativeViews.swift,
1990
+ entry
1991
+ ],
1992
+ cxx: [...spec.cxx, ...nativeViews.cxx],
1993
+ includes: [...spec.includes, ...nativeViews.includes],
1994
+ swiftFlags: [...spec.swiftFlags ?? [], ...nativeViews.swiftFlags]
1995
+ })).framework;
1996
+ }
1997
+ return (await buildFramework({
1998
+ ...common,
1999
+ swift: [...firstParty.swift, entry],
2000
+ frameworkPaths: [xcframeworkSlice(runtime, slice)],
2001
+ frameworks: [RUNTIME_MODULE[os]]
2002
+ })).framework;
2003
+ })), join(outDir, `${product}.xcframework`));
2004
+ }
2005
+ /**
2006
+ * dist/<target>-spm/Package.swift: one library product `<Product>` = the binaries in `names`
2007
+ * (`<Product>` + `BakeNative`, or `<Product>` alone with the runtime embedded). With `remote`
2008
+ * ({ baseURL, checksums }) the binaries are zips at `<baseURL>/<name>.xcframework.zip`.
2009
+ */
2010
+ function packageSwift({ product, target, names, remote }) {
2011
+ const platform = target === "ios" ? `.iOS("${IOS_MIN}")` : `.macOS("${MACOS_MIN}")`;
2012
+ const bin = (name) => remote ? `.binaryTarget(\n name: "${name}",\n url: "${remote.baseURL}/${name}.xcframework.zip",\n checksum: "${remote.checksums[name]}"\n )` : `.binaryTarget(name: "${name}", path: "${name}.xcframework")`;
2013
+ return `// swift-tools-version: 5.9
2014
+ // Generated by \`bake build --xcframework\`. Add this package to a host app and \`import ${product}\`.
2015
+ import PackageDescription
2016
+
2017
+ let package = Package(
2018
+ name: "${product}",
2019
+ platforms: [${platform}],
2020
+ products: [
2021
+ .library(name: "${product}", targets: [${names.map((n) => `"${n}"`).join(", ")}]),
2022
+ ],
2023
+ targets: [
2024
+ ${names.map((n) => ` ${bin(n)},`).join("\n")}
2025
+ ]
2026
+ )
2027
+ `;
2028
+ }
2029
+ /**
2030
+ * The sources of the native views `names` (manifest.json `requires.views`) for an app framework
2031
+ * built with the runtime in it: per view the generated Swift base + its interop entry, the
2032
+ * implementation (native-support.json `views.<Name>.build.apple.sources`) and the generated C++
2033
+ * JSI glue, staged into one module. The module is compiled with C++ interop for the glue's
2034
+ * `internal import`; `-disable-cxx-interop-requirement-at-import` keeps it importable from plain
2035
+ * Swift (the app), as the SwiftPM targets do (docs/design/native-views.md §6).
2036
+ */
2037
+ function viewSources(os, names, dir) {
2038
+ if (!names.length) return {
2039
+ swift: [],
2040
+ cxx: [],
2041
+ includes: [],
2042
+ classes: [],
2043
+ swiftFlags: []
2044
+ };
2045
+ const repoRoot = resolve(packageRoot$1, "../..");
2046
+ const pkg = join(repoRoot, "packages/core");
2047
+ const support = JSON.parse(readFileSync(join(pkg, "native-support.json"), "utf8")).views ?? {};
2048
+ rmSync(dir, {
2049
+ recursive: true,
2050
+ force: true
2051
+ });
2052
+ mkdirSync(join(dir, "include"), { recursive: true });
2053
+ const swift = [], cxx = [], classes = [], maps = [], headers = [];
2054
+ for (const name of [...new Set(names)].sort()) {
2055
+ const unit = support[name]?.build?.apple;
2056
+ if (!unit || !(support[name].targets ?? []).includes(os)) throw new Error(`the ${name} view has no ${os} implementation (native-support.json views.${name})`);
2057
+ const generated = join(pkg, "views/generated/apple");
2058
+ const files = [...listFiles(join(generated, `${name}ViewSpec`), ".swift"), ...listFiles(join(repoRoot, unit.sources), ".swift")];
2059
+ for (const file of files) {
2060
+ const staged = join(dir, basename(file));
2061
+ const text = readFileSync(file, "utf8").replace(/^([ \t]*)import[ \t]+(BakeNativeNativeViews|BakeNativeApple|BakeNativeCore|BakeNativeViewVideoSpec|BakeNative\w+ViewSpec|BakeNativeView\w+Spec)[ \t]*$/gm, "$1// (merged into this module)");
2062
+ writeFileSync(staged, text);
2063
+ swift.push(staged);
2064
+ }
2065
+ cxx.push(...listFiles(join(generated, `${name}ViewJSI`), ".cpp"));
2066
+ headers.push(join(generated, `${name}ViewJSI/include`));
2067
+ maps.push(`module ${name}ViewJSI {\n header "${join(generated, `${name}ViewJSI/include/${name}ViewJSIApple.h`)}"\n requires cplusplus\n export *\n}\n`);
2068
+ classes.push(unit.class);
2069
+ }
2070
+ writeFileSync(join(dir, "include/module.modulemap"), maps.join(""));
2071
+ return {
2072
+ swift,
2073
+ cxx,
2074
+ classes,
2075
+ includes: [
2076
+ join(dir, "include"),
2077
+ ...headers,
2078
+ join(repoRoot, "native/hermes/BakeNativeJSI/include"),
2079
+ join(repoRoot, "native/hermes/artifacts/include"),
2080
+ join(repoRoot, "native/rust/apple/Sources/CBakeNativeRust/include")
2081
+ ],
2082
+ swiftFlags: [
2083
+ "-cxx-interoperability-mode=default",
2084
+ "-Xfrontend",
2085
+ "-disable-cxx-interop-requirement-at-import"
2086
+ ]
2087
+ };
2088
+ }
2089
+ /**
2090
+ * The Swift sources and classes of the first-party modules `names` (manifest.json
2091
+ * `requires.modules`) for an app framework or package: they compile into its module, so a
2092
+ * framework holds exactly the modules its bundle uses (their files import the runtime module
2093
+ * only when it is a separate one).
2094
+ */
2095
+ function firstPartySources(target, names) {
2096
+ const units = moduleUnits(target, names);
2097
+ const repoRoot = resolve(packageRoot$1, "../..");
2098
+ const missing = units.find((u) => !existsSync(join(repoRoot, u.unit.sources)));
2099
+ if (missing) throw new Error(`the ${missing.name} module's sources (${missing.unit.sources}) are not here: build app frameworks and packages from an BakeNative checkout`);
2100
+ return {
2101
+ swift: units.flatMap((u) => listFiles(join(repoRoot, u.unit.sources), ".swift")),
2102
+ classes: units.map((u) => u.unit.class)
2103
+ };
2104
+ }
2105
+ /**
2106
+ * The generated entry point of an app package: the package (its bundle, its own modules) and
2107
+ * the few calls a host makes. `moduleClasses`: the package's BakeNativeModule classes (init()).
2108
+ */
2109
+ function packageEntrySwift(product, moduleClasses) {
2110
+ return `// Generated by \`bake package\`. Do not edit.
2111
+ @_exported import BakeNativeKit
2112
+ import Foundation
2113
+ import SwiftUI
2114
+ import UIKit
2115
+
2116
+ private final class PackageToken {}
2117
+
2118
+ /// ${product}: an BakeNative app package. Its bundle, its native modules (${moduleClasses.join(", ") || "none"})
2119
+ /// and BakeNativePackage.json are inside ${product}.framework; it runs on the host's BakeNative.xcframework.
2120
+ public enum ${product} {
2121
+ /// The package: the embedded bundle and the modules every screen registers. Their member
2122
+ /// signatures are what the package provides to an update (\`BakeNativePackage.check(update:)\`).
2123
+ public static let package = BakeNativePackage(resources: resources, modules: { [${moduleClasses.map((c) => `${c}()`).join(", ")}] })
2124
+
2125
+ /// \`${product}.framework/BakeNativeApp\`: next to this code when it is a dynamic framework, else in
2126
+ /// the app's Frameworks (Xcode embeds a static framework's resources there).
2127
+ static var resources: URL {
2128
+ let own = Bundle(for: PackageToken.self).bundleURL
2129
+ if own.lastPathComponent == "${product}.framework" { return own.appendingPathComponent("BakeNativeApp", isDirectory: true) }
2130
+ let main = Bundle.main
2131
+ for base in [main.privateFrameworksURL, main.resourceURL].compactMap({ $0 }) {
2132
+ let dir = base.appendingPathComponent("${product}.framework/BakeNativeApp", isDirectory: true)
2133
+ if FileManager.default.fileExists(atPath: dir.appendingPathComponent("BakeNativePackage.json").path) { return dir }
2134
+ }
2135
+ return (main.privateFrameworksURL ?? main.bundleURL).appendingPathComponent("${product}.framework/BakeNativeApp", isDirectory: true)
2136
+ }
2137
+
2138
+ /// The app's screen. \`capabilities\`: the host capabilities the package declares (requires).
2139
+ @MainActor public static func makeViewController(capabilities: [BakeNativeModule] = [],
2140
+ hydration: HydrationStrategy = .load) -> UIViewController {
2141
+ package.makeViewController(capabilities: capabilities, hydration: hydration)
2142
+ }
2143
+
2144
+ /// Prepares the first screen (no JS) while the host's UI is up: call it when the entry to the
2145
+ /// app becomes visible.
2146
+ @MainActor @discardableResult public static func prewarm() -> BakeNativePrewarmCancel { package.prewarm() }
2147
+
2148
+ /// OTA: run the bundle in \`directory\` when everything it requires (manifest.json
2149
+ /// \`requires\`) is provided by the runtime and this package (same native member signatures),
2150
+ /// else keep the embedded bundle. Adding members or changing native code keeps old bundles.
2151
+ @discardableResult public static func use(update directory: URL?) -> BakeNativePackage.UpdateDecision {
2152
+ package.use(update: directory)
2153
+ }
2154
+ }
2155
+
2156
+ /// SwiftUI: \`${product}View()\`.
2157
+ public struct ${product}View: View {
2158
+ let capabilities: [BakeNativeModule]
2159
+ let hydration: HydrationStrategy
2160
+ public init(capabilities: [BakeNativeModule] = [], hydration: HydrationStrategy = .load) {
2161
+ self.capabilities = capabilities
2162
+ self.hydration = hydration
2163
+ }
2164
+ public var body: some View {
2165
+ BakeNativePackageView(${product}.package, capabilities: capabilities, hydration: hydration).ignoresSafeArea()
2166
+ }
2167
+ }
2168
+ `;
2169
+ }
2170
+ /**
2171
+ * The app's module sources, staged against the runtime module (`import BakeNativeKit`), with the
2172
+ * contracts generated from its specs (`specs`: parsed native/<name>/<Name>.native.ts).
2173
+ */
2174
+ function stageModuleSources(modulesDir, dir, specs = []) {
2175
+ if (!modulesDir || !existsSync(modulesDir)) return {
2176
+ swift: [],
2177
+ classes: []
2178
+ };
2179
+ mkdirSync(dir, { recursive: true });
2180
+ const swift = [];
2181
+ const classes = [];
2182
+ for (const spec of specs) {
2183
+ const staged = join(dir, `${spec.name}Spec.swift`);
2184
+ writeFileSync(staged, swiftSpec(spec, {
2185
+ source: `${spec.name}.native.ts`,
2186
+ imports: ["BakeNativeKit"]
2187
+ }));
2188
+ swift.push(staged);
2189
+ }
2190
+ const contracts = specs.map((s) => `${s.name}Spec`).join("|") || "(?!)";
2191
+ for (const file of listFiles(modulesDir, ".swift")) {
2192
+ if (/Tests?\.swift$/.test(file)) continue;
2193
+ const text = readFileSync(file, "utf8");
2194
+ const conforms = new RegExp(`^\\s*(?:public\\s+)?(?:final\\s+)?class\\s+(\\w+)\\s*:\\s*(?:[\\w.]+\\s*,\\s*)*(?:BakeNativeModule|${contracts})\\b`, "gm");
2195
+ for (const m of text.matchAll(conforms)) classes.push(m[1]);
2196
+ const staged = join(dir, basename(file));
2197
+ writeFileSync(staged, text.replace(/^([ \t]*)import[ \t]+(BakeNativeCore|BakeNativeApple)[ \t]*$/gm, "$1import BakeNativeKit"));
2198
+ swift.push(staged);
2199
+ }
2200
+ return {
2201
+ swift,
2202
+ classes: classes.sort()
2203
+ };
2204
+ }
2205
+ /**
2206
+ * `bake package`: <Product>.xcframework, a STATIC framework per slice with the app's own native
2207
+ * modules + the generated entry point, compiled against (not containing) the runtime, and its
2208
+ * resources in `BakeNativeApp/`: the bundle files, `assets/`, BakeNativePackage.json (`manifest`).
2209
+ */
2210
+ async function buildPackageXCFramework({ product, target, bundleDir, runtime, manifest, modulesDir, specs = [], assetsDir, work, outDir, version, modules = [] }) {
2211
+ if (target !== "ios") throw new Error(`packages for ${target} are not built yet`);
2212
+ rmSync(work, {
2213
+ recursive: true,
2214
+ force: true
2215
+ });
2216
+ const resources = join(work, "BakeNativeApp");
2217
+ mkdirSync(resources, { recursive: true });
2218
+ copyBundleFiles(bundleDir, resources);
2219
+ if (!existsSync(join(resources, "app.hbc"))) throw new Error(`${bundleDir}/app.hbc is missing (hermesc did not run?)`);
2220
+ if (assetsDir) cpSync(assetsDir, join(resources, "assets"), { recursive: true });
2221
+ if (existsSync(join(bundleDir, "assets"))) cpSync(join(bundleDir, "assets"), join(resources, "assets"), { recursive: true });
2222
+ if (existsSync(join(bundleDir, "fonts"))) cpSync(join(bundleDir, "fonts"), join(resources, "fonts"), { recursive: true });
2223
+ writeFileSync(join(resources, "BakeNativePackage.json"), JSON.stringify(manifest, null, 2) + "\n");
2224
+ const own = stageModuleSources(modulesDir, join(work, "modules"), specs);
2225
+ const firstParty = firstPartySources(target, modules);
2226
+ const entry = join(work, `${product}.swift`);
2227
+ writeFileSync(entry, packageEntrySwift(product, [...own.classes, ...firstParty.classes]));
2228
+ return createXCFramework(await Promise.all(TARGET_SLICES[target].map(async (slice) => (await buildFramework({
2229
+ module: product,
2230
+ slice,
2231
+ swift: [
2232
+ entry,
2233
+ ...own.swift,
2234
+ ...firstParty.swift
2235
+ ],
2236
+ isStatic: true,
2237
+ frameworkPaths: [xcframeworkSlice(runtime, slice)],
2238
+ frameworks: [RUNTIME_MODULE[target]],
2239
+ resources,
2240
+ resourcesName: "BakeNativeApp",
2241
+ bundleId: manifest.id,
2242
+ version,
2243
+ work: join(work, "build", slice),
2244
+ out: join(work, "frameworks", slice)
2245
+ })).framework)), join(outDir, `${product}.xcframework`));
2246
+ }
2247
+ // src/third-party.ts
2248
+ const THIRD_PARTY_PLATFORMS = ["android", "ios"];
2249
+ /**
2250
+ * What the shared runtime (bakenative-runtime.aar) fixes for every package on Android. The NDK range
2251
+ * is the series the runtime's Hermes is built with (tools/build-hermes/android.sh): the runtime
2252
+ * links libc++ statically, so a package's libc++_shared.so only meets the package's own .so files,
2253
+ * but every package in one host gets the same single libc++_shared.so, so all of them must come
2254
+ * from one NDK series.
2255
+ */
2256
+ const ANDROID_RUNTIME = {
2257
+ ndk: ">=28.0.0 <29.0.0",
2258
+ ndkPinned: "28.2.13676358",
2259
+ minSdk: 29,
2260
+ abis: ["arm64-v8a"],
2261
+ javaPackages: ["dev.bakenative"],
2262
+ so: [
2263
+ "libbakenative.so",
2264
+ "libbakehermes.so",
2265
+ "libhermesvm.so"
2266
+ ]
2267
+ };
2268
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._@/-]*$/;
2269
+ const JAVA_PACKAGE = /^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/;
2270
+ const SO_NAME = /^lib[\w.+-]+\.so$/;
2271
+ /** The package's Android identity from `bakenative.package.android`, with defaults from the package. */
2272
+ function androidIdentity(raw, pkg) {
2273
+ const stem = pkg.name.toLowerCase().replace(/[^a-z0-9]/g, "");
2274
+ const identity = {
2275
+ package: raw?.package ?? pkg.id,
2276
+ resourcePrefix: raw?.resourcePrefix ?? `${stem}_`,
2277
+ soPrefix: raw?.soPrefix ?? `lib${stem}`
2278
+ };
2279
+ if (!JAVA_PACKAGE.test(identity.package)) throw new Error(`${pkg.name}: android.package "${identity.package}" is not a Java package name`);
2280
+ if (!/^[a-z][a-z0-9_]*$/.test(identity.resourcePrefix)) throw new Error(`${pkg.name}: android.resourcePrefix "${identity.resourcePrefix}" must be lowercase letters, digits and _`);
2281
+ if (!/^lib[\w+-]+$/.test(identity.soPrefix)) throw new Error(`${pkg.name}: android.soPrefix "${identity.soPrefix}" must start with "lib"`);
2282
+ return identity;
2283
+ }
2284
+ /**
2285
+ * Why a library cannot be isolated on `platform` (default: every platform it is declared for), or
2286
+ * null when it can. Android code (Java/Kotlin, .so) can always be renamed.
2287
+ */
2288
+ function isolatable(decl, platform) {
2289
+ if ((platform ?? "ios") === "ios" && decl.platforms.includes("ios") && decl.ios && decl.ios.language !== "c") return decl.ios.language === "swift" ? `Swift modules (${decl.ios.modules.join(", ")}) cannot be renamed: a process has one module of each name` : `ObjC classes (${decl.ios.classes.join(", ")}*) cannot be renamed: a process has one class of each name`;
2290
+ return null;
2291
+ }
2292
+ function strings(value, where, errors) {
2293
+ if (value === void 0) return [];
2294
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
2295
+ errors.push(`${where} must be a list of strings`);
2296
+ return [];
2297
+ }
2298
+ return value;
2299
+ }
2300
+ /**
2301
+ * `bakenative.package.thirdParty` read and checked. Throws one error listing every problem: a
2302
+ * declaration the checks cannot use would let undeclared code through.
2303
+ */
2304
+ function thirdPartyDeclarations(raw, pkgName) {
2305
+ if (raw === void 0) return [];
2306
+ const errors = [];
2307
+ if (!Array.isArray(raw)) throw new Error(`${pkgName}: thirdParty must be a list`);
2308
+ const out = [];
2309
+ const seen = /* @__PURE__ */ new Map();
2310
+ raw.forEach((entry, i) => {
2311
+ const at = `thirdParty[${i}]${typeof entry?.name === "string" ? ` (${entry.name})` : ""}`;
2312
+ if (!entry || typeof entry !== "object") return errors.push(`${at} must be an object`);
2313
+ const name = entry.name;
2314
+ if (typeof name !== "string" || !NAME.test(name)) errors.push(`${at}: name is required (letters, digits, . _ - / @)`);
2315
+ const version = entry.version;
2316
+ if (typeof version !== "string") errors.push(`${at}: version (a range such as ">=1.2.0 <2.0.0") is required`);
2317
+ else try {
2318
+ parseRange(version);
2319
+ } catch (e) {
2320
+ errors.push(`${at}: ${e.message}`);
2321
+ }
2322
+ const mode = entry.mode ?? "shared";
2323
+ if (mode !== "shared" && mode !== "isolated") errors.push(`${at}: mode must be "shared" or "isolated", not "${mode}"`);
2324
+ let android;
2325
+ if (entry.android !== void 0) {
2326
+ const packages = strings(entry.android.packages, `${at}: android.packages`, errors);
2327
+ const so = strings(entry.android.so, `${at}: android.so`, errors);
2328
+ for (const p of packages) if (!JAVA_PACKAGE.test(p)) errors.push(`${at}: android.packages: "${p}" is not a Java package`);
2329
+ for (const s of so) if (!SO_NAME.test(s)) errors.push(`${at}: android.so: "${s}" is not a lib<name>.so file name`);
2330
+ if (!packages.length && !so.length) errors.push(`${at}: android needs packages (Java/Kotlin) or so (.so files): the check recognizes the library by them`);
2331
+ android = {
2332
+ packages,
2333
+ so,
2334
+ ...typeof entry.android.maven === "string" ? { maven: entry.android.maven } : {}
2335
+ };
2336
+ }
2337
+ let ios;
2338
+ if (entry.ios !== void 0) {
2339
+ const language = entry.ios.language;
2340
+ if (![
2341
+ "swift",
2342
+ "objc",
2343
+ "c"
2344
+ ].includes(language)) errors.push(`${at}: ios.language must be "swift", "objc" or "c"`);
2345
+ const modules = strings(entry.ios.modules, `${at}: ios.modules`, errors);
2346
+ const classes = strings(entry.ios.classes, `${at}: ios.classes`, errors);
2347
+ const symbols = strings(entry.ios.symbols, `${at}: ios.symbols`, errors);
2348
+ if (language === "swift" && !modules.length) errors.push(`${at}: ios.modules (the Swift module names) is required for a Swift library`);
2349
+ if (language === "objc" && !classes.length) errors.push(`${at}: ios.classes (the ObjC class prefixes) is required for an ObjC library`);
2350
+ if (language === "c" && !symbols.length) errors.push(`${at}: ios.symbols (the C symbol prefixes) is required for a C library`);
2351
+ ios = {
2352
+ language,
2353
+ modules,
2354
+ classes,
2355
+ symbols
2356
+ };
2357
+ }
2358
+ const platforms = entry.platforms === void 0 ? THIRD_PARTY_PLATFORMS.filter((p) => entry[p] !== void 0) : strings(entry.platforms, `${at}: platforms`, errors).filter((p) => {
2359
+ if (THIRD_PARTY_PLATFORMS.includes(p)) return true;
2360
+ errors.push(`${at}: platforms: unknown platform "${p}" (android, ios)`);
2361
+ return false;
2362
+ });
2363
+ if (!platforms.length) errors.push(`${at}: no platform: add platforms and an android / ios block`);
2364
+ for (const p of platforms) if ((p === "android" ? android : ios) === void 0) errors.push(`${at}: platform ${p} needs an "${p}" block naming the library's code there`);
2365
+ if (typeof name === "string") {
2366
+ const taken = seen.get(name) ?? /* @__PURE__ */ new Set();
2367
+ for (const p of platforms) if (taken.has(p)) errors.push(`${at}: ${name} is declared twice for ${p}`);
2368
+ else taken.add(p);
2369
+ seen.set(name, taken);
2370
+ }
2371
+ const decl = {
2372
+ name,
2373
+ version,
2374
+ mode,
2375
+ platforms,
2376
+ android,
2377
+ ios
2378
+ };
2379
+ if (mode === "isolated") {
2380
+ const why = isolatable(decl);
2381
+ if (why) errors.push(`${at}: cannot be "isolated": ${why}. Use "shared" (the host links one copy)`);
2382
+ }
2383
+ out.push(decl);
2384
+ });
2385
+ if (errors.length) throw new Error(`${pkgName}: package.json "bakenative.package.thirdParty":\n ${errors.join("\n ")}`);
2386
+ return out;
2387
+ }
2388
+ function cmp(a, b) {
2389
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
2390
+ return 0;
2391
+ }
2392
+ /** "6", "6.4", "6.4.1", "6.4.x", "6.4.1-beta" (pre-release tags are ignored). */
2393
+ function partial(text) {
2394
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:[-+][\w.-]*)?$/.exec(text);
2395
+ if (!m) throw new Error(`"${text}" is not a version`);
2396
+ const parts = [
2397
+ m[1],
2398
+ m[2],
2399
+ m[3]
2400
+ ];
2401
+ let given = 0;
2402
+ let wild = false;
2403
+ const v = [];
2404
+ for (const p of parts) {
2405
+ wild ||= p === void 0 || /[xX*]/.test(p);
2406
+ v.push(wild ? 0 : Number(p));
2407
+ if (!wild) given++;
2408
+ }
2409
+ return {
2410
+ v,
2411
+ given
2412
+ };
2413
+ }
2414
+ function bump(v, at) {
2415
+ const out = [...v];
2416
+ out[at]++;
2417
+ for (let i = at + 1; i < 3; i++) out[i] = 0;
2418
+ return out;
2419
+ }
2420
+ function comparator(token) {
2421
+ const m = /^(\^|~|>=|<=|>|<|=)?(.+)$/.exec(token);
2422
+ const op = m[1] ?? "";
2423
+ const { v, given } = partial(m[2]);
2424
+ switch (op) {
2425
+ case ">=": return {
2426
+ lo: {
2427
+ v,
2428
+ incl: true
2429
+ },
2430
+ hi: null
2431
+ };
2432
+ case ">": return given < 3 ? {
2433
+ lo: {
2434
+ v: bump(v, Math.max(given - 1, 0)),
2435
+ incl: true
2436
+ },
2437
+ hi: null
2438
+ } : {
2439
+ lo: {
2440
+ v,
2441
+ incl: false
2442
+ },
2443
+ hi: null
2444
+ };
2445
+ case "<=": return given < 3 ? {
2446
+ lo: null,
2447
+ hi: {
2448
+ v: bump(v, Math.max(given - 1, 0)),
2449
+ incl: false
2450
+ }
2451
+ } : {
2452
+ lo: null,
2453
+ hi: {
2454
+ v,
2455
+ incl: true
2456
+ }
2457
+ };
2458
+ case "<": return {
2459
+ lo: null,
2460
+ hi: {
2461
+ v,
2462
+ incl: false
2463
+ }
2464
+ };
2465
+ case "^": {
2466
+ const at = v[0] > 0 || given === 1 ? 0 : v[1] > 0 || given === 2 ? 1 : 2;
2467
+ return {
2468
+ lo: {
2469
+ v,
2470
+ incl: true
2471
+ },
2472
+ hi: {
2473
+ v: bump(v, at),
2474
+ incl: false
2475
+ }
2476
+ };
2477
+ }
2478
+ case "~": return {
2479
+ lo: {
2480
+ v,
2481
+ incl: true
2482
+ },
2483
+ hi: {
2484
+ v: bump(v, given >= 2 ? 1 : 0),
2485
+ incl: false
2486
+ }
2487
+ };
2488
+ default:
2489
+ if (given === 0) return {
2490
+ lo: null,
2491
+ hi: null
2492
+ };
2493
+ if (given < 3) return {
2494
+ lo: {
2495
+ v,
2496
+ incl: true
2497
+ },
2498
+ hi: {
2499
+ v: bump(v, given - 1),
2500
+ incl: false
2501
+ }
2502
+ };
2503
+ return {
2504
+ lo: {
2505
+ v,
2506
+ incl: true
2507
+ },
2508
+ hi: {
2509
+ v,
2510
+ incl: true
2511
+ }
2512
+ };
2513
+ }
2514
+ }
2515
+ function maxLo(a, b) {
2516
+ if (!a) return b;
2517
+ if (!b) return a;
2518
+ const c = cmp(a.v, b.v);
2519
+ return c > 0 || c === 0 && !a.incl ? a : b;
2520
+ }
2521
+ function minHi(a, b) {
2522
+ if (!a) return b;
2523
+ if (!b) return a;
2524
+ const c = cmp(a.v, b.v);
2525
+ return c < 0 || c === 0 && !a.incl ? a : b;
2526
+ }
2527
+ function nonEmpty(i) {
2528
+ if (!i.lo || !i.hi) return true;
2529
+ const c = cmp(i.lo.v, i.hi.v);
2530
+ return c < 0 || c === 0 && i.lo.incl && i.hi.incl;
2531
+ }
2532
+ /** A range: `||`-separated sets of space-separated comparators (>=, >, <=, <, =, ^, ~, x-ranges). */
2533
+ function parseRange(range) {
2534
+ const sets = String(range).split("||").map((s) => s.trim());
2535
+ if (sets.some((s) => !s)) throw new Error(`version range "${range}" is empty`);
2536
+ return sets.map((set) => {
2537
+ const tokens = set.replace(/(>=|<=|>|<|=|\^|~)\s+/g, "$1").split(/\s+/);
2538
+ let acc = {
2539
+ lo: null,
2540
+ hi: null
2541
+ };
2542
+ for (const token of tokens) {
2543
+ let one;
2544
+ try {
2545
+ one = comparator(token);
2546
+ } catch {
2547
+ throw new Error(`version range "${range}": cannot read "${token}" (use >=1.2.0 <2.0.0, ^1.2.0 or 1.2.3)`);
2548
+ }
2549
+ acc = {
2550
+ lo: maxLo(acc.lo, one.lo),
2551
+ hi: minHi(acc.hi, one.hi)
2552
+ };
2553
+ }
2554
+ return acc;
2555
+ }).filter(nonEmpty);
2556
+ }
2557
+ /** The versions every range accepts, or [] when they do not overlap. */
2558
+ function intersectRanges(ranges) {
2559
+ let acc = [{
2560
+ lo: null,
2561
+ hi: null
2562
+ }];
2563
+ for (const r of ranges) {
2564
+ const next = [];
2565
+ for (const a of acc) for (const b of r) {
2566
+ const i = {
2567
+ lo: maxLo(a.lo, b.lo),
2568
+ hi: minHi(a.hi, b.hi)
2569
+ };
2570
+ if (nonEmpty(i)) next.push(i);
2571
+ }
2572
+ acc = next;
2573
+ }
2574
+ return acc;
2575
+ }
2576
+ const fmt = (v) => v.join(".");
2577
+ function formatRange(intervals) {
2578
+ if (!intervals.length) return "(none)";
2579
+ return intervals.map((i) => {
2580
+ if (i.lo && i.hi && i.lo.incl && i.hi.incl && cmp(i.lo.v, i.hi.v) === 0) return fmt(i.lo.v);
2581
+ const parts = [];
2582
+ if (i.lo) parts.push(`${i.lo.incl ? ">=" : ">"}${fmt(i.lo.v)}`);
2583
+ if (i.hi) parts.push(`${i.hi.incl ? "<=" : "<"}${fmt(i.hi.v)}`);
2584
+ return parts.join(" ") || "*";
2585
+ }).join(" || ");
2586
+ }
2587
+ function rangeAccepts(range, version) {
2588
+ const { v } = partial(version.trim());
2589
+ return (typeof range === "string" ? parseRange(range) : range).some((i) => (!i.lo || cmp(v, i.lo.v) > 0 || cmp(v, i.lo.v) === 0 && i.lo.incl) && (!i.hi || cmp(v, i.hi.v) < 0 || cmp(v, i.hi.v) === 0 && i.hi.incl));
2590
+ }
2591
+ const verb = (names, one, many) => `${names.join(", ")} ${names.length === 1 ? one : many}`;
2592
+ /**
2593
+ * The host integration check: every package's thirdParty declarations together. For each library
2594
+ * and platform, the `shared` ranges must overlap (the host links one version inside all of them);
2595
+ * when they do not, the message says which packages could switch to `isolated` instead, or why
2596
+ * none can (Swift / ObjC). `provide` pins versions the host already links.
2597
+ */
2598
+ function integrateThirdParty(packages, options = {}) {
2599
+ const errors = [];
2600
+ const notes = [];
2601
+ const libraries = [];
2602
+ const provide = options.provide ?? {};
2603
+ const platforms = options.platforms ?? [...THIRD_PARTY_PLATFORMS];
2604
+ const byId = /* @__PURE__ */ new Map();
2605
+ for (const p of packages) {
2606
+ const other = byId.get(p.id);
2607
+ if (other) errors.push(`package id ${p.id} is used by both ${other} and ${p.source}: every package needs its own id`);
2608
+ else byId.set(p.id, p.source);
2609
+ }
2610
+ if (platforms.includes("android")) {
2611
+ const androidPkgs = packages.filter((p) => p.android);
2612
+ for (let i = 0; i < androidPkgs.length; i++) for (let j = i + 1; j < androidPkgs.length; j++) {
2613
+ const a = androidPkgs[i], b = androidPkgs[j];
2614
+ const pa = a.android, pb = b.android;
2615
+ if (pa.package === pb.package || pa.package.startsWith(pb.package + ".") || pb.package.startsWith(pa.package + ".")) errors.push(`${a.name} (${pa.package}) and ${b.name} (${pb.package}): Java packages overlap; their classes and R classes would collide. Give each package its own android.package`);
2616
+ if (pa.resourcePrefix === pb.resourcePrefix) errors.push(`${a.name} and ${b.name} share the resource prefix "${pa.resourcePrefix}": a resource both define is silently overridden in the host. Set android.resourcePrefix per package`);
2617
+ if (pa.soPrefix === pb.soPrefix) errors.push(`${a.name} and ${b.name} share the .so prefix "${pa.soPrefix}": set android.soPrefix per package`);
2618
+ if (a.aar && b.aar) {
2619
+ for (const so of a.aar.so) if (so !== "libc++_shared.so" && b.aar.so.includes(so)) errors.push(`${a.name} and ${b.name} both contain ${so}: the host APK has one lib/<abi>/${so}`);
2620
+ for (const auth of a.aar.authorities) if (b.aar.authorities.includes(auth)) errors.push(`${a.name} and ${b.name} both declare provider authority ${auth}: the host fails to install`);
2621
+ for (const km of a.aar.kotlinModules) if (b.aar.kotlinModules.includes(km)) errors.push(`${a.name} and ${b.name} both contain META-INF/${km}: the host build fails on the duplicate file`);
2622
+ if (a.aar.namespace && a.aar.namespace === b.aar.namespace) errors.push(`${a.name} and ${b.name} have the manifest namespace ${a.aar.namespace}: their R classes collide`);
2623
+ }
2624
+ }
2625
+ }
2626
+ const claims = /* @__PURE__ */ new Map();
2627
+ for (const p of packages) for (const d of p.thirdParty) for (const key of [
2628
+ ...(d.android?.packages ?? []).map((x) => `android package ${x}`),
2629
+ ...(d.android?.so ?? []).map((x) => `android ${x}`),
2630
+ ...(d.ios?.modules ?? []).map((x) => `ios module ${x}`)
2631
+ ]) {
2632
+ const prev = claims.get(key);
2633
+ if (prev && prev !== d.name) errors.push(`${key} is declared as library "${prev}" and as "${d.name}" (${p.source}): use one name for one library`);
2634
+ else claims.set(key, d.name);
2635
+ }
2636
+ for (const platform of platforms) {
2637
+ const names = /* @__PURE__ */ new Set();
2638
+ for (const p of packages) for (const d of p.thirdParty) if (d.platforms.includes(platform)) names.add(d.name);
2639
+ for (const name of [...names].sort()) {
2640
+ const users = packages.flatMap((p) => p.thirdParty.filter((d) => d.name === name && d.platforms.includes(platform)).map((d) => ({
2641
+ p,
2642
+ d
2643
+ })));
2644
+ const shared = users.filter((u) => u.d.mode === "shared");
2645
+ const isolated = users.filter((u) => u.d.mode === "isolated");
2646
+ const lib = {
2647
+ name,
2648
+ platform,
2649
+ shared: shared.map((u) => ({
2650
+ package: u.p.name,
2651
+ version: u.d.version
2652
+ })),
2653
+ isolated: isolated.map((u) => ({
2654
+ package: u.p.name,
2655
+ version: u.d.version
2656
+ })),
2657
+ range: null,
2658
+ provided: provide[name] ?? null
2659
+ };
2660
+ libraries.push(lib);
2661
+ if (!shared.length) {
2662
+ notes.push(`${platform} ${name}: no shared users; ${verb(isolated.map((u) => u.p.name), "carries", "carry")} its own renamed copy`);
2663
+ continue;
2664
+ }
2665
+ const together = intersectRanges(shared.map((u) => parseRange(u.d.version)));
2666
+ if (!together.length) {
2667
+ const lines = shared.map((u) => ` ${u.p.name}: ${u.d.version}`).join("\n");
2668
+ const movable = shared.filter((u) => !isolatable(u.d, platform));
2669
+ const blocked = shared.filter((u) => isolatable(u.d, platform));
2670
+ const split = movable.filter((u) => isolatable(u.d)).map((u) => u.p.name);
2671
+ const splitHint = split.length ? ` (${verb(split, "declares", "declare")} it for more platforms: split the entry and set "platforms": ["${platform}"] on the isolated one)` : "";
2672
+ let advice;
2673
+ if (!blocked.length) advice = `Align the ranges, or make all but one of them "mode": "isolated" (the package carries a renamed copy: relocated Java/Kotlin packages, renamed .so, prefixed C symbols)${splitHint}`;
2674
+ else if (movable.length) advice = `Align the ranges, or make ${movable.map((u) => u.p.name).join(", ")} "isolated"${splitHint}. ${blocked.map((u) => `${u.p.name} cannot be isolated: ${isolatable(u.d, platform)}`).join("; ")}`;
2675
+ else advice = `Align the ranges: ${isolatable(blocked[0].d, platform)}, so "isolated" is not possible here`;
2676
+ errors.push(`${platform} ${name}: the shared version ranges do not overlap, so the host cannot link one copy:\n${lines}\n ${advice}`);
2677
+ continue;
2678
+ }
2679
+ lib.range = formatRange(together);
2680
+ if (lib.provided && !rangeAccepts(together, lib.provided)) errors.push(`${platform} ${name}: the host provides ${lib.provided}, outside ${lib.range} (what ${verb(shared.map((u) => u.p.name), "accepts", "accept")})`);
2681
+ if (isolated.length) notes.push(`${platform} ${name}: ${verb(isolated.map((u) => u.p.name), "carries", "carry")} its own renamed copy next to the host's`);
2682
+ }
2683
+ }
2684
+ return {
2685
+ ok: errors.length === 0,
2686
+ libraries,
2687
+ errors,
2688
+ notes
2689
+ };
2690
+ }
2691
+ // src/package.ts
2692
+ /** The runtime version: this toolchain's version (BakeNativeRuntime.version in native/apple). */
2693
+ const RUNTIME_VERSION = readPackageJson("package.json").version;
2694
+ /**
2695
+ * The app's package declaration, `package.json` "bakenative": { "package": { ... } }:
2696
+ * name Swift product (default: from the package name) id package id (default dev.bakenative.app.<name>)
2697
+ * modules directory of the app's own native modules' Swift implementations
2698
+ * schema signatures of modules without a spec (native-modules.json a host wrote); the
2699
+ * specs in native/<name>/<Name>.native.ts give the rest
2700
+ * requires host capabilities the app may use (native modules the host injects)
2701
+ * runtime the runtime range it runs on (default: the series it is built with); when
2702
+ * declared, its OTA bundles require it too
2703
+ * nativeBuild an integer (default 0) to raise when native behavior changes behind unchanged
2704
+ * signatures: bundles built from then on refuse packages below it
2705
+ * thirdParty third-party libraries it uses, each "shared" or "isolated" (src/third-party.ts)
2706
+ * android { package, resourcePrefix, soPrefix }: where its own Android code lives
2707
+ */
2708
+ function packageConfig(root, unavailable = /* @__PURE__ */ new Set()) {
2709
+ const file = join(root, "package.json");
2710
+ if (!existsSync(file)) return null;
2711
+ const json = JSON.parse(readFileSync(file, "utf8"));
2712
+ const p = json.bakenative?.package;
2713
+ if (!p) return null;
2714
+ const name = productName(p.name ?? json.name?.split("/").pop() ?? basename(root));
2715
+ const schemaPath = resolve(root, p.schema ?? "native-modules.json");
2716
+ const specs = [...appModuleSpecs(root).values()].filter((spec) => !unavailable.has(spec.name));
2717
+ const written = existsSync(schemaPath) ? JSON.parse(readFileSync(schemaPath, "utf8")) : {
2718
+ version: 1,
2719
+ modules: []
2720
+ };
2721
+ const fromSpecs = specsSchema(specs);
2722
+ const schema = {
2723
+ ...written,
2724
+ modules: [...fromSpecs.modules, ...(written.modules ?? []).filter((m) => !unavailable.has(m.name) && !specs.some((s) => s.name === m.name))].sort((a, b) => a.name < b.name ? -1 : 1)
2725
+ };
2726
+ const runtime = p.runtime ?? defaultRuntimeRange(RUNTIME_VERSION);
2727
+ if (!satisfies(RUNTIME_VERSION, runtime)) throw new Error(`${name}: runtime range "${runtime}" excludes this toolchain's runtime ${RUNTIME_VERSION}`);
2728
+ const nativeBuild = p.nativeBuild ?? 0;
2729
+ if (!Number.isInteger(nativeBuild) || nativeBuild < 0) throw new Error(`${name}: "nativeBuild" must be a non-negative integer, not ${JSON.stringify(nativeBuild)}`);
2730
+ const id = p.id ?? `dev.bakenative.app.${name}`;
2731
+ return {
2732
+ name,
2733
+ id,
2734
+ version: p.version ?? json.version ?? "0.0.0",
2735
+ modulesDir: p.modules ? resolve(root, p.modules) : null,
2736
+ schemaPath,
2737
+ schema,
2738
+ specs,
2739
+ requires: p.requires ?? [],
2740
+ runtime,
2741
+ runtimeDeclared: p.runtime !== void 0,
2742
+ nativeBuild,
2743
+ thirdParty: thirdPartyDeclarations(p.thirdParty, name),
2744
+ android: androidIdentity(p.android, {
2745
+ name,
2746
+ id
2747
+ })
2748
+ };
2749
+ }
2750
+ /**
2751
+ * The package half of the provides (what `bake_bundle_check` takes on device): the package id,
2752
+ * its native build number and the signature of every member of its own native modules.
2753
+ */
2754
+ function packageProvides(pkg) {
2755
+ return {
2756
+ package: pkg.id,
2757
+ nativeBuild: pkg.nativeBuild,
2758
+ native: memberSignatures(pkg.schema)
2759
+ };
2760
+ }
2761
+ /** BakeNativePackage.json: what a package provides (the device and `bake release check` read it). */
2762
+ function packageManifest(pkg, bundleManifest) {
2763
+ return {
2764
+ format: 2,
2765
+ name: pkg.name,
2766
+ id: pkg.id,
2767
+ version: pkg.version,
2768
+ runtime: {
2769
+ built: RUNTIME_VERSION,
2770
+ range: pkg.runtime
2771
+ },
2772
+ requires: pkg.requires,
2773
+ provides: {
2774
+ ...packageProvides(pkg),
2775
+ hermesBytecode: bundleManifest.hermesBytecode,
2776
+ modules: [...bundleManifest.requires?.modules ?? []].sort(),
2777
+ views: Object.fromEntries(Object.entries(bundleManifest.requires?.views ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)),
2778
+ runtime: RUNTIME_PROVIDES
2779
+ },
2780
+ thirdParty: pkg.thirdParty,
2781
+ android: pkg.android
2782
+ };
2783
+ }
2784
+ export { bundleComponents as $, writeRegistration as A, compatIssues as B, bundleAppModules as C, registrationFiles as D, checkoutRelative as E, nativeTools as F, toolchainFor as G, hermescPackage as H, repo as I, execToolBuffer as J, ToolError as K, toolProcessEnv as L, NATIVE_RENDERER as M, defaultHermesc as N, targetFiles as O, nativeTool as P, appEntries as Q, COMPAT as R, appViewUnit as S, bundleViews as T, packagedTool as U, hermescBytecode as V, toolchainDir as W, NOTICES as X, toolTimeout as Y, NOTICES_JSON as Z, run as _, androidIdentity as a, FAMILY as b, intersectRanges as c, thirdPartyDeclarations as d, mergeComponents as et, TARGET_SLICES as f, productName as g, packageSwift as h, ANDROID_RUNTIME as i, implementationIssues as j, targetNativeDeps as k, parseRange as l, buildPackageXCFramework as m, packageConfig as n, readNoticesJson as nt, formatRange as o, buildAppXCFramework as p, execTool as q, packageManifest as r, writeOutputNotices as rt, integrateThirdParty as s, RUNTIME_VERSION as t, placedAt as tt, rangeAccepts as u, runtimeNoticeFiles as v, bundleModules as w, appModuleSources as x, zipForSwiftPM as y, assertCompatible as z };