@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,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1 @@
1
+ export { dir, locale, setLocale } from './locale.js';
@@ -0,0 +1 @@
1
+ export { dir, locale, setLocale } from './locale.js';
package/locale.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The tag this screen renders in, from the app's `locales` in `bake.config.ts`. A saved app
3
+ * choice takes precedence over the user's preferred languages. If none matches, the first
4
+ * declared locale is used. The tag stays fixed for the life of the screen and matches the
5
+ * locale used to bake its first screen. Use it to initialize a translation table synchronously.
6
+ */
7
+ export function locale(): string;
8
+
9
+ /** The document's writing direction, `'rtl'` or `'ltr'`. It defaults to the direction of {@link locale}. */
10
+ export function dir(): 'ltr' | 'rtl';
11
+
12
+ /** The tag of `supported` a user with `preferred` languages (most preferred first) sees. */
13
+ export function resolveLocale(preferred: readonly string[], supported: readonly string[]): string | null;
14
+
15
+ /** Whether a BCP 47 tag is written right to left. */
16
+ export function isRtl(tag: string): boolean;
17
+
18
+ /**
19
+ * The app's own language choice: one of its `locales` (bake.config.ts), or `null` / `''` to follow the
20
+ * device again. Saved by the host (on the web, in localStorage) and resolved before the device's
21
+ * languages from the next launch on, whose first screen is the one baked for it. The screens of
22
+ * this launch keep their locale. Supported on web, iOS, macOS, Android, and Windows. Windows
23
+ * supports left-to-right locales. Throws a RangeError for a tag outside the app's locales.
24
+ */
25
+ export function setLocale(tag: string | null): void;
26
+
27
+ /** {@link resolveLocale} with the app's saved choice ('' none) first. */
28
+ export function resolveWithSaved(saved: string, preferred: readonly string[], supported: readonly string[]): string | null;
package/locale.js ADDED
@@ -0,0 +1,124 @@
1
+ // The app locale: the one tag of the app's `locales` (bake.config.ts) a screen renders in, and its
2
+ // writing direction. Native hosts resolve it in the core (bake-core locale.rs) once per root,
3
+ // before the first render, and hand it to the bundle as `globalThis.__bakeAppLocale`; the web
4
+ // resolves it here from `navigator.languages`. tests/locale/cases.json keeps both equal.
5
+ //
6
+ // import { locale, dir, setLocale } from '@bake-native/core';
7
+ // const t = i18n(locale()); // a synchronous translation table in the bundle
8
+ // setLocale('ko'); // the app's own choice: from the next launch on
9
+ //
10
+ // Both are fixed for the life of the screen, and the build bakes a first screen for each locale
11
+ // with the same values. A native process reads the saved choice and the device's languages once,
12
+ // so every screen of one launch opens in the same locale as the first screen picked for it.
13
+
14
+ /** `zh-Hant-TW` → { language, script, region } (`_` accepted for `-`), or null. */
15
+ function parse(tag) {
16
+ const parts = String(tag).split(/[-_]/).filter(Boolean);
17
+ const language = parts.shift();
18
+ if (!language || !/^[A-Za-z]{2,8}$/.test(language)) return null;
19
+ const t = { language: language.toLowerCase(), script: null, region: null };
20
+ for (const p of parts) {
21
+ if (!t.script && !t.region && /^[A-Za-z]{4}$/.test(p)) t.script = p[0].toUpperCase() + p.slice(1).toLowerCase();
22
+ else if (!t.region && (/^[A-Za-z]{2}$/.test(p) || /^\d{3}$/.test(p))) t.region = p.toUpperCase();
23
+ else break;
24
+ }
25
+ return t;
26
+ }
27
+
28
+ /** The script, or the language's default where it has several (Chinese by region, Serbian). */
29
+ function scriptOf(t) {
30
+ if (t.script) return t.script;
31
+ if (t.language === 'zh') return ['TW', 'HK', 'MO'].includes(t.region) ? 'Hant' : 'Hans';
32
+ if (t.language === 'sr') return 'Cyrl';
33
+ return null;
34
+ }
35
+
36
+ const same = (a, b) => a && b && a.language === b.language && a.script === b.script && a.region === b.region;
37
+
38
+ /** The tag of `supported` a user with `preferred` languages sees (bake-core `locale::resolve`). */
39
+ export function resolveLocale(preferred, supported) {
40
+ const tags = supported.map(parse);
41
+ for (const p of preferred) {
42
+ const want = parse(p);
43
+ if (!want) continue;
44
+ const exact = tags.findIndex((t) => same(t, want));
45
+ if (exact >= 0) return supported[exact];
46
+ const candidates = tags.flatMap((t, i) => (t && t.language === want.language && scriptOf(t) === scriptOf(want) ? [i] : []));
47
+ const pick = candidates.find((i) => !tags[i].region) ?? candidates[0];
48
+ if (pick !== undefined) return supported[pick];
49
+ }
50
+ return supported.length ? supported[0] : null;
51
+ }
52
+
53
+ /** resolveLocale with the app's own saved choice (setLocale; '' none) first (bake-core resolve_with_saved). */
54
+ export function resolveWithSaved(saved, preferred, supported) {
55
+ return resolveLocale(saved ? [saved, ...preferred] : preferred, supported);
56
+ }
57
+
58
+ const RTL_SCRIPTS = new Set(['Arab', 'Hebr', 'Thaa', 'Syrc', 'Nkoo', 'Adlm', 'Rohg', 'Mand', 'Samr']);
59
+ const RTL_LANGUAGES = new Set(['ar', 'he', 'iw', 'fa', 'ur', 'ps', 'sd', 'ug', 'ckb', 'yi', 'ji', 'dv', 'syr', 'arc', 'nqo', 'mzn', 'glk', 'lrc']);
60
+
61
+ /** Whether `tag` is written right to left (bake-core `locale::is_rtl`). */
62
+ export function isRtl(tag) {
63
+ const t = parse(tag);
64
+ if (!t) return false;
65
+ return t.script ? RTL_SCRIPTS.has(t.script) : RTL_LANGUAGES.has(t.language);
66
+ }
67
+
68
+ /** The app's `locales` (bake.config.ts), set by the build; `['en']` without any. */
69
+ const LOCALES = typeof __BAKE_LOCALES__ === 'undefined' ? ['en'] : __BAKE_LOCALES__;
70
+
71
+ let resolved;
72
+
73
+ /** The web's saved choice (setLocale): localStorage, when it can be read. */
74
+ const WEB_KEY = 'bakenative.locale';
75
+ function savedOnWeb() {
76
+ try {
77
+ return globalThis.localStorage?.getItem(WEB_KEY) ?? null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /** The tag this screen renders in: one of the app's `locales`. */
84
+ export function locale() {
85
+ if (resolved) return resolved;
86
+ const g = globalThis;
87
+ const given = g.__bakeAppLocale?.tag;
88
+ if (given) return (resolved = given);
89
+ const os = g.navigator?.languages?.length ? g.navigator.languages : g.navigator?.language ? [g.navigator.language] : [];
90
+ return (resolved = resolveWithSaved(savedOnWeb() ?? '', os, LOCALES));
91
+ }
92
+
93
+ /** `'rtl'` or `'ltr'`: the document's direction, the `dir` of its `<html>` element, which the
94
+ * host (and the bake, per locale) set from `locale()` before the first render; without one,
95
+ * the direction of `locale()`. */
96
+ export function dir() {
97
+ const g = globalThis;
98
+ const html = g.__bakePageHtml ?? g.document?.documentElement;
99
+ const set = html?.getAttribute?.('dir');
100
+ if (set === 'rtl' || set === 'ltr') return set;
101
+ return g.__bakeAppLocale?.dir ?? (isRtl(locale()) ? 'rtl' : 'ltr');
102
+ }
103
+
104
+ /**
105
+ * The app's own language choice: one of its `locales`, or null / '' to follow the device again. Saved
106
+ * (by the host, or in localStorage on the web) and resolved before the device's languages from
107
+ * the next launch on, whose first screen is the one baked for it; the screens of this launch keep
108
+ * their locale (restart the app, or reload the page, to switch).
109
+ */
110
+ export function setLocale(tag) {
111
+ if (tag === '') tag = null;
112
+ if (tag !== null && !LOCALES.includes(tag)) throw new RangeError(`setLocale(${JSON.stringify(tag)}): not one of the app's locales (${LOCALES.join(', ')})`);
113
+ const saveOnHost = globalThis.__bakeSetLocale;
114
+ if (typeof saveOnHost === 'function') {
115
+ saveOnHost(tag ?? '');
116
+ return;
117
+ }
118
+ try {
119
+ if (tag === null) globalThis.localStorage?.removeItem(WEB_KEY);
120
+ else globalThis.localStorage?.setItem(WEB_KEY, tag);
121
+ } catch {
122
+ // Storage blocked: the choice lasts for this page only.
123
+ }
124
+ }
@@ -0,0 +1,87 @@
1
+ import SUPPORT from './native-support.json' with { type: 'json' };
2
+
3
+ export function issue(id, subject, what, entry, why, instead) {
4
+ return { id, subject, message: `${what} is not supported on native targets: ${entry?.why ?? why}. Instead: ${entry?.instead ?? instead} (${id}).` };
5
+ }
6
+
7
+ function elementEntry(tag) {
8
+ for (const [k, v] of Object.entries(SUPPORT.elements.supported)) {
9
+ if (k === tag || (k.endsWith('*') && tag.startsWith(k.slice(0, -1)) && (!v.kinds || v.kinds.includes(tag.slice(k.length - 1))))) return v;
10
+ }
11
+ return null;
12
+ }
13
+
14
+ /** The wildcard entry (`swiftui-*`) whose prefix `tag` has but whose `kinds` list lacks it. */
15
+ function unlistedKind(tag) {
16
+ return Object.entries(SUPPORT.elements.supported).find(([k, v]) => k.endsWith('*') && v.kinds && tag.startsWith(k.slice(0, -1)))?.[1] ?? null;
17
+ }
18
+
19
+ /** Whether checkElement reads the value of attribute `name` on <tag> (a fixed list of values). */
20
+ export function valueChecked(tag, name) {
21
+ const attrs = SUPPORT.attributes;
22
+ return !!(elementEntry(tag)?.values?.[name] ?? attrs.values[name] ?? attrs.valueTargets?.[name]);
23
+ }
24
+
25
+ /** props: [[name, value|null]], handlers: ['onClick'] -> issues ({id, subject, message}). */
26
+ export function checkElement(tag, props, handlers, target) {
27
+ const out = [];
28
+ // A native view (the component `bake native view gen` writes marks <bake-name> with
29
+ // data-bake-view): its props are the spec's; `bake build` checks the view per target (view-<name>).
30
+ if (tag.startsWith('bake-') && props.some(([name]) => name === 'data-bake-view')) return out;
31
+ const entry = elementEntry(tag);
32
+ if (!entry) {
33
+ const unsupported = SUPPORT.elements.unsupported[tag];
34
+ const reason = unsupported ?? unlistedKind(tag)?.unknown;
35
+ out.push(issue(unsupported ? `element-${tag}` : 'element-unknown', tag, `<${tag}>`, reason, 'native has no such element', 'a supported element (see the support list)'));
36
+ return out;
37
+ }
38
+ if (entry.targets && !entry.targets.includes(target)) {
39
+ out.push(issue('element-target', tag, `<${tag}> on ${target}`, null, `it is drawn only on ${entry.targets.join(', ')}`, 'branch on import.meta.env.BAKE_TARGET'));
40
+ }
41
+ const attrs = SUPPORT.attributes;
42
+ const any = entry.attributes === '*';
43
+ const own = Array.isArray(entry.attributes) ? entry.attributes : [];
44
+ for (const [name, value] of props) {
45
+ if (any || /^on[A-Z]/.test(name)) continue;
46
+ const known = attrs.global.includes(name) || own.includes(name) || (entry.svg && attrs.svg.includes(name)) || attrs.prefixes.some((p) => name.startsWith(p));
47
+ if (!known) {
48
+ const unsupported = attrs.unsupported[name];
49
+ const [id, e] = unsupported ? [`attribute-${name}`, unsupported]
50
+ : /^aria-|^aria[A-Z]/.test(name) ? ['attribute-aria', attrs['aria-unsupported']] : ['attribute-unknown', null];
51
+ out.push(issue(id, name, `the attribute \`${name}\` on <${tag}>`, e, 'native ignores it', 'remove it, or a supported attribute'));
52
+ continue;
53
+ }
54
+ const values = entry.values?.[name] ?? attrs.values[name];
55
+ if (values && typeof value === 'string' && !values.includes(value.toLowerCase())) {
56
+ out.push(issue('attribute-value', name, `\`${name}="${value}"\` on <${tag}>`, null, `native handles only ${values.join(', ')}`, 'one of those'));
57
+ continue;
58
+ }
59
+ // A value only some targets handle (`dir="rtl"`).
60
+ const pending = typeof value === 'string' ? attrs.valueTargets?.[name]?.[value.toLowerCase()] : undefined;
61
+ if (pending && !pending.targets.includes(target)) {
62
+ out.push(issue('attribute-value-target', name, `\`${name}="${value}"\` on <${tag}> on ${target}`, pending));
63
+ }
64
+ }
65
+ const ev = SUPPORT.events;
66
+ for (const h of handlers) {
67
+ if (any) continue;
68
+ let supported = ev.supported[h];
69
+ // onPointerDownCapture: the capture phase of an event that propagates.
70
+ const base = h.endsWith('Capture') && !h.endsWith('PointerCapture') ? h.slice(0, -7) : null;
71
+ if (!supported && base && ev.supported[base]?.capture) supported = ev.supported[base];
72
+ if (supported?.targets && !supported.targets.includes(target)) {
73
+ const why = 'the ' + target + ' host does not feed the core raw input yet (delivered on ' + supported.targets.join(', ') + ')';
74
+ out.push(issue('event-target', h, '`' + h + '` on ' + target, null, why, 'onClick, or branch on import.meta.env.BAKE_TARGET'));
75
+ continue;
76
+ }
77
+ if (supported && (!supported.elements || supported.elements.includes(tag))) continue;
78
+ const prefix = Object.keys(ev.unsupportedPrefixes).filter((p) => h.startsWith(p)).sort((a, b) => b.length - a.length)[0];
79
+ const [id, e] = ev.unsupported[h] ? [`event-${h}`, ev.unsupported[h]]
80
+ : prefix ? [`event-${prefix}`, ev.unsupportedPrefixes[prefix]]
81
+ : supported ? ['event-element', null] : ['event-unknown', null];
82
+ const why = supported ? `native delivers it only on <${supported.elements.join('>, <')}>` : 'native never delivers it';
83
+ out.push(issue(id, h, `\`${h}\` on <${tag}>`, e, why, 'a supported handler (see the support list)'));
84
+ }
85
+ return out;
86
+ }
87
+
@@ -0,0 +1,115 @@
1
+ // <video> element handles of native targets (bake_core::media): the core renders a <video> with
2
+ // the platform player; its ref and event.target are element handles whose prototype adds the
3
+ // media element's members on top of the element APIs' (element-api.js, when the bundle has them):
4
+ // currentTime, duration, paused, ended, videoWidth, videoHeight, error, play(), pause().
5
+ // State comes with every media event (the core puts it on `target`); play() / pause() /
6
+ // currentTime = t call the player (`native.$views.Video`, installed by hosts that link it: bake
7
+ // build links it when the bundle renders <video>).
8
+ //
9
+ // host-runtime.js installs this only in bundles that render <video> (`bake build`: __BAKE_MEDIA__):
10
+ // the rest pay nothing for it.
11
+
12
+ const FIELDS = ['currentTime', 'duration', 'paused', 'ended', 'videoWidth', 'videoHeight', 'error'];
13
+ /** The DOM types of the player's events. */
14
+ const EVENTS = new Set(['loadedmetadata', 'play', 'pause', 'ended', 'timeupdate', 'error']);
15
+
16
+ function mediaError(message, code) {
17
+ const e = new Error(message);
18
+ e.name = code === 'E_UNAVAILABLE' ? 'NotSupportedError' : 'AbortError';
19
+ e.code = code;
20
+ return e;
21
+ }
22
+
23
+ function player(id, command, args) {
24
+ const fn = globalThis.native?.$views?.Video?.[command];
25
+ if (typeof fn !== 'function') {
26
+ return Promise.reject(mediaError('<video>.' + command + ': this host has no video player (rebuild the app: bake build links it when a bundle renders <video>)', 'E_UNAVAILABLE'));
27
+ }
28
+ try {
29
+ return Promise.resolve(fn(id, ...args));
30
+ } catch (e) {
31
+ return Promise.reject(e);
32
+ }
33
+ }
34
+
35
+ /** Installs the <video> handle prototype over `base` (the element handles' prototype, or null).
36
+ * `adopt(id, proto)` turns a handle made before its node was known as a <video> (a ref is set
37
+ * in the commit, before its batch is applied) into one. Returns { proto, isVideo(id),
38
+ * track(commands), event(payload, element) }. */
39
+ export function installMediaElement(base, adopt) {
40
+ // Host ids of <video> elements (from the batches) and their media state (from the events).
41
+ const videos = new Set();
42
+ const states = new Map();
43
+ const add = (id) => {
44
+ if (videos.has(id)) return;
45
+ videos.add(id);
46
+ adopt(id, proto);
47
+ };
48
+ const state = (id) => {
49
+ let s = states.get(id);
50
+ if (!s) states.set(id, (s = { currentTime: 0, duration: NaN, paused: true, ended: false, videoWidth: 0, videoHeight: 0, error: null }));
51
+ return s;
52
+ };
53
+ const proto = Object.create(base ?? Object.prototype);
54
+ for (const k of FIELDS) {
55
+ if (k === 'currentTime') continue;
56
+ Object.defineProperty(proto, k, { get() { return state(this.id)[k]; }, enumerable: true });
57
+ }
58
+ Object.defineProperty(proto, 'currentTime', {
59
+ enumerable: true,
60
+ get() { return state(this.id).currentTime; },
61
+ set(t) {
62
+ const s = Number(t);
63
+ if (!Number.isFinite(s)) throw new TypeError('currentTime must be a finite number');
64
+ const st = state(this.id);
65
+ st.currentTime = Math.max(0, s);
66
+ player(this.id, 'seek', [st.currentTime]).catch(() => {});
67
+ },
68
+ });
69
+ proto.play = function play() { return player(this.id, 'play', []); };
70
+ // HTMLMediaElement.pause() returns nothing.
71
+ proto.pause = function pause() { player(this.id, 'pause', []).catch(() => {}); };
72
+
73
+ /** <video> host ids from a batch: create / recreate and template mounts (host ids are
74
+ * contiguous: first + run * nodes + index); destroyed ones go with their state. */
75
+ function track(commands) {
76
+ for (const c of commands) {
77
+ switch (c.op) {
78
+ case 'create':
79
+ case 'recreate':
80
+ if (c.type === 'video') add(c.id);
81
+ else if (c.op === 'recreate' && videos.delete(c.id)) states.delete(c.id);
82
+ break;
83
+ case 'destroy':
84
+ if (videos.delete(c.id)) states.delete(c.id);
85
+ break;
86
+ case 'mount-template':
87
+ c.shape.forEach((s, i) => { if (s.type === 'video') add(c.nodes[i].id); });
88
+ break;
89
+ case 'mount-template-run':
90
+ case 'mount-template-range': {
91
+ const nodes = c.program.nodes;
92
+ const count = c.op === 'mount-template-run' ? c.count : 1;
93
+ nodes.forEach((n, i) => {
94
+ if (n.type !== 'video') return;
95
+ for (let k = 0; k < count; k++) add(c.firstId + k * nodes.length + i);
96
+ });
97
+ break;
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ /** A media event's payload: the element's state comes on `target`; the event gets the handle. */
104
+ function event(payload, element) {
105
+ const t = payload?.target;
106
+ if (!EVENTS.has(payload?.type) || t == null || typeof t !== 'object' || typeof t.id !== 'number' || !('paused' in t)) return payload;
107
+ add(t.id);
108
+ const el = element(t.id);
109
+ const s = state(t.id);
110
+ for (const k of FIELDS) if (k in t) s[k] = t[k] ?? (k === 'duration' ? NaN : k === 'error' ? null : s[k]);
111
+ return Object.assign({}, payload, { target: el, currentTarget: el, nativeEvent: null });
112
+ }
113
+
114
+ return { proto, isVideo: (id) => videos.has(id), track, event };
115
+ }
@@ -0,0 +1,2 @@
1
+ // Imported by the web glue generated from native module specs.
2
+ export { webSpec } from './native-args.js';
@@ -0,0 +1,7 @@
1
+ // The descriptor generated from a native module spec.
2
+ type ArgType =
3
+ | 's' | 'n' | 'i' | 'b' | 'u'
4
+ | { o: ArgType } | { a: ArgType } | { m: ArgType } | { e: string[] }
5
+ | { r: string; f: [string, ArgType, 1?][] };
6
+
7
+ export declare function webSpec(name: string, members: Record<string, [0 | 1, ...ArgType[]]>): void;
package/native-args.js ADDED
@@ -0,0 +1,155 @@
1
+ // Argument checks of web modules against their spec, as the native hosts do them (Swift
2
+ // BakeNativeGenerated, Kotlin BakeNativeGenerated, Rust bake_runtime::modules): a call a host rejects with
3
+ // E_ARGUMENT is rejected on the web too, with the same message. Only the generated web glue
4
+ // (`<Name>Spec.js`, `bake build`) imports this; a native bundle never does.
5
+ //
6
+ // Types are compact descriptors the glue writes from the spec:
7
+ // 's' string 'n' number 'i' Int 'b' boolean 'u' unknown
8
+ // { o: T } T | null { a: T } T[] { m: T } Record<string, T> { e: [values] } a string union
9
+ // { r: 'Name', f: [[field, T, optional?], ...] } a record
10
+ // { u: 'Name', k: tag, c: [[value, [[field, T, optional?], ...]], ...] } a tagged union
11
+ // A member is [async (0 | 1), ...parameter types].
12
+ import { checkWebModule } from './native.js';
13
+
14
+ const SCALAR = { s: 'string', n: 'number', i: 'number', b: 'boolean', u: 'unknown' };
15
+ const quote = (v) => `'${v.replace(/'/g, "\\'")}'`;
16
+
17
+ /** The TypeScript string of a type, as the hosts write it (native-specs.mjs tsType). */
18
+ export function typeScript(t) {
19
+ if (typeof t === 'string') return SCALAR[t];
20
+ if (t.o) return `${typeScript(t.o)} | null`;
21
+ if (t.a) { const e = typeScript(t.a); return e.includes(' ') ? `(${e})[]` : `${e}[]`; }
22
+ if (t.m) return `Record<string, ${typeScript(t.m)}>`;
23
+ if (t.e) return t.e.map(quote).join(' | ');
24
+ if (t.u) return t.c.map(([value, f]) => `{ ${[`${t.k}: ${quote(value)}`, ...f.map(([k, x, opt]) => `${k}${opt ? '?' : ''}: ${typeScript(x)}`)].join('; ')} }`).join(' | ');
25
+ return t.f.length ? `{ ${t.f.map(([k, f, opt]) => `${k}${opt ? '?' : ''}: ${typeScript(f)}`).join('; ')} }` : 'Record<string, unknown>';
26
+ }
27
+
28
+ /** A value as the hosts name it in messages: "null", "boolean true", "number 42", "string \"x\"", "array", "object". */
29
+ export function describe(v) {
30
+ if (v == null) return 'null';
31
+ if (typeof v === 'boolean') return `boolean ${v}`;
32
+ if (typeof v === 'number') return `number ${v}`;
33
+ if (typeof v === 'string') { const c = [...v]; return `string "${c.length > 40 ? `${c.slice(0, 40).join('')}…` : v}"`; }
34
+ return Array.isArray(v) ? 'array' : 'object';
35
+ }
36
+
37
+ // A value of the wrong type ({ x: expected, g: got }) or a record's own error ({ m: message }).
38
+ const mismatch = (x, v) => ({ x, g: describe(v) });
39
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
40
+
41
+ function check(t, v) {
42
+ if (v === undefined) v = null; // what crosses to a host: JSON-like values, undefined as null
43
+ switch (t) {
44
+ case 'u': return;
45
+ case 's': case 'b': if (typeof v !== SCALAR[t]) throw mismatch(SCALAR[t], v); return;
46
+ case 'n': case 'i':
47
+ if (typeof v !== 'number') throw mismatch('number', v);
48
+ // Int: a 64-bit integer (Swift Int(exactly:), Kotlin Long, Rust i64).
49
+ if (t === 'i' && !(Number.isInteger(v) && v >= -(2 ** 63) && v < 2 ** 63)) throw mismatch('integer', v);
50
+ return;
51
+ }
52
+ if (t.o) { if (v !== null) check(t.o, v); return; }
53
+ if (t.e) { if (!t.e.includes(v)) throw mismatch(typeScript(t), v); return; }
54
+ if (t.a) {
55
+ if (!Array.isArray(v)) throw mismatch(typeScript(t), v);
56
+ v.forEach((x, i) => {
57
+ try { check(t.a, x); } catch (e) { throw e.x ? mismatch(`${e.x} at [${i}]`, x) : e; }
58
+ });
59
+ return;
60
+ }
61
+ if (!isObject(v)) throw mismatch(typeScript(t), v);
62
+ if (t.m) { for (const k in v) check(t.m, v[k]); return; }
63
+ if (t.u) { checkFields(t.u, unionCase(t, v), v); return; }
64
+ // A record: fields it does not declare are ignored, as on every host.
65
+ checkFields(t.r, t.f, v);
66
+ }
67
+
68
+ /** The fields of the case `v` (an object) of tagged union `t`, or a record error for its tag. */
69
+ function unionCase(t, v) {
70
+ if (v[t.k] === undefined) throw { m: `${t.u}: missing field "${t.k}"` };
71
+ const c = t.c.find(([value]) => value === v[t.k]);
72
+ if (!c) throw { m: `${t.u}: field "${t.k}" expected ${t.c.map(([value]) => quote(value)).join(' | ')}, got ${describe(v[t.k])}` };
73
+ return c[1];
74
+ }
75
+
76
+ function checkFields(name, fields, v) {
77
+ for (const [k, f, opt] of fields) {
78
+ if (v[k] === undefined) {
79
+ if (opt) continue;
80
+ throw { m: `${name}: missing field "${k}"` };
81
+ }
82
+ try { check(f, v[k]); } catch (e) { throw { m: e.x ? `${name}: field "${k}" expected ${e.x}, got ${e.g}` : `${name}.${k}: ${e.m}` }; }
83
+ }
84
+ }
85
+
86
+ /** The E_ARGUMENT message of a call with `args` (no label), or undefined when the host takes it. */
87
+ export function argumentError(params, args) {
88
+ const n = params.length;
89
+ if (args.length > n) return `expected ${n ? `at most ${n}` : 'no'} argument${n === 1 ? '' : 's'}, got ${args.length}`;
90
+ for (let i = 0; i < n; i++) {
91
+ try { check(params[i], args[i]); } catch (e) {
92
+ return `argument ${i}: ${e.x ? `expected ${e.x}, got ${i < args.length ? e.g : 'undefined'}` : e.m}`;
93
+ }
94
+ }
95
+ }
96
+
97
+ /**
98
+ * An argument as the native hosts hand it to the implementation: a record's optional field that is
99
+ * null (or undefined) is absent, as a Swift `nil` / Kotlin `null` / Rust `None` that goes back out
100
+ * absent. Other values are passed as they are (a checked argument is never copied needlessly).
101
+ */
102
+ export function normalize(t, v) {
103
+ if (v == null || typeof t === 'string' || t.e) return v;
104
+ if (t.o) return normalize(t.o, v);
105
+ if (t.a) return Array.isArray(v) ? v.map((x) => normalize(t.a, x)) : v;
106
+ if (t.m) return v;
107
+ const fields = t.u ? t.c.find(([value]) => value === v[t.k])?.[1] ?? [] : t.f;
108
+ let out = v;
109
+ for (const [k, f, opt] of fields) {
110
+ if (!(k in v)) continue;
111
+ if (opt && v[k] == null) {
112
+ if (out === v) out = { ...v };
113
+ delete out[k];
114
+ } else if (typeof f !== 'string') {
115
+ const n = normalize(f, v[k]);
116
+ if (n !== v[k]) { if (out === v) out = { ...v }; out[k] = n; }
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /** An implementation's error as the native hosts label it: `<Module>.<member>: <message>`, its
123
+ * code kept (E_NATIVE when it has none). */
124
+ function labeled(e, path) {
125
+ const message = e instanceof Error ? e.message : String(e);
126
+ return Object.assign(new Error(`${path}: ${message}`), { code: (e && typeof e.code === 'string' && e.code) || 'E_NATIVE' });
127
+ }
128
+
129
+ /** The generated glue of module `name`: `members` by name ([async, ...parameter types]). */
130
+ export function webSpec(name, members) {
131
+ checkWebModule(name, (impl) => {
132
+ const out = {};
133
+ for (const k of new Set([...Object.keys(impl), ...Object.keys(members)])) {
134
+ const m = members[k];
135
+ if (!m || typeof impl[k] !== 'function') {
136
+ if (k in impl) Object.defineProperty(out, k, { get: () => impl[k], enumerable: true, configurable: true });
137
+ continue;
138
+ }
139
+ const [async, ...params] = m;
140
+ out[k] = (...args) => {
141
+ const message = argumentError(params, args);
142
+ if (message === undefined) {
143
+ const path = `${name}.${k}`;
144
+ const values = args.map((a, i) => normalize(params[i], a));
145
+ if (async) return Promise.resolve().then(() => impl[k](...values)).catch((e) => { throw labeled(e, path); });
146
+ try { return impl[k](...values); } catch (e) { throw labeled(e, path); }
147
+ }
148
+ const e = Object.assign(new Error(`${name}.${k}: ${message}`), { code: 'E_ARGUMENT' });
149
+ if (async) return Promise.reject(e);
150
+ throw e;
151
+ };
152
+ }
153
+ return out;
154
+ });
155
+ }
@@ -0,0 +1 @@
1
+ export { native, hasNative, registerWebModule, host } from './native.js';