@craftguild/expo-oriha 0.0.0-stage → 0.2.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 (46) hide show
  1. package/ExpoOriha.podspec +26 -0
  2. package/LICENSE +8 -0
  3. package/LICENSE-APACHE +176 -0
  4. package/LICENSE-MIT +27 -0
  5. package/README.md +76 -2
  6. package/THIRD_PARTY_NOTICES.md +126 -0
  7. package/android/build.gradle +37 -0
  8. package/android/src/main/AndroidManifest.xml +1 -0
  9. package/android/src/main/java/co/progressiveworks/oriha/ExpoOrihaModule.kt +62 -0
  10. package/android/src/main/java/co/progressiveworks/oriha/OrihaRustBridge.kt +73 -0
  11. package/android/src/main/java/uniffi/oriha_native_bridge/oriha_native_bridge.kt +5862 -0
  12. package/android/src/main/jniLibs/arm64-v8a/liboriha_native_bridge.so +0 -0
  13. package/android/src/main/jniLibs/armeabi-v7a/liboriha_native_bridge.so +0 -0
  14. package/android/src/main/jniLibs/x86_64/liboriha_native_bridge.so +0 -0
  15. package/dist/chunk-CfYAbeIz.mjs +13 -0
  16. package/dist/index.cjs +4517 -0
  17. package/dist/index.d.cts +1031 -0
  18. package/dist/index.d.mts +1029 -0
  19. package/dist/index.mjs +4338 -0
  20. package/expo-module.config.json +10 -0
  21. package/ios/ExpoOrihaModule.swift +55 -0
  22. package/ios/OrihaRustBridge.swift +62 -0
  23. package/ios/generated/oriha_native_bridge.swift +6526 -0
  24. package/ios/generated/oriha_native_bridgeFFI.h +766 -0
  25. package/ios/generated/oriha_native_bridgeFFI.modulemap +7 -0
  26. package/ios/native/OrihaNativeBridge.xcframework/Info.plist +47 -0
  27. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64/Headers/oriha_native_bridge.swift +6526 -0
  28. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64/Headers/oriha_native_bridgeFFI.h +766 -0
  29. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64/Headers/oriha_native_bridgeFFI.modulemap +7 -0
  30. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64/liboriha_native_bridge.a +0 -0
  31. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64-simulator/Headers/oriha_native_bridge.swift +6526 -0
  32. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64-simulator/Headers/oriha_native_bridgeFFI.h +766 -0
  33. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64-simulator/Headers/oriha_native_bridgeFFI.modulemap +7 -0
  34. package/ios/native/OrihaNativeBridge.xcframework/ios-arm64-simulator/liboriha_native_bridge.a +0 -0
  35. package/licenses/heroicons-LICENSE +21 -0
  36. package/licenses/rolldown-LICENSE +25 -0
  37. package/licenses/third-party-licenses.json +415 -0
  38. package/package.json +82 -4
  39. package/sbom/aarch64-apple-ios-sim.cdx.json +912 -0
  40. package/sbom/aarch64-apple-ios.cdx.json +912 -0
  41. package/sbom/aarch64-linux-android.cdx.json +929 -0
  42. package/sbom/armv7-linux-androideabi.cdx.json +929 -0
  43. package/sbom/artifacts.json +241 -0
  44. package/sbom/bom.cdx.json +6607 -0
  45. package/sbom/javascript.cdx.json +85 -0
  46. package/sbom/x86_64-linux-android.cdx.json +929 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,4517 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ let react = require("react");
34
+ react = __toESM(react);
35
+ let react_native = require("react-native");
36
+ let react_native_webview = require("react-native-webview");
37
+ let expo_file_system_legacy = require("expo-file-system/legacy");
38
+ expo_file_system_legacy = __toESM(expo_file_system_legacy);
39
+ let expo_crypto = require("expo-crypto");
40
+ expo_crypto = __toESM(expo_crypto);
41
+ let react_native_svg = require("react-native-svg");
42
+ react_native_svg = __toESM(react_native_svg);
43
+ let react_jsx_runtime = require("react/jsx-runtime");
44
+ let expo_sharing = require("expo-sharing");
45
+ expo_sharing = __toESM(expo_sharing);
46
+ let expo_file_system = require("expo-file-system");
47
+ let expo_print = require("expo-print");
48
+ expo_print = __toESM(expo_print);
49
+ let expo = require("expo");
50
+ //#region src/provider/OrihaEnums.ts
51
+ let OrihaOverlayPlacement = /* @__PURE__ */ function(OrihaOverlayPlacement) {
52
+ OrihaOverlayPlacement["Top"] = "top";
53
+ OrihaOverlayPlacement["Center"] = "center";
54
+ OrihaOverlayPlacement["Bottom"] = "bottom";
55
+ OrihaOverlayPlacement["Fill"] = "fill";
56
+ return OrihaOverlayPlacement;
57
+ }({});
58
+ let OrihaToastPosition = /* @__PURE__ */ function(OrihaToastPosition) {
59
+ OrihaToastPosition["Top"] = "top";
60
+ OrihaToastPosition["Center"] = "center";
61
+ OrihaToastPosition["Bottom"] = "bottom";
62
+ return OrihaToastPosition;
63
+ }({});
64
+ let OrihaToastVariant = /* @__PURE__ */ function(OrihaToastVariant) {
65
+ OrihaToastVariant["Neutral"] = "neutral";
66
+ OrihaToastVariant["Info"] = "info";
67
+ OrihaToastVariant["Note"] = "note";
68
+ OrihaToastVariant["Success"] = "success";
69
+ OrihaToastVariant["Warn"] = "warn";
70
+ OrihaToastVariant["Warning"] = "warn";
71
+ OrihaToastVariant["Err"] = "err";
72
+ OrihaToastVariant["Error"] = "err";
73
+ return OrihaToastVariant;
74
+ }({});
75
+ //#endregion
76
+ //#region generated/generatedBridgeEnums.ts
77
+ let RenderMode = /* @__PURE__ */ function(RenderMode) {
78
+ RenderMode["StyledHtml"] = "styledHtml";
79
+ RenderMode["SemanticHtml"] = "semanticHtml";
80
+ return RenderMode;
81
+ }({});
82
+ let AppearanceStyle = /* @__PURE__ */ function(AppearanceStyle) {
83
+ AppearanceStyle["Rich"] = "rich";
84
+ AppearanceStyle["Simple"] = "simple";
85
+ return AppearanceStyle;
86
+ }({});
87
+ let TableBorderStyle = /* @__PURE__ */ function(TableBorderStyle) {
88
+ TableBorderStyle["None"] = "none";
89
+ TableBorderStyle["Inner"] = "inner";
90
+ TableBorderStyle["All"] = "all";
91
+ TableBorderStyle["Vertical"] = "vertical";
92
+ TableBorderStyle["Horizontal"] = "horizontal";
93
+ return TableBorderStyle;
94
+ }({});
95
+ let RenderDiagnosticSeverity = /* @__PURE__ */ function(RenderDiagnosticSeverity) {
96
+ RenderDiagnosticSeverity["Info"] = "info";
97
+ RenderDiagnosticSeverity["Warning"] = "warning";
98
+ RenderDiagnosticSeverity["Error"] = "error";
99
+ return RenderDiagnosticSeverity;
100
+ }({});
101
+ let RenderDiagnosticEngine = /* @__PURE__ */ function(RenderDiagnosticEngine) {
102
+ RenderDiagnosticEngine["Core"] = "core";
103
+ RenderDiagnosticEngine["Bridge"] = "bridge";
104
+ return RenderDiagnosticEngine;
105
+ }({});
106
+ let RenderAssetKind = /* @__PURE__ */ function(RenderAssetKind) {
107
+ RenderAssetKind["Svg"] = "svg";
108
+ RenderAssetKind["Css"] = "css";
109
+ RenderAssetKind["Other"] = "other";
110
+ return RenderAssetKind;
111
+ }({});
112
+ let RenderPatchStrategy = /* @__PURE__ */ function(RenderPatchStrategy) {
113
+ RenderPatchStrategy["Incremental"] = "incremental";
114
+ RenderPatchStrategy["ReplaceAll"] = "replaceAll";
115
+ return RenderPatchStrategy;
116
+ }({});
117
+ let RenderPatchFallbackReason = /* @__PURE__ */ function(RenderPatchFallbackReason) {
118
+ RenderPatchFallbackReason["MissingSnapshot"] = "missingSnapshot";
119
+ RenderPatchFallbackReason["IncompatibleSnapshot"] = "incompatibleSnapshot";
120
+ RenderPatchFallbackReason["TailChanged"] = "tailChanged";
121
+ RenderPatchFallbackReason["OutputTruncated"] = "outputTruncated";
122
+ RenderPatchFallbackReason["InvalidInput"] = "invalidInput";
123
+ RenderPatchFallbackReason["EnginePanic"] = "enginePanic";
124
+ return RenderPatchFallbackReason;
125
+ }({});
126
+ let BridgeFeature = /* @__PURE__ */ function(BridgeFeature) {
127
+ BridgeFeature["Gfm"] = "gfm";
128
+ BridgeFeature["SyntaxHighlight"] = "syntaxHighlight";
129
+ BridgeFeature["DarkMode"] = "darkMode";
130
+ BridgeFeature["Tables"] = "tables";
131
+ BridgeFeature["TaskLists"] = "taskLists";
132
+ BridgeFeature["Footnotes"] = "footnotes";
133
+ BridgeFeature["RawHtml"] = "rawHtml";
134
+ BridgeFeature["PdfExport"] = "pdfExport";
135
+ BridgeFeature["Callouts"] = "callouts";
136
+ BridgeFeature["RemovePdfWatermark"] = "removePdfWatermark";
137
+ BridgeFeature["PrioritySupport"] = "prioritySupport";
138
+ BridgeFeature["Plantuml"] = "plantuml";
139
+ BridgeFeature["Mermaid"] = "mermaid";
140
+ BridgeFeature["Math"] = "math";
141
+ BridgeFeature["SyntaxThemeCustomization"] = "syntaxThemeCustomization";
142
+ BridgeFeature["FontCustomization"] = "fontCustomization";
143
+ return BridgeFeature;
144
+ }({});
145
+ let UsageAnalyticsOutboxCommandKind = /* @__PURE__ */ function(UsageAnalyticsOutboxCommandKind) {
146
+ UsageAnalyticsOutboxCommandKind["LoadEnvelopes"] = "loadEnvelopes";
147
+ UsageAnalyticsOutboxCommandKind["WriteEnvelope"] = "writeEnvelope";
148
+ UsageAnalyticsOutboxCommandKind["DeleteEnvelope"] = "deleteEnvelope";
149
+ UsageAnalyticsOutboxCommandKind["PurgeEnvelopes"] = "purgeEnvelopes";
150
+ UsageAnalyticsOutboxCommandKind["SendHttp"] = "sendHttp";
151
+ return UsageAnalyticsOutboxCommandKind;
152
+ }({});
153
+ let Plan = /* @__PURE__ */ function(Plan) {
154
+ Plan["Free"] = "free";
155
+ Plan["Premium"] = "premium";
156
+ return Plan;
157
+ }({});
158
+ let ColorScheme = /* @__PURE__ */ function(ColorScheme) {
159
+ ColorScheme["Light"] = "light";
160
+ ColorScheme["Dark"] = "dark";
161
+ return ColorScheme;
162
+ }({});
163
+ let SyntaxTheme = /* @__PURE__ */ function(SyntaxTheme) {
164
+ SyntaxTheme["GitHubLight"] = "github-light";
165
+ SyntaxTheme["GitHubDark"] = "github-dark";
166
+ SyntaxTheme["SolarizedLight"] = "solarized-light";
167
+ SyntaxTheme["SolarizedDark"] = "solarized-dark";
168
+ SyntaxTheme["GruvboxLight"] = "gruvbox-light";
169
+ SyntaxTheme["GruvboxDark"] = "gruvbox-dark";
170
+ SyntaxTheme["CatppuccinLatte"] = "catppuccin-latte";
171
+ SyntaxTheme["CatppuccinMocha"] = "catppuccin-mocha";
172
+ SyntaxTheme["AyuLight"] = "ayu-light";
173
+ SyntaxTheme["AyuDark"] = "ayu-dark";
174
+ SyntaxTheme["TokyoNightDay"] = "tokyo-night-day";
175
+ SyntaxTheme["TokyoNight"] = "tokyo-night";
176
+ SyntaxTheme["RosePineDawn"] = "rose-pine-dawn";
177
+ SyntaxTheme["RosePine"] = "rose-pine";
178
+ SyntaxTheme["HighContrastLight"] = "high-contrast-light";
179
+ SyntaxTheme["HighContrastDark"] = "high-contrast-dark";
180
+ SyntaxTheme["Custom"] = "custom";
181
+ return SyntaxTheme;
182
+ }({});
183
+ let HeadingFont = /* @__PURE__ */ function(HeadingFont) {
184
+ HeadingFont["SystemDefault"] = "system-default";
185
+ HeadingFont["Custom"] = "custom";
186
+ return HeadingFont;
187
+ }({});
188
+ let BodyFont = /* @__PURE__ */ function(BodyFont) {
189
+ BodyFont["SystemDefault"] = "system-default";
190
+ BodyFont["Custom"] = "custom";
191
+ return BodyFont;
192
+ }({});
193
+ let CodeFont = /* @__PURE__ */ function(CodeFont) {
194
+ CodeFont["SystemDefault"] = "system-default";
195
+ CodeFont["Custom"] = "custom";
196
+ return CodeFont;
197
+ }({});
198
+ //#endregion
199
+ //#region generated/generatedBridgeTypes.ts
200
+ var generatedBridgeTypes_exports = /* @__PURE__ */ __exportAll({
201
+ AppearanceStyle: () => AppearanceStyle,
202
+ BodyFont: () => BodyFont,
203
+ BridgeFeature: () => BridgeFeature,
204
+ CodeFont: () => CodeFont,
205
+ ColorScheme: () => ColorScheme,
206
+ HeadingFont: () => HeadingFont,
207
+ Plan: () => Plan,
208
+ RenderAssetKind: () => RenderAssetKind,
209
+ RenderDiagnosticEngine: () => RenderDiagnosticEngine,
210
+ RenderDiagnosticSeverity: () => RenderDiagnosticSeverity,
211
+ RenderMode: () => RenderMode,
212
+ RenderPatchFallbackReason: () => RenderPatchFallbackReason,
213
+ RenderPatchStrategy: () => RenderPatchStrategy,
214
+ SyntaxTheme: () => SyntaxTheme,
215
+ TableBorderStyle: () => TableBorderStyle,
216
+ UsageAnalyticsOutboxCommandKind: () => UsageAnalyticsOutboxCommandKind
217
+ });
218
+ //#endregion
219
+ //#region src/types.ts
220
+ const OrihaPdfPaperSize = {
221
+ A4: "A4",
222
+ B4: "B4",
223
+ Letter: "Letter"
224
+ };
225
+ const OrihaPdfOrientation = {
226
+ Portrait: "Portrait",
227
+ Landscape: "Landscape"
228
+ };
229
+ //#endregion
230
+ //#region src/runtime/expoRuntimeI18n.ts
231
+ const DEFAULT_ORIHA_LOCALE = "en";
232
+ const ORIHA_MESSAGE_KEYS = [
233
+ "codeCopy.success",
234
+ "codeCopy.failure",
235
+ "debug.shareRenderedHtml",
236
+ "debug.shareDialogTitle",
237
+ "debug.renderedHtmlSaved",
238
+ "debug.shareFailed",
239
+ "debug.fileSystemDirectoryUnavailable",
240
+ "externalLink.openFailed",
241
+ "measurement.cancelled",
242
+ "measurement.timeout"
243
+ ];
244
+ const EN_MESSAGES = {
245
+ "codeCopy.success": "Copied",
246
+ "codeCopy.failure": "Copy failed",
247
+ "debug.shareRenderedHtml": "Share rendered HTML",
248
+ "debug.shareDialogTitle": "Rendered HTML",
249
+ "debug.renderedHtmlSaved": "Rendered HTML saved: {fileUri}",
250
+ "debug.shareFailed": "HTML file share failed: {message}",
251
+ "debug.fileSystemDirectoryUnavailable": "Expo FileSystem directory is not available",
252
+ "externalLink.openFailed": "Could not open link",
253
+ "measurement.cancelled": "Markdown measurement cancelled",
254
+ "measurement.timeout": "Markdown measurement timed out after {timeoutMs}ms"
255
+ };
256
+ const BUILTIN_MESSAGES = {
257
+ en: EN_MESSAGES,
258
+ es: {
259
+ "codeCopy.success": "Copiado",
260
+ "codeCopy.failure": "No se pudo copiar",
261
+ "debug.shareRenderedHtml": "Compartir HTML renderizado",
262
+ "debug.shareDialogTitle": "HTML renderizado",
263
+ "debug.renderedHtmlSaved": "HTML renderizado guardado: {fileUri}",
264
+ "debug.shareFailed": "No se pudo compartir el archivo HTML: {message}",
265
+ "debug.fileSystemDirectoryUnavailable": "El directorio de Expo FileSystem no está disponible",
266
+ "externalLink.openFailed": "No se pudo abrir el enlace",
267
+ "measurement.cancelled": "Medición de Markdown cancelada",
268
+ "measurement.timeout": "La medición de Markdown agotó el tiempo tras {timeoutMs} ms"
269
+ },
270
+ fr: {
271
+ "codeCopy.success": "Copié",
272
+ "codeCopy.failure": "Échec de la copie",
273
+ "debug.shareRenderedHtml": "Partager le HTML rendu",
274
+ "debug.shareDialogTitle": "HTML rendu",
275
+ "debug.renderedHtmlSaved": "HTML rendu enregistré : {fileUri}",
276
+ "debug.shareFailed": "Échec du partage du fichier HTML : {message}",
277
+ "debug.fileSystemDirectoryUnavailable": "Le répertoire Expo FileSystem n'est pas disponible",
278
+ "externalLink.openFailed": "Impossible d'ouvrir le lien",
279
+ "measurement.cancelled": "Mesure Markdown annulée",
280
+ "measurement.timeout": "La mesure Markdown a expiré après {timeoutMs} ms"
281
+ },
282
+ ja: {
283
+ "codeCopy.success": "コピーしました",
284
+ "codeCopy.failure": "コピーに失敗しました",
285
+ "debug.shareRenderedHtml": "レンダリング済みHTMLを共有",
286
+ "debug.shareDialogTitle": "レンダリング済みHTML",
287
+ "debug.renderedHtmlSaved": "レンダリング済みHTMLを保存しました: {fileUri}",
288
+ "debug.shareFailed": "HTMLファイルの共有に失敗しました: {message}",
289
+ "debug.fileSystemDirectoryUnavailable": "Expo FileSystem の保存先を利用できません",
290
+ "externalLink.openFailed": "リンクを開けませんでした",
291
+ "measurement.cancelled": "Markdown の計測をキャンセルしました",
292
+ "measurement.timeout": "Markdown の計測が {timeoutMs}ms 以内に完了しませんでした"
293
+ },
294
+ ko: {
295
+ "codeCopy.success": "복사했습니다",
296
+ "codeCopy.failure": "복사에 실패했습니다",
297
+ "debug.shareRenderedHtml": "렌더링된 HTML 공유",
298
+ "debug.shareDialogTitle": "렌더링된 HTML",
299
+ "debug.renderedHtmlSaved": "렌더링된 HTML을 저장했습니다: {fileUri}",
300
+ "debug.shareFailed": "HTML 파일 공유에 실패했습니다: {message}",
301
+ "debug.fileSystemDirectoryUnavailable": "Expo FileSystem 저장 위치를 사용할 수 없습니다",
302
+ "externalLink.openFailed": "링크를 열 수 없습니다",
303
+ "measurement.cancelled": "Markdown 측정을 취소했습니다",
304
+ "measurement.timeout": "Markdown 측정이 {timeoutMs}ms 안에 완료되지 않았습니다"
305
+ },
306
+ "zh-Hans": {
307
+ "codeCopy.success": "已复制",
308
+ "codeCopy.failure": "复制失败",
309
+ "debug.shareRenderedHtml": "分享已渲染的 HTML",
310
+ "debug.shareDialogTitle": "已渲染的 HTML",
311
+ "debug.renderedHtmlSaved": "已保存已渲染的 HTML: {fileUri}",
312
+ "debug.shareFailed": "HTML 文件分享失败: {message}",
313
+ "debug.fileSystemDirectoryUnavailable": "无法使用 Expo FileSystem 目录",
314
+ "externalLink.openFailed": "无法打开链接",
315
+ "measurement.cancelled": "已取消 Markdown 测量",
316
+ "measurement.timeout": "Markdown 测量在 {timeoutMs}ms 内未完成"
317
+ },
318
+ "zh-Hant": {
319
+ "codeCopy.success": "已複製",
320
+ "codeCopy.failure": "複製失敗",
321
+ "debug.shareRenderedHtml": "分享已轉譯的 HTML",
322
+ "debug.shareDialogTitle": "已轉譯的 HTML",
323
+ "debug.renderedHtmlSaved": "已儲存已轉譯的 HTML: {fileUri}",
324
+ "debug.shareFailed": "HTML 檔案分享失敗: {message}",
325
+ "debug.fileSystemDirectoryUnavailable": "無法使用 Expo FileSystem 目錄",
326
+ "externalLink.openFailed": "無法開啟連結",
327
+ "measurement.cancelled": "已取消 Markdown 測量",
328
+ "measurement.timeout": "Markdown 測量未在 {timeoutMs}ms 內完成"
329
+ }
330
+ };
331
+ function createOrihaI18n(locale = "en", messages) {
332
+ const builtinLocale = resolveBuiltinLocale(locale);
333
+ const catalog = {
334
+ ...EN_MESSAGES,
335
+ ...BUILTIN_MESSAGES[builtinLocale],
336
+ ...messages
337
+ };
338
+ return {
339
+ locale,
340
+ formatMessage: (key, values) => formatOrihaMessage(catalog, key, values)
341
+ };
342
+ }
343
+ function defaultOrihaFormatMessage(key, values) {
344
+ return formatOrihaMessage(EN_MESSAGES, key, values);
345
+ }
346
+ function formatOrihaMessage(messages, key, values = {}) {
347
+ var _ref, _messages$key;
348
+ const template = (_ref = (_messages$key = messages[key]) !== null && _messages$key !== void 0 ? _messages$key : EN_MESSAGES[key]) !== null && _ref !== void 0 ? _ref : key;
349
+ if (typeof template === "function") return template(values);
350
+ return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, name) => {
351
+ const value = values[name];
352
+ return value == null ? "" : String(value);
353
+ });
354
+ }
355
+ function resolveBuiltinLocale(locale) {
356
+ const parts = locale.replace(/_/g, "-").toLowerCase().split("-");
357
+ const language = parts[0];
358
+ const regionOrScript = parts.slice(1).join("-");
359
+ switch (language) {
360
+ case "es": return "es";
361
+ case "fr": return "fr";
362
+ case "ja": return "ja";
363
+ case "ko": return "ko";
364
+ case "zh":
365
+ if (regionOrScript.includes("hant") || regionOrScript.includes("tw") || regionOrScript.includes("hk") || regionOrScript.includes("mo")) return "zh-Hant";
366
+ return "zh-Hans";
367
+ default: return "en";
368
+ }
369
+ }
370
+ //#endregion
371
+ //#region src/provider/providerContext.tsx
372
+ const OrihaContext = (0, react.createContext)(null);
373
+ function useOrihaContext() {
374
+ return (0, react.useContext)(OrihaContext);
375
+ }
376
+ function useOrihaFonts() {
377
+ const context = (0, react.useContext)(OrihaContext);
378
+ if (!context) return {
379
+ installedFonts: [],
380
+ installableFonts: [],
381
+ isLoading: false,
382
+ error: null,
383
+ listInstalledFonts: () => Promise.resolve([]),
384
+ listInstallableFonts: () => Promise.resolve([]),
385
+ refreshFontRegistry: () => Promise.resolve([]),
386
+ installFont: () => Promise.reject(/* @__PURE__ */ new Error("useOrihaFonts must be used within OrihaProvider")),
387
+ uninstallFont: () => Promise.resolve()
388
+ };
389
+ return context.fontRegistry;
390
+ }
391
+ function useOrihaOverlay() {
392
+ const context = (0, react.useContext)(OrihaContext);
393
+ if (!context) return {
394
+ presentOverlay: () => () => void 0,
395
+ dismissOverlay: () => void 0,
396
+ showToast: () => () => void 0,
397
+ dismissToast: () => void 0
398
+ };
399
+ return {
400
+ presentOverlay: context.presentOverlay,
401
+ dismissOverlay: context.dismissOverlay,
402
+ showToast: context.showToast,
403
+ dismissToast: context.dismissToast
404
+ };
405
+ }
406
+ function useOrihaI18n() {
407
+ const context = (0, react.useContext)(OrihaContext);
408
+ if (!context) return {
409
+ locale: "en",
410
+ formatMessage: defaultOrihaFormatMessage
411
+ };
412
+ return context.i18n;
413
+ }
414
+ //#endregion
415
+ //#region src/fonts/fontRegistryStorage.ts
416
+ const VENDOR_STORAGE_DIR = "co.progressiveworks.expo-oriha";
417
+ const FONT_FILES_DIR = "files";
418
+ function buildFontRelativeDir(fontId) {
419
+ return `${FONT_FILES_DIR}/${encodeURIComponent(fontId)}/`;
420
+ }
421
+ function buildFontRelativePath(fontId, fileName) {
422
+ return `${buildFontRelativeDir(fontId)}${fileName}`;
423
+ }
424
+ function resolveFontFileUri(storageRootUri, relativePath) {
425
+ return `${ensureTrailingSlash$3(storageRootUri)}${relativePath}`;
426
+ }
427
+ function normalizeInstalledFontFileRecord(value, options) {
428
+ if (!value || typeof value !== "object") return null;
429
+ const file = value;
430
+ if (!file.fileName || !file.sha256) return null;
431
+ const relativePath = typeof file.relativePath === "string" && file.relativePath.length > 0 ? normalizeStoredFontRelativePath(file.relativePath) : typeof file.uri === "string" ? relativePathFromLegacyFontUri(file.uri, options.storageNamespace) : null;
432
+ if (!relativePath) return null;
433
+ return {
434
+ uri: resolveFontFileUri(options.storageRootUri, relativePath),
435
+ relativePath,
436
+ fileName: file.fileName,
437
+ sha256: file.sha256,
438
+ weight: file.weight,
439
+ style: file.style,
440
+ format: file.format,
441
+ unicodeRange: file.unicodeRange,
442
+ size: file.size
443
+ };
444
+ }
445
+ function serializeInstalledFontForIndex(font) {
446
+ return {
447
+ ...font,
448
+ files: font.files.map(({ uri: _uri, ...file }) => file)
449
+ };
450
+ }
451
+ function installedFontIndexEntryNeedsRewrite(value) {
452
+ if (!value || typeof value !== "object") return true;
453
+ const font = value;
454
+ if (!Array.isArray(font.files)) return true;
455
+ return font.files.some((file) => {
456
+ if (!file || typeof file !== "object") return true;
457
+ const installedFile = file;
458
+ return typeof installedFile.uri === "string" || typeof installedFile.relativePath !== "string" || normalizeStoredFontRelativePath(installedFile.relativePath) === null;
459
+ });
460
+ }
461
+ function normalizeStoredFontRelativePath(value) {
462
+ const path = value;
463
+ const segments = path.split("/");
464
+ if (!path || !path.startsWith(`files/`) || segments.some((segment) => !segment || segment === "." || segment === "..") || path.startsWith("file:") || /^[a-z][a-z\d+.-]*:/i.test(path)) return null;
465
+ return path;
466
+ }
467
+ function relativePathFromLegacyFontUri(uri, storageNamespace) {
468
+ const storageMarker = `/${VENDOR_STORAGE_DIR}/${storageNamespace}/`;
469
+ const markerIndex = uri.indexOf(storageMarker);
470
+ if (markerIndex < 0) return null;
471
+ return normalizeStoredFontRelativePath(uri.slice(markerIndex + storageMarker.length));
472
+ }
473
+ function ensureTrailingSlash$3(value) {
474
+ return value.endsWith("/") ? value : `${value}/`;
475
+ }
476
+ //#endregion
477
+ //#region src/fonts/fontRegistryStoragePort.ts
478
+ async function readJsonEntry(port, uri) {
479
+ const info = await port.getInfo(uri);
480
+ if (!info.exists || info.isDirectory) return null;
481
+ try {
482
+ return JSON.parse(await port.readString(uri));
483
+ } catch {
484
+ return null;
485
+ }
486
+ }
487
+ async function writeJsonEntry(port, uri, value) {
488
+ await port.writeString(uri, `${JSON.stringify(value, null, 2)}\n`);
489
+ }
490
+ async function ensureDirectoryEntry(port, uri) {
491
+ await port.makeDirectory(uri, { intermediates: true });
492
+ }
493
+ async function deleteEntryIfExists(port, uri) {
494
+ if ((await port.getInfo(uri)).exists) await port.delete(uri, { idempotent: true });
495
+ }
496
+ async function fileEntryExists(port, uri) {
497
+ try {
498
+ const info = await port.getInfo(uri);
499
+ return info.exists && !info.isDirectory;
500
+ } catch {
501
+ return false;
502
+ }
503
+ }
504
+ async function readPrunedIndexEntries(options) {
505
+ const parsed = await readJsonEntry(options.port, options.indexUri);
506
+ const rawEntries = options.getRawEntries(parsed);
507
+ const normalizedEntries = rawEntries.map(options.normalizeEntry).filter((entry) => entry !== null);
508
+ const existingEntries = await filterExistingEntries(normalizedEntries, options.entryExists);
509
+ if (normalizedEntries.length !== rawEntries.length || rawEntries.some(options.entryNeedsRewrite) || existingEntries.length !== normalizedEntries.length) try {
510
+ await writeJsonEntry(options.port, options.indexUri, options.serializeIndex(existingEntries));
511
+ } catch {}
512
+ return existingEntries;
513
+ }
514
+ async function filterExistingEntries(entries, entryExists) {
515
+ return (await Promise.all(entries.map(async (entry) => ({
516
+ entry,
517
+ exists: await entryExists(entry)
518
+ })))).filter((checkedEntry) => checkedEntry.exists).map((checkedEntry) => checkedEntry.entry);
519
+ }
520
+ //#endregion
521
+ //#region src/fonts/fontRegistryCss.ts
522
+ async function buildInstalledFontFaceCssRules(installedFonts, selectedFontSpecs, readFileBase64) {
523
+ const selectedFamilies = selectedFontFamilies(selectedFontSpecs);
524
+ const rules = [];
525
+ for (const font of installedFonts) {
526
+ if (selectedFamilies && !selectedFamilies.has(font.fontFamilySpec.family)) continue;
527
+ for (const file of font.files) rules.push(buildInstalledFontFaceRule(font, file, await readFileBase64(file)));
528
+ }
529
+ return rules.join("\n");
530
+ }
531
+ function buildInstalledFontFaceRule(font, file, base64) {
532
+ var _file$weight, _file$style;
533
+ const mimeType = fontMimeType(file);
534
+ return [
535
+ "@font-face {",
536
+ ` font-family: ${cssFontFamily(font.fontFamilySpec.family)};`,
537
+ ` src: url("data:${mimeType};base64,${base64}")${file.format ? ` format("${escapeCssString(file.format)}")` : ""};`,
538
+ ` font-weight: ${(_file$weight = file.weight) !== null && _file$weight !== void 0 ? _file$weight : "400"};`,
539
+ ` font-style: ${(_file$style = file.style) !== null && _file$style !== void 0 ? _file$style : "normal"};`,
540
+ ...file.unicodeRange ? [` unicode-range: ${file.unicodeRange};`] : [],
541
+ " font-display: swap;",
542
+ "}"
543
+ ].join("\n");
544
+ }
545
+ function selectedFontFamilies(selectedFontSpecs) {
546
+ return selectedFontSpecs ? new Set(selectedFontSpecs.map((spec) => spec === null || spec === void 0 ? void 0 : spec.family).filter((family) => Boolean(family))) : null;
547
+ }
548
+ function fontMimeType(file) {
549
+ var _file$format;
550
+ const format = (_file$format = file.format) === null || _file$format === void 0 ? void 0 : _file$format.trim().toLowerCase();
551
+ if (format === "woff2") return "font/woff2";
552
+ if (format === "woff") return "font/woff";
553
+ if (format === "opentype" || format === "otf") return "font/otf";
554
+ if (format === "truetype" || format === "ttf") return "font/ttf";
555
+ const lowerFileName = file.fileName.toLowerCase();
556
+ if (lowerFileName.endsWith(".woff2")) return "font/woff2";
557
+ if (lowerFileName.endsWith(".woff")) return "font/woff";
558
+ if (lowerFileName.endsWith(".otf")) return "font/otf";
559
+ if (lowerFileName.endsWith(".ttf")) return "font/ttf";
560
+ return "font/ttf";
561
+ }
562
+ function cssFontFamily(family) {
563
+ const trimmed = family.trim();
564
+ if (trimmed.startsWith("\"") && trimmed.endsWith("\"") || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed;
565
+ return `"${escapeCssString(trimmed)}"`;
566
+ }
567
+ function escapeCssString(value) {
568
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
569
+ }
570
+ //#endregion
571
+ //#region src/fonts/fontRegistryModel.ts
572
+ const DEFAULT_STORAGE_NAMESPACE$1 = "default";
573
+ const INSTALLED_INDEX_FILE = "installed-index.json";
574
+ const REGISTRY_CACHE_FILE = "registry-cache.json";
575
+ const REGISTRY_MANIFEST_FILE = "index.json";
576
+ //#endregion
577
+ //#region src/fonts/fontRegistryNormalization.ts
578
+ function normalizeConfig(config) {
579
+ var _config$storageNamesp;
580
+ return {
581
+ baseUrl: config === null || config === void 0 ? void 0 : config.baseUrl,
582
+ storageNamespace: sanitizeNamespace((_config$storageNamesp = config === null || config === void 0 ? void 0 : config.storageNamespace) !== null && _config$storageNamesp !== void 0 ? _config$storageNamesp : DEFAULT_STORAGE_NAMESPACE$1)
583
+ };
584
+ }
585
+ function normalizeRegistryManifest(manifest, baseUrl) {
586
+ return (Array.isArray(manifest) ? manifest : Array.isArray(manifest.fonts) ? manifest.fonts : []).map((font) => normalizeInstallableFont(font, baseUrl)).filter((font) => font !== null);
587
+ }
588
+ function normalizeInstallableFont(value, baseUrl) {
589
+ if (!value || typeof value !== "object") return null;
590
+ const font = value;
591
+ if (!font.id || !font.label || !font.family || !font.version || !font.fontFamilySpec || !Array.isArray(font.kinds) || !Array.isArray(font.files)) return null;
592
+ const files = font.files.map((file) => normalizeInstallableFile(file, baseUrl)).filter((file) => file !== null);
593
+ if (files.length === 0) return null;
594
+ return {
595
+ id: font.id,
596
+ label: font.label,
597
+ family: font.family,
598
+ kinds: normalizeFontKinds(font.kinds),
599
+ fontFamilySpec: normalizeFontFamilySpec(font.fontFamilySpec),
600
+ version: String(font.version),
601
+ files,
602
+ description: font.description
603
+ };
604
+ }
605
+ function normalizeInstalledFont(value, storage) {
606
+ if (!value || typeof value !== "object") return null;
607
+ const font = value;
608
+ if (!font.id || !font.label || !font.family || !font.version || !font.installedAt || !font.fontFamilySpec || !Array.isArray(font.kinds) || !Array.isArray(font.files)) return null;
609
+ const files = font.files.map((file) => normalizeInstalledFile(file, storage)).filter((file) => file !== null);
610
+ if (files.length === 0) return null;
611
+ return {
612
+ id: font.id,
613
+ label: font.label,
614
+ family: font.family,
615
+ kinds: normalizeFontKinds(font.kinds),
616
+ fontFamilySpec: normalizeFontFamilySpec(font.fontFamilySpec),
617
+ installedAt: font.installedAt,
618
+ version: font.version,
619
+ files,
620
+ description: font.description
621
+ };
622
+ }
623
+ function normalizeInstallableFile(value, baseUrl) {
624
+ var _file$url;
625
+ if (!value || typeof value !== "object") return null;
626
+ const file = value;
627
+ const rawUrl = (_file$url = file.url) !== null && _file$url !== void 0 ? _file$url : file.path;
628
+ if (!rawUrl || !file.sha256) return null;
629
+ return {
630
+ url: resolveFontFileUrl(rawUrl, baseUrl),
631
+ fileName: file.fileName,
632
+ sha256: normalizeSha256(file.sha256),
633
+ weight: file.weight,
634
+ style: file.style,
635
+ format: file.format,
636
+ unicodeRange: file.unicodeRange
637
+ };
638
+ }
639
+ function normalizeInstalledFile(value, storage) {
640
+ const file = normalizeInstalledFontFileRecord(value, {
641
+ storageRootUri: storage.rootDir,
642
+ storageNamespace: storage.config.storageNamespace
643
+ });
644
+ if (!file) return null;
645
+ return {
646
+ uri: file.uri,
647
+ relativePath: file.relativePath,
648
+ fileName: file.fileName,
649
+ sha256: normalizeSha256(file.sha256),
650
+ weight: file.weight,
651
+ style: file.style,
652
+ format: file.format,
653
+ unicodeRange: file.unicodeRange
654
+ };
655
+ }
656
+ function normalizeFontFamilySpec(value) {
657
+ return {
658
+ family: value.family,
659
+ fallbacks: value.fallbacks
660
+ };
661
+ }
662
+ function normalizeFontKinds(kinds) {
663
+ const normalized = kinds.filter((kind) => kind === "heading" || kind === "body" || kind === "code");
664
+ return normalized.length > 0 ? normalized : ["body"];
665
+ }
666
+ function resolveRegistryManifestUrl(baseUrl) {
667
+ if (!baseUrl) throw new Error("fontRegistry.baseUrl is required to refresh fonts");
668
+ if (/\.json(?:[?#].*)?$/i.test(baseUrl)) return baseUrl;
669
+ return new URL(REGISTRY_MANIFEST_FILE, ensureTrailingSlash$2(baseUrl)).toString();
670
+ }
671
+ function resolveFontFileUrl(rawUrl, baseUrl) {
672
+ if (/^[a-z][a-z\d+.-]*:/i.test(rawUrl)) return rawUrl;
673
+ if (!baseUrl) throw new Error(`Relative font file URL requires fontRegistry.baseUrl: ${rawUrl}`);
674
+ return new URL(rawUrl, resolveFontAssetBaseUrl(baseUrl)).toString();
675
+ }
676
+ function resolveFontAssetBaseUrl(baseUrl) {
677
+ if (/\.json(?:[?#].*)?$/i.test(baseUrl)) return new URL(".", baseUrl).toString();
678
+ return ensureTrailingSlash$2(baseUrl);
679
+ }
680
+ function safeFileName(value) {
681
+ var _value$split$filter$p;
682
+ const safe = ((_value$split$filter$p = value.split(/[/?#]/).filter(Boolean).pop()) !== null && _value$split$filter$p !== void 0 ? _value$split$filter$p : "font").replace(/[^A-Za-z0-9._-]/g, "-");
683
+ return safe.length > 0 ? safe : "font";
684
+ }
685
+ function sanitizeNamespace(value) {
686
+ const safe = value.trim().replace(/[^A-Za-z0-9._-]/g, "-");
687
+ return safe.length > 0 ? safe : DEFAULT_STORAGE_NAMESPACE$1;
688
+ }
689
+ function ensureTrailingSlash$2(value) {
690
+ return value.endsWith("/") ? value : `${value}/`;
691
+ }
692
+ function normalizeSha256(value) {
693
+ return value.toLowerCase().replace(/^sha256[:-]/, "");
694
+ }
695
+ //#endregion
696
+ //#region src/fonts/fontRegistryTransfer.ts
697
+ async function fetchFontPayload(url, onProgress) {
698
+ if (typeof XMLHttpRequest !== "undefined") return fetchFontPayloadWithXhr(url, onProgress);
699
+ const response = await fetch(url);
700
+ if (!response.ok) throw new Error(`Font file download failed with HTTP ${response.status}: ${url}`);
701
+ const payload = new Uint8Array(await response.arrayBuffer());
702
+ onProgress === null || onProgress === void 0 || onProgress(payload.byteLength, payload.byteLength);
703
+ return payload;
704
+ }
705
+ function fetchFontPayloadWithXhr(url, onProgress) {
706
+ return new Promise((resolve, reject) => {
707
+ const request = new XMLHttpRequest();
708
+ request.open("GET", url);
709
+ request.responseType = "arraybuffer";
710
+ request.onprogress = (event) => {
711
+ onProgress === null || onProgress === void 0 || onProgress(event.loaded, event.lengthComputable ? event.total : void 0);
712
+ };
713
+ request.onerror = () => {
714
+ reject(/* @__PURE__ */ new Error(`Font file download failed: ${url}`));
715
+ };
716
+ request.onload = () => {
717
+ if (request.status < 200 || request.status >= 300) {
718
+ reject(/* @__PURE__ */ new Error(`Font file download failed with HTTP ${request.status}: ${url}`));
719
+ return;
720
+ }
721
+ if (!(request.response instanceof ArrayBuffer)) {
722
+ reject(/* @__PURE__ */ new Error(`Font file download did not return binary data: ${url}`));
723
+ return;
724
+ }
725
+ const payload = new Uint8Array(request.response);
726
+ onProgress === null || onProgress === void 0 || onProgress(payload.byteLength, payload.byteLength);
727
+ resolve(payload);
728
+ };
729
+ request.send();
730
+ });
731
+ }
732
+ async function sha256Bytes(bytes) {
733
+ const buffer = new ArrayBuffer(bytes.byteLength);
734
+ const data = new Uint8Array(buffer);
735
+ data.set(bytes);
736
+ return arrayBufferToHex(await expo_crypto.digest(expo_crypto.CryptoDigestAlgorithm.SHA256, data));
737
+ }
738
+ function totalKnownBytes(files) {
739
+ if (!files.every((file) => typeof file.size === "number")) return;
740
+ return files.reduce((sum, file) => {
741
+ var _file$size;
742
+ return sum + ((_file$size = file.size) !== null && _file$size !== void 0 ? _file$size : 0);
743
+ }, 0);
744
+ }
745
+ function overallProgress(fileIndex, fileCount, installedBytes, fileReceivedBytes, fileTotalBytes, totalBytes, phase) {
746
+ if (totalBytes && totalBytes > 0) return clampRatio((installedBytes + (fileReceivedBytes !== null && fileReceivedBytes !== void 0 ? fileReceivedBytes : 0)) / totalBytes);
747
+ return clampRatio((fileIndex - 1 + (fileTotalBytes && fileTotalBytes > 0 ? clampRatio((fileReceivedBytes !== null && fileReceivedBytes !== void 0 ? fileReceivedBytes : 0) / fileTotalBytes) : phase === "complete" ? 1 : 0)) / fileCount);
748
+ }
749
+ function progressBytes(fileReceivedBytes, fileTotalBytes) {
750
+ if (fileReceivedBytes === void 0) return 0;
751
+ if (fileTotalBytes === void 0) return fileReceivedBytes;
752
+ return Math.min(fileReceivedBytes, fileTotalBytes);
753
+ }
754
+ function clampRatio(value) {
755
+ return Math.max(0, Math.min(1, value));
756
+ }
757
+ function bytesToBase64(bytes) {
758
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
759
+ let output = "";
760
+ for (let index = 0; index < bytes.length; index += 3) {
761
+ const first = bytes[index];
762
+ const second = bytes[index + 1];
763
+ const third = bytes[index + 2];
764
+ output += alphabet[first >> 2];
765
+ output += alphabet[(first & 3) << 4 | (second !== null && second !== void 0 ? second : 0) >> 4];
766
+ output += second === void 0 ? "=" : alphabet[(second & 15) << 2 | (third !== null && third !== void 0 ? third : 0) >> 6];
767
+ output += third === void 0 ? "=" : alphabet[third & 63];
768
+ }
769
+ return output;
770
+ }
771
+ function arrayBufferToHex(buffer) {
772
+ return Array.from(new Uint8Array(buffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
773
+ }
774
+ //#endregion
775
+ //#region src/fonts/fontRegistry.ts
776
+ const expoFontRegistryStoragePort = {
777
+ get documentDirectory() {
778
+ return expo_file_system_legacy.documentDirectory;
779
+ },
780
+ getInfo(uri) {
781
+ return expo_file_system_legacy.getInfoAsync(uri);
782
+ },
783
+ readString(uri, options) {
784
+ return expo_file_system_legacy.readAsStringAsync(uri, toExpoStringOptions(options));
785
+ },
786
+ writeString(uri, value, options) {
787
+ return expo_file_system_legacy.writeAsStringAsync(uri, value, toExpoStringOptions(options));
788
+ },
789
+ makeDirectory(uri, options) {
790
+ return expo_file_system_legacy.makeDirectoryAsync(uri, options);
791
+ },
792
+ delete(uri, options) {
793
+ return expo_file_system_legacy.deleteAsync(uri, options);
794
+ }
795
+ };
796
+ function toExpoStringOptions(options) {
797
+ return (options === null || options === void 0 ? void 0 : options.encoding) === "base64" ? { encoding: expo_file_system_legacy.EncodingType.Base64 } : void 0;
798
+ }
799
+ async function listInstalledFonts(config) {
800
+ return readInstalledIndex(requireStorage(config, expoFontRegistryStoragePort), expoFontRegistryStoragePort);
801
+ }
802
+ async function listInstallableFonts(config) {
803
+ const storage = requireStorage(config, expoFontRegistryStoragePort);
804
+ const [installedFonts, cachedFonts] = await Promise.all([readInstalledIndex(storage, expoFontRegistryStoragePort), readRegistryCache(storage, expoFontRegistryStoragePort)]);
805
+ const installedIds = new Set(installedFonts.map((font) => font.id));
806
+ return cachedFonts.filter((font) => !installedIds.has(font.id));
807
+ }
808
+ async function refreshFontRegistry(config) {
809
+ const storage = requireStorage(config, expoFontRegistryStoragePort);
810
+ await ensureDirectoryEntry(expoFontRegistryStoragePort, storage.rootDir);
811
+ const manifestUrl = resolveRegistryManifestUrl(storage.config.baseUrl);
812
+ const response = await fetch(manifestUrl);
813
+ if (!response.ok) throw new Error(`Font registry refresh failed with HTTP ${response.status}: ${manifestUrl}`);
814
+ const manifest = normalizeRegistryManifest(await response.json(), storage.config.baseUrl);
815
+ await writeJsonEntry(expoFontRegistryStoragePort, storage.registryCacheUri, {
816
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
817
+ fonts: manifest
818
+ });
819
+ const installedFonts = await readInstalledIndex(storage, expoFontRegistryStoragePort);
820
+ const installedIds = new Set(installedFonts.map((font) => font.id));
821
+ return manifest.filter((font) => !installedIds.has(font.id));
822
+ }
823
+ async function installFont(fontId, config, options) {
824
+ const storage = requireStorage(config, expoFontRegistryStoragePort);
825
+ const font = (await readRegistryCache(storage, expoFontRegistryStoragePort)).find((entry) => entry.id === fontId);
826
+ if (!font) throw new Error(`Font is not available in the local registry cache: ${fontId}`);
827
+ const installedFonts = await readInstalledIndex(storage, expoFontRegistryStoragePort);
828
+ const existing = installedFonts.find((entry) => entry.id === fontId);
829
+ if (existing && existing.version === font.version) return existing;
830
+ const fontRelativeDir = buildFontRelativeDir(font.id);
831
+ const fontDir = `${storage.rootDir}${fontRelativeDir}`;
832
+ await ensureDirectoryEntry(expoFontRegistryStoragePort, fontDir);
833
+ const installedFiles = [];
834
+ const totalBytes = totalKnownBytes(font.files);
835
+ let installedBytes = 0;
836
+ for (const [fileOffset, file] of font.files.entries()) {
837
+ var _file$fileName;
838
+ const fileName = safeFileName((_file$fileName = file.fileName) !== null && _file$fileName !== void 0 ? _file$fileName : file.url);
839
+ const fileIndex = fileOffset + 1;
840
+ const relativePath = buildFontRelativePath(font.id, fileName);
841
+ const destination = `${fontDir}${fileName}`;
842
+ const reportProgress = (phase, fileReceivedBytes, fileTotalBytes) => {
843
+ var _options$onProgress;
844
+ options === null || options === void 0 || (_options$onProgress = options.onProgress) === null || _options$onProgress === void 0 || _options$onProgress.call(options, {
845
+ fontId: font.id,
846
+ fontLabel: font.label,
847
+ fileIndex,
848
+ fileCount: font.files.length,
849
+ fileName,
850
+ fileUrl: file.url,
851
+ phase,
852
+ fileReceivedBytes,
853
+ fileTotalBytes: fileTotalBytes !== null && fileTotalBytes !== void 0 ? fileTotalBytes : file.size,
854
+ installedBytes: installedBytes + progressBytes(fileReceivedBytes, fileTotalBytes !== null && fileTotalBytes !== void 0 ? fileTotalBytes : file.size),
855
+ totalBytes,
856
+ overallProgress: overallProgress(fileIndex, font.files.length, installedBytes, fileReceivedBytes, fileTotalBytes !== null && fileTotalBytes !== void 0 ? fileTotalBytes : file.size, totalBytes, phase)
857
+ });
858
+ };
859
+ const payload = await fetchFontPayload(file.url, (receivedBytes, totalFileBytes) => {
860
+ reportProgress("download", receivedBytes, totalFileBytes);
861
+ });
862
+ reportProgress("verify", payload.byteLength, payload.byteLength);
863
+ const actualSha256 = await sha256Bytes(payload);
864
+ const expectedSha256 = normalizeSha256(file.sha256);
865
+ if (actualSha256 !== expectedSha256) throw new Error(`Font file checksum mismatch for ${font.id}/${fileName}: expected ${expectedSha256}, got ${actualSha256}`);
866
+ reportProgress("write", payload.byteLength, payload.byteLength);
867
+ await expoFontRegistryStoragePort.writeString(destination, bytesToBase64(payload), { encoding: "base64" });
868
+ if (!(await expoFontRegistryStoragePort.getInfo(destination)).exists) throw new Error(`Font file write failed for ${font.id}/${fileName}: ${destination}`);
869
+ installedFiles.push({
870
+ fileName,
871
+ uri: destination,
872
+ relativePath,
873
+ sha256: expectedSha256,
874
+ weight: file.weight,
875
+ style: file.style,
876
+ format: file.format,
877
+ unicodeRange: file.unicodeRange
878
+ });
879
+ reportProgress("complete", payload.byteLength, payload.byteLength);
880
+ installedBytes += payload.byteLength;
881
+ }
882
+ const installedFont = {
883
+ id: font.id,
884
+ label: font.label,
885
+ family: font.family,
886
+ kinds: font.kinds,
887
+ fontFamilySpec: font.fontFamilySpec,
888
+ installedAt: (/* @__PURE__ */ new Date()).toISOString(),
889
+ version: font.version,
890
+ files: installedFiles,
891
+ description: font.description
892
+ };
893
+ await writeInstalledIndex(storage, expoFontRegistryStoragePort, [...installedFonts.filter((entry) => entry.id !== font.id), installedFont].sort((a, b) => a.label.localeCompare(b.label)));
894
+ return installedFont;
895
+ }
896
+ async function uninstallFont(fontId, config) {
897
+ const storage = requireStorage(config, expoFontRegistryStoragePort);
898
+ const installedFonts = await readInstalledIndex(storage, expoFontRegistryStoragePort);
899
+ const nextInstalledFonts = installedFonts.filter((font) => font.id !== fontId);
900
+ if (nextInstalledFonts.length === installedFonts.length) return;
901
+ await writeInstalledIndex(storage, expoFontRegistryStoragePort, nextInstalledFonts);
902
+ await deleteEntryIfExists(expoFontRegistryStoragePort, `${storage.filesDir}${encodeURIComponent(fontId)}/`);
903
+ }
904
+ async function buildInstalledFontFaceCss(installedFonts, selectedFontSpecs) {
905
+ return buildInstalledFontFaceCssRules(installedFonts, selectedFontSpecs, (file) => expoFontRegistryStoragePort.readString(file.uri, { encoding: "base64" }));
906
+ }
907
+ function requireStorage(config, port = expoFontRegistryStoragePort) {
908
+ const documentDirectory = port.documentDirectory;
909
+ if (!documentDirectory) throw new Error("Expo FileSystem documentDirectory is not available");
910
+ const normalizedConfig = normalizeConfig(config);
911
+ const rootDir = `${ensureTrailingSlash$2(documentDirectory)}${VENDOR_STORAGE_DIR}/${normalizedConfig.storageNamespace}/`;
912
+ return {
913
+ config: normalizedConfig,
914
+ rootDir,
915
+ installedIndexUri: `${rootDir}${INSTALLED_INDEX_FILE}`,
916
+ registryCacheUri: `${rootDir}${REGISTRY_CACHE_FILE}`,
917
+ filesDir: `${rootDir}${FONT_FILES_DIR}/`
918
+ };
919
+ }
920
+ async function readInstalledIndex(storage, port) {
921
+ return readPrunedIndexEntries({
922
+ port,
923
+ indexUri: storage.installedIndexUri,
924
+ getRawEntries(index) {
925
+ const parsed = index;
926
+ return Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.fonts) ? parsed.fonts : [];
927
+ },
928
+ normalizeEntry: (font) => normalizeInstalledFont(font, storage),
929
+ entryExists: (font) => installedFontFilesExist(font, port),
930
+ entryNeedsRewrite: installedFontIndexEntryNeedsRewrite,
931
+ serializeIndex(fonts) {
932
+ return { fonts: fonts.map(serializeInstalledFontForIndex) };
933
+ }
934
+ });
935
+ }
936
+ async function writeInstalledIndex(storage, port, fonts) {
937
+ await ensureDirectoryEntry(port, storage.rootDir);
938
+ await writeJsonEntry(port, storage.installedIndexUri, { fonts: fonts.map(serializeInstalledFontForIndex) });
939
+ }
940
+ async function readRegistryCache(storage, port) {
941
+ const parsed = await readJsonEntry(port, storage.registryCacheUri);
942
+ return (Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.fonts) ? parsed.fonts : []).map((font) => normalizeInstallableFont(font, storage.config.baseUrl)).filter((font) => font !== null);
943
+ }
944
+ async function installedFontFilesExist(font, port) {
945
+ return (await Promise.all(font.files.map((file) => fileEntryExists(port, file.uri)))).every(Boolean);
946
+ }
947
+ //#endregion
948
+ //#region src/provider/providerFonts.tsx
949
+ function useProviderFonts(fontRegistry) {
950
+ const [installedFonts, setInstalledFonts] = (0, react.useState)([]);
951
+ const [installableFonts, setInstallableFonts] = (0, react.useState)([]);
952
+ const [fontRegistryLoading, setFontRegistryLoading] = (0, react.useState)(false);
953
+ const [fontRegistryError, setFontRegistryError] = (0, react.useState)(null);
954
+ const reloadFontRegistryState = (0, react.useCallback)(async () => {
955
+ setFontRegistryLoading(true);
956
+ setFontRegistryError(null);
957
+ try {
958
+ const [nextInstalledFonts, nextInstallableFonts] = await Promise.all([listInstalledFonts(fontRegistry), listInstallableFonts(fontRegistry)]);
959
+ setInstalledFonts(nextInstalledFonts);
960
+ setInstallableFonts(nextInstallableFonts);
961
+ return {
962
+ installedFonts: nextInstalledFonts,
963
+ installableFonts: nextInstallableFonts
964
+ };
965
+ } catch (error) {
966
+ setFontRegistryError(error);
967
+ throw error;
968
+ } finally {
969
+ setFontRegistryLoading(false);
970
+ }
971
+ }, [fontRegistry]);
972
+ const listInstalledFontsForProvider = (0, react.useCallback)(async () => {
973
+ const nextInstalledFonts = await listInstalledFonts(fontRegistry);
974
+ setInstalledFonts(nextInstalledFonts);
975
+ return nextInstalledFonts;
976
+ }, [fontRegistry]);
977
+ const listInstallableFontsForProvider = (0, react.useCallback)(async () => {
978
+ const nextInstallableFonts = await listInstallableFonts(fontRegistry);
979
+ setInstallableFonts(nextInstallableFonts);
980
+ return nextInstallableFonts;
981
+ }, [fontRegistry]);
982
+ const refreshFontRegistryForProvider = (0, react.useCallback)(async () => {
983
+ setFontRegistryLoading(true);
984
+ setFontRegistryError(null);
985
+ try {
986
+ const nextInstallableFonts = await refreshFontRegistry(fontRegistry);
987
+ setInstalledFonts(await listInstalledFonts(fontRegistry));
988
+ setInstallableFonts(nextInstallableFonts);
989
+ return nextInstallableFonts;
990
+ } catch (error) {
991
+ setFontRegistryError(error);
992
+ throw error;
993
+ } finally {
994
+ setFontRegistryLoading(false);
995
+ }
996
+ }, [fontRegistry]);
997
+ const installFontForProvider = (0, react.useCallback)(async (fontId, options) => {
998
+ setFontRegistryLoading(true);
999
+ setFontRegistryError(null);
1000
+ try {
1001
+ const installedFont = await installFont(fontId, fontRegistry, options);
1002
+ await reloadFontRegistryState();
1003
+ return installedFont;
1004
+ } catch (error) {
1005
+ setFontRegistryError(error);
1006
+ throw error;
1007
+ } finally {
1008
+ setFontRegistryLoading(false);
1009
+ }
1010
+ }, [fontRegistry, reloadFontRegistryState]);
1011
+ const uninstallFontForProvider = (0, react.useCallback)(async (fontId) => {
1012
+ setFontRegistryLoading(true);
1013
+ setFontRegistryError(null);
1014
+ try {
1015
+ await uninstallFont(fontId, fontRegistry);
1016
+ await reloadFontRegistryState();
1017
+ } catch (error) {
1018
+ setFontRegistryError(error);
1019
+ throw error;
1020
+ } finally {
1021
+ setFontRegistryLoading(false);
1022
+ }
1023
+ }, [fontRegistry, reloadFontRegistryState]);
1024
+ return {
1025
+ fontRegistryState: (0, react.useMemo)(() => ({
1026
+ installedFonts,
1027
+ installableFonts,
1028
+ isLoading: fontRegistryLoading,
1029
+ error: fontRegistryError,
1030
+ listInstalledFonts: listInstalledFontsForProvider,
1031
+ listInstallableFonts: listInstallableFontsForProvider,
1032
+ refreshFontRegistry: refreshFontRegistryForProvider,
1033
+ installFont: installFontForProvider,
1034
+ uninstallFont: uninstallFontForProvider
1035
+ }), [
1036
+ fontRegistryError,
1037
+ fontRegistryLoading,
1038
+ installFontForProvider,
1039
+ installableFonts,
1040
+ installedFonts,
1041
+ listInstallableFontsForProvider,
1042
+ listInstalledFontsForProvider,
1043
+ refreshFontRegistryForProvider,
1044
+ uninstallFontForProvider
1045
+ ]),
1046
+ installedFonts,
1047
+ setInstalledFonts,
1048
+ setInstallableFonts,
1049
+ setFontRegistryLoading,
1050
+ setFontRegistryError
1051
+ };
1052
+ }
1053
+ function useInitializeProviderFonts(fontRegistry, { setInstalledFonts, setInstallableFonts, setFontRegistryLoading, setFontRegistryError }) {
1054
+ (0, react.useEffect)(() => {
1055
+ let cancelled = false;
1056
+ setFontRegistryLoading(true);
1057
+ setFontRegistryError(null);
1058
+ Promise.all([listInstalledFonts(fontRegistry), listInstallableFonts(fontRegistry)]).then(([nextInstalledFonts, nextInstallableFonts]) => {
1059
+ if (cancelled) return;
1060
+ setInstalledFonts(nextInstalledFonts);
1061
+ setInstallableFonts(nextInstallableFonts);
1062
+ }).catch((error) => {
1063
+ if (!cancelled) setFontRegistryError(error);
1064
+ }).finally(() => {
1065
+ if (!cancelled) setFontRegistryLoading(false);
1066
+ });
1067
+ return () => {
1068
+ cancelled = true;
1069
+ };
1070
+ }, [
1071
+ fontRegistry,
1072
+ setFontRegistryError,
1073
+ setFontRegistryLoading,
1074
+ setInstallableFonts,
1075
+ setInstalledFonts
1076
+ ]);
1077
+ }
1078
+ //#endregion
1079
+ //#region src/provider/measurementStyleSource.ts
1080
+ const measurementStyleSource = ` var LENGTH_PROPS = {
1081
+ fontSize: true,
1082
+ lineHeight: true,
1083
+ letterSpacing: true,
1084
+ width: true,
1085
+ maxWidth: true,
1086
+ minWidth: true,
1087
+ height: true,
1088
+ maxHeight: true,
1089
+ minHeight: true,
1090
+ padding: true,
1091
+ paddingTop: true,
1092
+ paddingRight: true,
1093
+ paddingBottom: true,
1094
+ paddingLeft: true,
1095
+ margin: true,
1096
+ marginTop: true,
1097
+ marginRight: true,
1098
+ marginBottom: true,
1099
+ marginLeft: true
1100
+ };
1101
+
1102
+ function cssValue(property, value) {
1103
+ if (value == null) {
1104
+ return "";
1105
+ }
1106
+ if (typeof value === "number" && LENGTH_PROPS[property]) {
1107
+ return value + "px";
1108
+ }
1109
+ return String(value);
1110
+ }
1111
+
1112
+ function applyStyle(element, style) {
1113
+ if (!style) {
1114
+ return;
1115
+ }
1116
+ Object.keys(style).forEach(function(property) {
1117
+ var value = cssValue(property, style[property]);
1118
+ if (value) {
1119
+ element.style[property] = value;
1120
+ }
1121
+ });
1122
+ }
1123
+
1124
+ function svgTextAttributeName(property) {
1125
+ switch (property) {
1126
+ case "fontFamily":
1127
+ return "font-family";
1128
+ case "fontSize":
1129
+ return "font-size";
1130
+ case "fontWeight":
1131
+ return "font-weight";
1132
+ case "fontStyle":
1133
+ return "font-style";
1134
+ case "letterSpacing":
1135
+ return "letter-spacing";
1136
+ case "textDecorationLine":
1137
+ return "text-decoration";
1138
+ default:
1139
+ return null;
1140
+ }
1141
+ }
1142
+
1143
+ function applySvgTextStyle(element, style) {
1144
+ applyStyle(element, style);
1145
+ if (!style) {
1146
+ return;
1147
+ }
1148
+ Object.keys(style).forEach(function(property) {
1149
+ var attr = svgTextAttributeName(property);
1150
+ if (!attr) {
1151
+ return;
1152
+ }
1153
+ var value = cssValue(property, style[property]);
1154
+ if (value) {
1155
+ element.setAttribute(attr, value);
1156
+ }
1157
+ });
1158
+ }
1159
+
1160
+ function mergedTextStyle(base, override) {
1161
+ var style = {};
1162
+ if (base) {
1163
+ Object.keys(base).forEach(function(property) {
1164
+ style[property] = base[property];
1165
+ });
1166
+ }
1167
+ if (override) {
1168
+ Object.keys(override).forEach(function(property) {
1169
+ style[property] = override[property];
1170
+ });
1171
+ }
1172
+ return style;
1173
+ }
1174
+
1175
+ `;
1176
+ //#endregion
1177
+ //#region src/provider/measurementFontSource.ts
1178
+ const measurementFontSource = ` function finiteNumber(value, fallback) {
1179
+ var number = typeof value === "number" ? value : Number(value);
1180
+ return Number.isFinite(number) ? number : fallback;
1181
+ }
1182
+
1183
+ function safeDimension(value) {
1184
+ return Math.max(0, finiteNumber(value, 0));
1185
+ }
1186
+
1187
+ function safeCoordinate(value) {
1188
+ return finiteNumber(value, 0);
1189
+ }
1190
+
1191
+ function requestId(request) {
1192
+ if (request && request.id != null) {
1193
+ return String(request.id);
1194
+ }
1195
+ return "";
1196
+ }
1197
+
1198
+ function requestText(request) {
1199
+ if (request && request.text != null) {
1200
+ return String(request.text);
1201
+ }
1202
+ return "";
1203
+ }
1204
+
1205
+ function copyRequestTextStyle(request) {
1206
+ var requestStyle = {};
1207
+ if (request && request.style) {
1208
+ Object.keys(request.style).forEach(function(property) {
1209
+ requestStyle[property] = request.style[property];
1210
+ });
1211
+ }
1212
+ if (request && request.fontFamily != null) {
1213
+ requestStyle.fontFamily = request.fontFamily;
1214
+ }
1215
+ if (request && request.fontSize != null) {
1216
+ requestStyle.fontSize = request.fontSize;
1217
+ }
1218
+ if (request && request.fontWeight != null) {
1219
+ requestStyle.fontWeight = request.fontWeight;
1220
+ }
1221
+ if (request && request.fontStyle != null) {
1222
+ requestStyle.fontStyle = request.fontStyle;
1223
+ }
1224
+ return requestStyle;
1225
+ }
1226
+
1227
+ function fontLoadStyle(style) {
1228
+ if (!style || style.fontFamily == null) {
1229
+ return null;
1230
+ }
1231
+ var fontSize = safeDimension(firstDefined(style.fontSize, 16));
1232
+ if (fontSize <= 0) {
1233
+ fontSize = 16;
1234
+ }
1235
+ var fontStyle = style.fontStyle != null ? String(style.fontStyle) : "normal";
1236
+ var fontWeight = style.fontWeight != null ? String(style.fontWeight) : "normal";
1237
+ return fontStyle + " " + fontWeight + " " + fontSize + "px " + String(style.fontFamily);
1238
+ }
1239
+
1240
+ function collectFontLoadRequests(request, output) {
1241
+ var requestStyle = copyRequestTextStyle(request);
1242
+ var requestFont = fontLoadStyle(requestStyle);
1243
+ if (requestFont) {
1244
+ output.push({
1245
+ font: requestFont,
1246
+ text: requestText(request)
1247
+ });
1248
+ }
1249
+ if (request && Array.isArray(request.runs)) {
1250
+ request.runs.forEach(function(run) {
1251
+ var runStyle = mergedTextStyle(requestStyle, run && run.style);
1252
+ var runFont = fontLoadStyle(runStyle);
1253
+ if (runFont) {
1254
+ output.push({
1255
+ font: runFont,
1256
+ text: run && run.text != null ? String(run.text) : ""
1257
+ });
1258
+ }
1259
+ });
1260
+ }
1261
+ }
1262
+
1263
+ function waitForFonts(requests) {
1264
+ if (!document.fonts) {
1265
+ return Promise.resolve();
1266
+ }
1267
+ var loads = [];
1268
+ var seen = {};
1269
+ var fontRequests = [];
1270
+ requests.forEach(function(request) {
1271
+ collectFontLoadRequests(request, fontRequests);
1272
+ });
1273
+ fontRequests.forEach(function(fontRequest) {
1274
+ var key = fontRequest.font + "\\n" + fontRequest.text;
1275
+ if (seen[key]) {
1276
+ return;
1277
+ }
1278
+ seen[key] = true;
1279
+ if (document.fonts.load) {
1280
+ loads.push(
1281
+ document.fonts.load(fontRequest.font, fontRequest.text || "A")
1282
+ .catch(function() {
1283
+ return [];
1284
+ })
1285
+ );
1286
+ }
1287
+ });
1288
+ if (document.fonts.ready) {
1289
+ loads.push(
1290
+ document.fonts.ready.catch(function() {
1291
+ return document.fonts;
1292
+ })
1293
+ );
1294
+ }
1295
+ return Promise.all(loads).then(function() {
1296
+ return undefined;
1297
+ });
1298
+ }
1299
+
1300
+ function firstDefined(primary, secondary) {
1301
+ return primary != null ? primary : secondary;
1302
+ }
1303
+
1304
+ function normalizedWrapMode(request, fallback) {
1305
+ var value = request && request.wrapMode != null
1306
+ ? request.wrapMode
1307
+ : fallback;
1308
+ return String(value || "")
1309
+ .trim()
1310
+ .toLowerCase()
1311
+ .replace(/_/g, "-")
1312
+ .replace(/\\s+/g, "-");
1313
+ }
1314
+
1315
+ function applyWrapMode(element, request, fallback) {
1316
+ var mode = normalizedWrapMode(request, fallback);
1317
+ switch (mode) {
1318
+ case "none":
1319
+ case "no-wrap":
1320
+ case "nowrap":
1321
+ element.style.whiteSpace = "pre";
1322
+ element.style.overflowWrap = "normal";
1323
+ element.style.wordBreak = "normal";
1324
+ return;
1325
+ case "normal":
1326
+ element.style.whiteSpace = "normal";
1327
+ element.style.overflowWrap = "normal";
1328
+ element.style.wordBreak = "normal";
1329
+ return;
1330
+ case "pre":
1331
+ element.style.whiteSpace = "pre";
1332
+ element.style.overflowWrap = "normal";
1333
+ element.style.wordBreak = "normal";
1334
+ return;
1335
+ case "pre-line":
1336
+ element.style.whiteSpace = "pre-line";
1337
+ element.style.overflowWrap = "break-word";
1338
+ element.style.wordBreak = "normal";
1339
+ return;
1340
+ case "anywhere":
1341
+ element.style.whiteSpace = "pre-wrap";
1342
+ element.style.overflowWrap = "anywhere";
1343
+ element.style.wordBreak = "break-word";
1344
+ return;
1345
+ case "break-word":
1346
+ case "breakword":
1347
+ element.style.whiteSpace = "pre-wrap";
1348
+ element.style.overflowWrap = "break-word";
1349
+ element.style.wordBreak = "normal";
1350
+ return;
1351
+ case "pre-wrap":
1352
+ case "preserve":
1353
+ default:
1354
+ element.style.whiteSpace = "pre-wrap";
1355
+ element.style.overflowWrap = "break-word";
1356
+ element.style.wordBreak = "normal";
1357
+ return;
1358
+ }
1359
+ }
1360
+
1361
+ `;
1362
+ //#endregion
1363
+ //#region src/provider/measurementResultSource.ts
1364
+ const measurementResultSource = ` function fallbackMeasurementResult(request) {
1365
+ return {
1366
+ id: requestId(request),
1367
+ width: 0,
1368
+ height: 0,
1369
+ lineCount: 0
1370
+ };
1371
+ }
1372
+
1373
+ function sanitizeRect(rect) {
1374
+ return {
1375
+ x: safeCoordinate(rect && rect.x),
1376
+ y: safeCoordinate(rect && rect.y),
1377
+ width: safeDimension(rect && rect.width),
1378
+ height: safeDimension(rect && rect.height)
1379
+ };
1380
+ }
1381
+
1382
+ function sanitizeMeasurementResult(result, request) {
1383
+ if (!result) {
1384
+ return fallbackMeasurementResult(request);
1385
+ }
1386
+ var sanitized = {
1387
+ id: result.id != null ? String(result.id) : requestId(request),
1388
+ width: safeDimension(result.width),
1389
+ height: safeDimension(result.height),
1390
+ lineCount: Math.max(0, Math.round(finiteNumber(result.lineCount, 0)))
1391
+ };
1392
+ if (result.left != null) {
1393
+ sanitized.left = safeCoordinate(result.left);
1394
+ }
1395
+ if (result.right != null) {
1396
+ sanitized.right = safeCoordinate(result.right);
1397
+ }
1398
+ if (result.rawWidth != null) {
1399
+ sanitized.rawWidth = safeDimension(result.rawWidth);
1400
+ }
1401
+ if (Array.isArray(result.runs)) {
1402
+ sanitized.runs = result.runs.map(function(run, index) {
1403
+ var rects = Array.isArray(run && run.rects) ? run.rects : [];
1404
+ return {
1405
+ id: run && run.id != null ? String(run.id) : undefined,
1406
+ index: Math.max(0, Math.round(finiteNumber(run && run.index, index))),
1407
+ width: safeDimension(run && run.width),
1408
+ height: safeDimension(run && run.height),
1409
+ rects: rects.map(sanitizeRect)
1410
+ };
1411
+ });
1412
+ }
1413
+ return sanitized;
1414
+ }
1415
+
1416
+ function rectToJson(rect) {
1417
+ return {
1418
+ x: rect.x,
1419
+ y: rect.y,
1420
+ width: rect.width,
1421
+ height: rect.height
1422
+ };
1423
+ }
1424
+
1425
+ function measureRun(span, run, index) {
1426
+ var rects = Array.prototype.map.call(span.getClientRects(), rectToJson);
1427
+ var bounds = span.getBoundingClientRect();
1428
+ return {
1429
+ id: run.id,
1430
+ index: index,
1431
+ width: bounds.width,
1432
+ height: bounds.height,
1433
+ rects: rects
1434
+ };
1435
+ }
1436
+
1437
+ function isPlantUmlInlineTextRequest(request) {
1438
+ return request &&
1439
+ request.engine === "plantuml" &&
1440
+ request.kind === "inlineText" &&
1441
+ request.runs &&
1442
+ request.runs.length > 0;
1443
+ }
1444
+
1445
+ function isMermaidRequest(request) {
1446
+ return request && request.engine === "mermaid";
1447
+ }
1448
+
1449
+ function svgBBox(element) {
1450
+ try {
1451
+ return element.getBBox();
1452
+ } catch (_) {
1453
+ return { x: 0, y: 0, width: 0, height: 0 };
1454
+ }
1455
+ }
1456
+
1457
+ function svgTextLength(element, fallbackWidth) {
1458
+ try {
1459
+ var length = element.getComputedTextLength();
1460
+ if (Number.isFinite(length)) {
1461
+ return length;
1462
+ }
1463
+ } catch (_) {}
1464
+ return fallbackWidth;
1465
+ }
1466
+
1467
+ function svgTextRunX(element, fallbackX) {
1468
+ try {
1469
+ var text = element.textContent || "";
1470
+ if (text.length > 0) {
1471
+ var point = element.getStartPositionOfChar(0);
1472
+ if (Number.isFinite(point.x)) {
1473
+ return point.x;
1474
+ }
1475
+ }
1476
+ } catch (_) {}
1477
+ return fallbackX;
1478
+ }
1479
+
1480
+ function createHiddenSvg() {
1481
+ var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
1482
+ svg.style.position = "absolute";
1483
+ svg.style.left = "0";
1484
+ svg.style.top = "0";
1485
+ svg.style.visibility = "hidden";
1486
+ svg.style.overflow = "visible";
1487
+ svg.setAttribute("width", "4096");
1488
+ svg.setAttribute("height", "256");
1489
+ return svg;
1490
+ }
1491
+
1492
+ function measureMermaidSvgTextRequest(request) {
1493
+ var svg = createHiddenSvg();
1494
+ var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
1495
+ text.setAttribute("x", "0");
1496
+ text.setAttribute("y", "128");
1497
+ text.textContent = requestText(request);
1498
+
1499
+ var requestStyle = copyRequestTextStyle(request);
1500
+ applySvgTextStyle(svg, requestStyle);
1501
+ applySvgTextStyle(text, requestStyle);
1502
+
1503
+ svg.appendChild(text);
1504
+ document.body.appendChild(svg);
1505
+
1506
+ var box = svgBBox(text);
1507
+ var computedLength = svgTextLength(text, box.width);
1508
+ document.body.removeChild(svg);
1509
+
1510
+ var left = Math.max(0, -safeCoordinate(box.x));
1511
+ var width = safeDimension(box.width);
1512
+ var result = {
1513
+ id: requestId(request),
1514
+ width: width,
1515
+ height: safeDimension(box.height),
1516
+ lineCount: 1,
1517
+ left: left,
1518
+ right: Math.max(0, safeCoordinate(box.x) + width)
1519
+ };
1520
+
1521
+ if (request.kind === "svgComputedLength") {
1522
+ result.width = safeDimension(computedLength);
1523
+ result.rawWidth = result.width;
1524
+ result.left = 0;
1525
+ result.right = result.width;
1526
+ } else {
1527
+ result.rawWidth = safeDimension(computedLength);
1528
+ }
1529
+
1530
+ return result;
1531
+ }
1532
+
1533
+ `;
1534
+ //#endregion
1535
+ //#region src/provider/measurementHtmlSource.ts
1536
+ const measurementHtmlSource = ` function appendTextContent(element, request) {
1537
+ if (request && Array.isArray(request.runs) && request.runs.length > 0) {
1538
+ request.runs.forEach(function(run) {
1539
+ var span = document.createElement("span");
1540
+ span.textContent = run && run.text != null ? String(run.text) : "";
1541
+ applyStyle(span, run && run.style);
1542
+ element.appendChild(span);
1543
+ });
1544
+ return;
1545
+ }
1546
+
1547
+ var span = document.createElement("span");
1548
+ span.textContent = requestText(request);
1549
+ element.appendChild(span);
1550
+ }
1551
+
1552
+ function contentLineCount(element) {
1553
+ var count = 0;
1554
+ Array.prototype.forEach.call(element.children, function(child) {
1555
+ count += child.getClientRects().length;
1556
+ });
1557
+ if (count === 0) {
1558
+ count = element.getClientRects().length;
1559
+ }
1560
+ return Math.max(1, count);
1561
+ }
1562
+
1563
+ function createHtmlTextMeasureElement(request, options) {
1564
+ var element = document.createElement("div");
1565
+ var requestStyle = copyRequestTextStyle(request);
1566
+ element.style.position = "absolute";
1567
+ element.style.left = "0";
1568
+ element.style.top = "0";
1569
+ element.style.visibility = "hidden";
1570
+ element.style.boxSizing = "border-box";
1571
+ element.style.display = "inline-block";
1572
+ element.style.pointerEvents = "none";
1573
+ applyStyle(element, requestStyle);
1574
+ applyWrapMode(element, request, options.wrapMode);
1575
+
1576
+ if (options.constrain) {
1577
+ var width = firstDefined(request && request.width, requestStyle.width);
1578
+ var maxWidth = firstDefined(request && request.maxWidth, requestStyle.maxWidth);
1579
+ if (width != null) {
1580
+ element.style.width = cssValue("width", width);
1581
+ } else if (maxWidth != null) {
1582
+ element.style.maxWidth = cssValue("maxWidth", maxWidth);
1583
+ }
1584
+ }
1585
+
1586
+ appendTextContent(element, request);
1587
+ return element;
1588
+ }
1589
+
1590
+ function measureHtmlText(request, options) {
1591
+ var element = createHtmlTextMeasureElement(request, options);
1592
+ document.body.appendChild(element);
1593
+ var bounds = element.getBoundingClientRect();
1594
+ var result = {
1595
+ id: requestId(request),
1596
+ width: bounds.width,
1597
+ height: bounds.height,
1598
+ lineCount: contentLineCount(element)
1599
+ };
1600
+ document.body.removeChild(element);
1601
+ return result;
1602
+ }
1603
+
1604
+ function measureHtmlRawWidth(request) {
1605
+ var element = createHtmlTextMeasureElement(request, {
1606
+ constrain: false,
1607
+ wrapMode: "none"
1608
+ });
1609
+ document.body.appendChild(element);
1610
+ var width = element.getBoundingClientRect().width;
1611
+ document.body.removeChild(element);
1612
+ return width;
1613
+ }
1614
+
1615
+ function measureMermaidHtmlTextRequest(request) {
1616
+ var kind = request && request.kind;
1617
+ var isWrapped = kind !== "text";
1618
+ var result = measureHtmlText(request, {
1619
+ constrain: isWrapped,
1620
+ wrapMode: isWrapped ? "pre-wrap" : "none"
1621
+ });
1622
+ if (kind === "wrappedRaw" || kind === "wrappedWithRawWidth") {
1623
+ result.rawWidth = measureHtmlRawWidth(request);
1624
+ }
1625
+ return result;
1626
+ }
1627
+
1628
+ function measureMermaidRequest(request) {
1629
+ switch (request && request.kind) {
1630
+ case "text":
1631
+ case "wrapped":
1632
+ case "wrappedRaw":
1633
+ case "wrappedWithRawWidth":
1634
+ return measureMermaidHtmlTextRequest(request);
1635
+ case "svgComputedLength":
1636
+ case "svgBBoxX":
1637
+ case "svgBBoxXAsciiOverhang":
1638
+ case "svgTitleBBoxX":
1639
+ case "svgSimpleBBoxWidth":
1640
+ case "svgSimpleBBoxHeight":
1641
+ return measureMermaidSvgTextRequest(request);
1642
+ default:
1643
+ return fallbackMeasurementResult(request);
1644
+ }
1645
+ }
1646
+
1647
+ `;
1648
+ //#endregion
1649
+ //#region src/provider/measurementDiagramSource.ts
1650
+ const measurementDiagramSource = ` function measurePlantUmlInlineTextRequest(request) {
1651
+ var svg = createHiddenSvg();
1652
+ svg.setAttribute("height", "128");
1653
+
1654
+ var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
1655
+ text.setAttribute("x", "0");
1656
+ text.setAttribute("y", "64");
1657
+
1658
+ var requestStyle = {};
1659
+ if (request.style) {
1660
+ Object.keys(request.style).forEach(function(property) {
1661
+ requestStyle[property] = request.style[property];
1662
+ });
1663
+ }
1664
+ if (request.fontFamily != null) {
1665
+ requestStyle.fontFamily = request.fontFamily;
1666
+ }
1667
+ if (request.fontSize != null) {
1668
+ requestStyle.fontSize = request.fontSize;
1669
+ }
1670
+ if (request.fontWeight != null) {
1671
+ requestStyle.fontWeight = request.fontWeight;
1672
+ }
1673
+ if (request.fontStyle != null) {
1674
+ requestStyle.fontStyle = request.fontStyle;
1675
+ }
1676
+ applySvgTextStyle(svg, requestStyle);
1677
+ applySvgTextStyle(text, requestStyle);
1678
+
1679
+ request.runs.forEach(function(run, index) {
1680
+ var tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
1681
+ if (index === 0) {
1682
+ tspan.setAttribute("x", "0");
1683
+ }
1684
+ tspan.textContent = run.text || "";
1685
+ applySvgTextStyle(tspan, run.style);
1686
+ text.appendChild(tspan);
1687
+ });
1688
+
1689
+ svg.appendChild(text);
1690
+ document.body.appendChild(svg);
1691
+
1692
+ var textBox = svgBBox(text);
1693
+ var totalWidth = svgTextLength(text, textBox.width);
1694
+ var runResults = [];
1695
+ var fallbackX = 0;
1696
+ Array.prototype.forEach.call(text.children, function(tspan, index) {
1697
+ var run = request.runs[index];
1698
+ var box = svgBBox(tspan);
1699
+ var width = svgTextLength(tspan, box.width);
1700
+ var x = svgTextRunX(tspan, fallbackX);
1701
+ runResults.push({
1702
+ id: run.id,
1703
+ index: index,
1704
+ width: width,
1705
+ height: box.height,
1706
+ rects: [{
1707
+ x: x,
1708
+ y: box.y - textBox.y,
1709
+ width: width,
1710
+ height: box.height
1711
+ }]
1712
+ });
1713
+ fallbackX += width;
1714
+ });
1715
+
1716
+ document.body.removeChild(svg);
1717
+
1718
+ return {
1719
+ id: request.id,
1720
+ width: totalWidth,
1721
+ height: textBox.height,
1722
+ lineCount: 1,
1723
+ runs: runResults
1724
+ };
1725
+ }
1726
+
1727
+ function measureRequest(request) {
1728
+ try {
1729
+ if (isPlantUmlInlineTextRequest(request)) {
1730
+ return sanitizeMeasurementResult(
1731
+ measurePlantUmlInlineTextRequest(request),
1732
+ request
1733
+ );
1734
+ }
1735
+
1736
+ if (isMermaidRequest(request)) {
1737
+ return sanitizeMeasurementResult(measureMermaidRequest(request), request);
1738
+ }
1739
+
1740
+ return sanitizeMeasurementResult(measureGenericTextRequest(request), request);
1741
+ } catch (_) {
1742
+ return fallbackMeasurementResult(request);
1743
+ }
1744
+ }
1745
+
1746
+ function measureGenericTextRequest(request) {
1747
+ var element = document.createElement("div");
1748
+ element.style.position = "absolute";
1749
+ element.style.left = "0";
1750
+ element.style.top = "0";
1751
+ element.style.visibility = "hidden";
1752
+ element.style.whiteSpace = "pre-wrap";
1753
+ element.style.boxSizing = "border-box";
1754
+ element.style.overflowWrap = "break-word";
1755
+ var requestStyle = {};
1756
+ if (request.style) {
1757
+ Object.keys(request.style).forEach(function(property) {
1758
+ requestStyle[property] = request.style[property];
1759
+ });
1760
+ }
1761
+ if (request.fontFamily != null) {
1762
+ requestStyle.fontFamily = request.fontFamily;
1763
+ }
1764
+ if (request.fontSize != null) {
1765
+ requestStyle.fontSize = request.fontSize;
1766
+ }
1767
+ if (request.fontWeight != null) {
1768
+ requestStyle.fontWeight = request.fontWeight;
1769
+ }
1770
+ if (request.fontStyle != null) {
1771
+ requestStyle.fontStyle = request.fontStyle;
1772
+ }
1773
+ applyStyle(element, requestStyle);
1774
+
1775
+ var width = request.width || requestStyle.width;
1776
+ var maxWidth = request.maxWidth || requestStyle.maxWidth;
1777
+ if (width != null) {
1778
+ element.style.width = cssValue("width", width);
1779
+ } else if (maxWidth != null) {
1780
+ element.style.maxWidth = cssValue("maxWidth", maxWidth);
1781
+ }
1782
+
1783
+ var runResults = [];
1784
+ if (request.runs && request.runs.length > 0) {
1785
+ request.runs.forEach(function(run, index) {
1786
+ var span = document.createElement("span");
1787
+ span.textContent = run.text || "";
1788
+ applyStyle(span, run.style);
1789
+ element.appendChild(span);
1790
+ });
1791
+ } else {
1792
+ element.textContent = request.text || "";
1793
+ }
1794
+
1795
+ document.body.appendChild(element);
1796
+
1797
+ if (request.runs && request.runs.length > 0) {
1798
+ Array.prototype.forEach.call(element.children, function(span, index) {
1799
+ runResults.push(measureRun(span, request.runs[index], index));
1800
+ });
1801
+ }
1802
+
1803
+ var bounds = element.getBoundingClientRect();
1804
+ var lineCount = Math.max(1, element.getClientRects().length);
1805
+ document.body.removeChild(element);
1806
+
1807
+ var result = {
1808
+ id: request.id,
1809
+ width: bounds.width,
1810
+ height: bounds.height,
1811
+ lineCount: lineCount
1812
+ };
1813
+ if (runResults.length > 0) {
1814
+ result.runs = runResults;
1815
+ }
1816
+ return result;
1817
+ }
1818
+
1819
+ `;
1820
+ //#endregion
1821
+ //#region src/provider/measurementBatchSource.ts
1822
+ function measurementBatchSource(MESSAGE_TYPE_BATCH_RESULT) {
1823
+ return ` function measureBatch(payload) {
1824
+ try {
1825
+ var requests = Array.isArray(payload.requests) ? payload.requests : [];
1826
+ waitForFonts(requests).then(function() {
1827
+ var results = requests.map(measureRequest);
1828
+ window.ReactNativeWebView.postMessage(JSON.stringify({
1829
+ type: "${MESSAGE_TYPE_BATCH_RESULT}",
1830
+ id: payload.id,
1831
+ generationId: payload.generationId,
1832
+ results: results
1833
+ }));
1834
+ }, function(error) {
1835
+ window.ReactNativeWebView.postMessage(JSON.stringify({
1836
+ type: "${MESSAGE_TYPE_BATCH_RESULT}",
1837
+ id: payload.id,
1838
+ generationId: payload.generationId,
1839
+ results: [],
1840
+ error: error && error.message ? error.message : String(error)
1841
+ }));
1842
+ });
1843
+ } catch (error) {
1844
+ window.ReactNativeWebView.postMessage(JSON.stringify({
1845
+ type: "${MESSAGE_TYPE_BATCH_RESULT}",
1846
+ id: payload.id,
1847
+ generationId: payload.generationId,
1848
+ results: [],
1849
+ error: error && error.message ? error.message : String(error)
1850
+ }));
1851
+ }
1852
+ }
1853
+
1854
+ window.__orihaMeasureTextBatch = function(payload) {
1855
+ measureBatch(payload);
1856
+ };
1857
+ `;
1858
+ }
1859
+ //#endregion
1860
+ //#region src/provider/measurementDocument.tsx
1861
+ const MESSAGE_TYPE_BATCH_RESULT = "oriha.measureTextBatchResult";
1862
+ function buildMeasureBatchScript(payload) {
1863
+ return `
1864
+ (function() {
1865
+ if (window.__orihaMeasureTextBatch) {
1866
+ window.__orihaMeasureTextBatch(${JSON.stringify(payload)});
1867
+ }
1868
+ })();
1869
+ true;`;
1870
+ }
1871
+ function buildMeasurementWebViewHtml(fontFaceCss) {
1872
+ return `<!doctype html>
1873
+ <html>
1874
+ <head>
1875
+ <meta charset="utf-8" />
1876
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1877
+ <style>
1878
+ ${fontFaceCss.replace(/<\/style/gi, "<\\/style")}
1879
+ html, body {
1880
+ margin: 0;
1881
+ padding: 0;
1882
+ background: transparent;
1883
+ }
1884
+ </style>
1885
+ </head>
1886
+ <body>
1887
+ <script>
1888
+ (function() {
1889
+ ${measurementStyleSource}${measurementFontSource}${measurementResultSource}${measurementHtmlSource}${measurementDiagramSource}${measurementBatchSource(MESSAGE_TYPE_BATCH_RESULT)} })();
1890
+ <\/script>
1891
+ </body>
1892
+ </html>`;
1893
+ }
1894
+ //#endregion
1895
+ //#region src/provider/providerMeasurement.tsx
1896
+ function logMeasurementDebug(kind, payload) {
1897
+ console.log(`[OrihaEngine] measureTextBatch ${kind}`, payload);
1898
+ }
1899
+ function useTextMeasurementBridge({ installedFonts, measurementTimeoutMs, debugMeasurementLogs, formatMessage, setFontRegistryError }) {
1900
+ const webViewRef = (0, react.useRef)(null);
1901
+ const pendingBatches = (0, react.useRef)(/* @__PURE__ */ new Map());
1902
+ const nextBatchId = (0, react.useRef)(0);
1903
+ const providerGeneration = (0, react.useRef)(0);
1904
+ const installedFontFaceCssRef = (0, react.useRef)("");
1905
+ const measurementFontFaceCssLoading = (0, react.useRef)(false);
1906
+ const measurementWebViewLoaded = (0, react.useRef)(false);
1907
+ const measurementWebViewReady = (0, react.useRef)(false);
1908
+ const [installedFontFaceCss, setInstalledFontFaceCss] = (0, react.useState)("");
1909
+ const formatMessageRef = (0, react.useRef)(formatMessage);
1910
+ (0, react.useEffect)(() => {
1911
+ formatMessageRef.current = formatMessage;
1912
+ }, [formatMessage]);
1913
+ const measurementWebViewHtml = (0, react.useMemo)(() => buildMeasurementWebViewHtml(installedFontFaceCss), [installedFontFaceCss]);
1914
+ const injectBatch = (0, react.useCallback)((batch) => {
1915
+ const webView = webViewRef.current;
1916
+ if (!webView) return;
1917
+ batch.injected = true;
1918
+ webView.injectJavaScript(buildMeasureBatchScript({
1919
+ id: batch.id,
1920
+ generationId: batch.generationId,
1921
+ requests: batch.requests
1922
+ }));
1923
+ }, []);
1924
+ const flushPendingBatches = (0, react.useCallback)(() => {
1925
+ for (const batch of pendingBatches.current.values()) if (!batch.injected) injectBatch(batch);
1926
+ }, [injectBatch]);
1927
+ (0, react.useEffect)(() => {
1928
+ installedFontFaceCssRef.current = installedFontFaceCss;
1929
+ }, [installedFontFaceCss]);
1930
+ (0, react.useEffect)(() => {
1931
+ let cancelled = false;
1932
+ measurementFontFaceCssLoading.current = true;
1933
+ measurementWebViewReady.current = false;
1934
+ const complete = (nextFontFaceCss) => {
1935
+ measurementFontFaceCssLoading.current = false;
1936
+ if (nextFontFaceCss === installedFontFaceCssRef.current) {
1937
+ if (measurementWebViewLoaded.current) {
1938
+ measurementWebViewReady.current = true;
1939
+ flushPendingBatches();
1940
+ }
1941
+ return;
1942
+ }
1943
+ measurementWebViewReady.current = false;
1944
+ setInstalledFontFaceCss(nextFontFaceCss);
1945
+ };
1946
+ buildInstalledFontFaceCss(installedFonts).then((nextFontFaceCss) => {
1947
+ if (!cancelled) complete(nextFontFaceCss);
1948
+ }).catch((error) => {
1949
+ if (!cancelled) {
1950
+ setFontRegistryError(error);
1951
+ complete("");
1952
+ }
1953
+ });
1954
+ return () => {
1955
+ cancelled = true;
1956
+ };
1957
+ }, [
1958
+ flushPendingBatches,
1959
+ installedFonts,
1960
+ setFontRegistryError
1961
+ ]);
1962
+ const measureTextBatch = (0, react.useCallback)((requests, options) => {
1963
+ var _options$generationId, _options$timeoutMs;
1964
+ if (requests.length === 0) return Promise.resolve([]);
1965
+ const id = `measure-${Date.now()}-${nextBatchId.current++}`;
1966
+ const generationId = (_options$generationId = options === null || options === void 0 ? void 0 : options.generationId) !== null && _options$generationId !== void 0 ? _options$generationId : providerGeneration.current++;
1967
+ const timeoutMs = (_options$timeoutMs = options === null || options === void 0 ? void 0 : options.timeoutMs) !== null && _options$timeoutMs !== void 0 ? _options$timeoutMs : measurementTimeoutMs;
1968
+ if (debugMeasurementLogs) logMeasurementDebug("request", {
1969
+ id,
1970
+ generationId,
1971
+ requestCount: requests.length,
1972
+ requests
1973
+ });
1974
+ return new Promise((resolve, reject) => {
1975
+ const batch = {
1976
+ id,
1977
+ generationId,
1978
+ requests,
1979
+ injected: false,
1980
+ resolve,
1981
+ reject,
1982
+ timer: setTimeout(() => {
1983
+ pendingBatches.current.delete(id);
1984
+ if (debugMeasurementLogs) logMeasurementDebug("timeout", {
1985
+ id,
1986
+ generationId,
1987
+ timeoutMs,
1988
+ requestCount: requests.length
1989
+ });
1990
+ reject(new Error(formatMessageRef.current("measurement.timeout", { timeoutMs })));
1991
+ }, timeoutMs)
1992
+ };
1993
+ pendingBatches.current.set(id, batch);
1994
+ if (measurementWebViewReady.current) injectBatch(batch);
1995
+ });
1996
+ }, [
1997
+ debugMeasurementLogs,
1998
+ injectBatch,
1999
+ measurementTimeoutMs
2000
+ ]);
2001
+ const handleMessage = (0, react.useCallback)((event) => {
2002
+ let message;
2003
+ try {
2004
+ message = JSON.parse(event.nativeEvent.data);
2005
+ } catch {
2006
+ return;
2007
+ }
2008
+ if (message.type !== "oriha.measureTextBatchResult") return;
2009
+ const batch = pendingBatches.current.get(message.id);
2010
+ if (!batch || batch.generationId !== message.generationId) return;
2011
+ clearTimeout(batch.timer);
2012
+ pendingBatches.current.delete(message.id);
2013
+ if (debugMeasurementLogs) logMeasurementDebug("result", {
2014
+ id: message.id,
2015
+ generationId: message.generationId,
2016
+ resultCount: message.results.length,
2017
+ results: message.results,
2018
+ error: message.error
2019
+ });
2020
+ if (message.error) {
2021
+ batch.reject(new Error(message.error));
2022
+ return;
2023
+ }
2024
+ batch.resolve(message.results);
2025
+ }, [debugMeasurementLogs]);
2026
+ const handleMeasurementWebViewLoad = (0, react.useCallback)(() => {
2027
+ measurementWebViewLoaded.current = true;
2028
+ if (measurementFontFaceCssLoading.current) return;
2029
+ measurementWebViewReady.current = true;
2030
+ flushPendingBatches();
2031
+ }, [flushPendingBatches]);
2032
+ (0, react.useEffect)(() => {
2033
+ measurementWebViewLoaded.current = false;
2034
+ measurementWebViewReady.current = false;
2035
+ }, [measurementWebViewHtml]);
2036
+ (0, react.useEffect)(() => {
2037
+ const batches = pendingBatches.current;
2038
+ return () => {
2039
+ for (const batch of batches.values()) {
2040
+ clearTimeout(batch.timer);
2041
+ batch.reject(new Error(formatMessageRef.current("measurement.cancelled")));
2042
+ }
2043
+ batches.clear();
2044
+ };
2045
+ }, []);
2046
+ return {
2047
+ webViewRef,
2048
+ installedFontFaceCss,
2049
+ measurementWebViewHtml,
2050
+ measureTextBatch,
2051
+ handleMessage,
2052
+ handleMeasurementWebViewLoad
2053
+ };
2054
+ }
2055
+ //#endregion
2056
+ //#region src/provider/providerStyles.tsx
2057
+ const styles$1 = react_native.StyleSheet.create({
2058
+ root: { flex: 1 },
2059
+ overlayHost: {
2060
+ ...react_native.StyleSheet.absoluteFillObject,
2061
+ zIndex: 1e4,
2062
+ elevation: 1e4
2063
+ },
2064
+ overlaySlot: { ...react_native.StyleSheet.absoluteFillObject },
2065
+ overlayTop: {
2066
+ alignItems: "stretch",
2067
+ justifyContent: "flex-start"
2068
+ },
2069
+ overlayCenter: {
2070
+ alignItems: "center",
2071
+ justifyContent: "center"
2072
+ },
2073
+ overlayBottom: {
2074
+ alignItems: "stretch",
2075
+ justifyContent: "flex-end"
2076
+ },
2077
+ overlayFill: {
2078
+ alignItems: "stretch",
2079
+ justifyContent: "flex-start"
2080
+ },
2081
+ toastHost: {
2082
+ ...react_native.StyleSheet.absoluteFillObject,
2083
+ zIndex: 10001,
2084
+ elevation: 10001
2085
+ },
2086
+ toastSlot: {
2087
+ ...react_native.StyleSheet.absoluteFillObject,
2088
+ alignItems: "center",
2089
+ paddingHorizontal: 16
2090
+ },
2091
+ toastSlotTop: {
2092
+ justifyContent: "flex-start",
2093
+ paddingTop: 48
2094
+ },
2095
+ toastSlotCenter: { justifyContent: "center" },
2096
+ toastSlotBottom: {
2097
+ justifyContent: "flex-end",
2098
+ paddingBottom: 24
2099
+ },
2100
+ toastItem: { marginVertical: 4 },
2101
+ toast: {
2102
+ alignItems: "center",
2103
+ alignSelf: "center",
2104
+ borderRadius: 999,
2105
+ flexDirection: "row",
2106
+ maxWidth: "100%",
2107
+ paddingHorizontal: 16,
2108
+ paddingVertical: 10,
2109
+ shadowColor: "#000",
2110
+ shadowOffset: {
2111
+ width: 0,
2112
+ height: 6
2113
+ },
2114
+ shadowOpacity: .18,
2115
+ shadowRadius: 14
2116
+ },
2117
+ toastIcon: { marginRight: 8 },
2118
+ toastText: {
2119
+ fontSize: 14,
2120
+ fontWeight: "600",
2121
+ lineHeight: 18
2122
+ },
2123
+ measurementHost: {
2124
+ position: "absolute",
2125
+ left: -1e4,
2126
+ top: 0,
2127
+ width: 1024,
2128
+ height: 1024,
2129
+ opacity: 0,
2130
+ overflow: "hidden"
2131
+ },
2132
+ measurementWebView: {
2133
+ width: 1024,
2134
+ height: 1024,
2135
+ backgroundColor: "transparent"
2136
+ }
2137
+ });
2138
+ //#endregion
2139
+ //#region generated/generatedHeroicons.ts
2140
+ const HEROICON_SOLID_DEFINITIONS = {
2141
+ "information-circle": {
2142
+ viewBox: "0 0 24 24",
2143
+ paths: [{
2144
+ d: "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm8.706-1.442c1.146-.573 2.437.463 2.126 1.706l-.709 2.836.042-.02a.75.75 0 0 1 .67 1.34l-.04.022c-1.147.573-2.438-.463-2.127-1.706l.71-2.836-.042.02a.75.75 0 1 1-.671-1.34l.041-.022ZM12 9a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z",
2145
+ fillRule: "evenodd",
2146
+ clipRule: "evenodd"
2147
+ }]
2148
+ },
2149
+ "pencil": {
2150
+ viewBox: "0 0 24 24",
2151
+ paths: [{ d: "M21.731 2.269a2.625 2.625 0 0 0-3.712 0l-1.157 1.157 3.712 3.712 1.157-1.157a2.625 2.625 0 0 0 0-3.712ZM19.513 8.199l-3.712-3.712-12.15 12.15a5.25 5.25 0 0 0-1.32 2.214l-.8 2.685a.75.75 0 0 0 .933.933l2.685-.8a5.25 5.25 0 0 0 2.214-1.32L19.513 8.2Z" }]
2152
+ },
2153
+ "check-circle": {
2154
+ viewBox: "0 0 24 24",
2155
+ paths: [{
2156
+ d: "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z",
2157
+ fillRule: "evenodd",
2158
+ clipRule: "evenodd"
2159
+ }]
2160
+ },
2161
+ "exclamation-triangle": {
2162
+ viewBox: "0 0 24 24",
2163
+ paths: [{
2164
+ d: "M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z",
2165
+ fillRule: "evenodd",
2166
+ clipRule: "evenodd"
2167
+ }]
2168
+ },
2169
+ "exclamation-circle": {
2170
+ viewBox: "0 0 24 24",
2171
+ paths: [{
2172
+ d: "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z",
2173
+ fillRule: "evenodd",
2174
+ clipRule: "evenodd"
2175
+ }]
2176
+ },
2177
+ "megaphone": {
2178
+ viewBox: "0 0 24 24",
2179
+ paths: [{ d: "M16.881 4.345A23.112 23.112 0 0 1 8.25 6H7.5a5.25 5.25 0 0 0-.88 10.427 21.593 21.593 0 0 0 1.378 3.94c.464 1.004 1.674 1.32 2.582.796l.657-.379c.88-.508 1.165-1.593.772-2.468a17.116 17.116 0 0 1-.628-1.607c1.918.258 3.76.75 5.5 1.446A21.727 21.727 0 0 0 18 11.25c0-2.414-.393-4.735-1.119-6.905ZM18.26 3.74a23.22 23.22 0 0 1 1.24 7.51 23.22 23.22 0 0 1-1.41 7.992.75.75 0 1 0 1.409.516 24.555 24.555 0 0 0 1.415-6.43 2.992 2.992 0 0 0 .836-2.078c0-.807-.319-1.54-.836-2.078a24.65 24.65 0 0 0-1.415-6.43.75.75 0 1 0-1.409.516c.059.16.116.321.17.483Z" }]
2180
+ }
2181
+ };
2182
+ //#endregion
2183
+ //#region src/provider/providerOverlays.tsx
2184
+ const TOAST_POSITIONS = [
2185
+ "top",
2186
+ "center",
2187
+ "bottom"
2188
+ ];
2189
+ function OrihaToast({ toast, onDismiss }) {
2190
+ const progress = (0, react.useRef)(new react_native.Animated.Value(0)).current;
2191
+ const variantStyle = toastVariantStyle(toast.variant);
2192
+ (0, react.useEffect)(() => {
2193
+ react_native.Animated.timing(progress, {
2194
+ toValue: 1,
2195
+ duration: 180,
2196
+ useNativeDriver: true
2197
+ }).start();
2198
+ const timer = setTimeout(() => {
2199
+ react_native.Animated.timing(progress, {
2200
+ toValue: 0,
2201
+ duration: 160,
2202
+ useNativeDriver: true
2203
+ }).start(({ finished }) => {
2204
+ if (finished) onDismiss(toast.id);
2205
+ });
2206
+ }, toast.durationMs);
2207
+ return () => {
2208
+ clearTimeout(timer);
2209
+ };
2210
+ }, [
2211
+ onDismiss,
2212
+ progress,
2213
+ toast.durationMs,
2214
+ toast.id
2215
+ ]);
2216
+ const translateY = progress.interpolate({
2217
+ inputRange: [0, 1],
2218
+ outputRange: [toast.position === "top" ? -24 : 24, 0]
2219
+ });
2220
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.Animated.View, {
2221
+ pointerEvents: "none",
2222
+ style: [
2223
+ styles$1.toast,
2224
+ { backgroundColor: variantStyle.backgroundColor },
2225
+ {
2226
+ opacity: progress,
2227
+ transform: [{ translateY }]
2228
+ }
2229
+ ],
2230
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Heroicon, {
2231
+ color: variantStyle.iconColor,
2232
+ name: variantStyle.icon,
2233
+ style: styles$1.toastIcon
2234
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.Text, {
2235
+ style: [styles$1.toastText, { color: variantStyle.textColor }],
2236
+ children: toast.message
2237
+ })]
2238
+ });
2239
+ }
2240
+ function Heroicon({ color, name, style }) {
2241
+ const icon = HEROICON_SOLID_DEFINITIONS[name];
2242
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native_svg.default, {
2243
+ fill: color,
2244
+ height: 20,
2245
+ style,
2246
+ viewBox: icon.viewBox,
2247
+ width: 20,
2248
+ children: icon.paths.map((path, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native_svg.Path, { ...path }, `${name}-${index}`))
2249
+ });
2250
+ }
2251
+ function toastVariantStyle(variant) {
2252
+ switch (variant) {
2253
+ case "info": return {
2254
+ backgroundColor: "#0284c7",
2255
+ icon: "information-circle",
2256
+ iconColor: "#e0f2fe",
2257
+ textColor: "#ffffff"
2258
+ };
2259
+ case "note": return {
2260
+ backgroundColor: "#4f46e5",
2261
+ icon: "pencil",
2262
+ iconColor: "#e0e7ff",
2263
+ textColor: "#ffffff"
2264
+ };
2265
+ case "success": return {
2266
+ backgroundColor: "#059669",
2267
+ icon: "check-circle",
2268
+ iconColor: "#d1fae5",
2269
+ textColor: "#ffffff"
2270
+ };
2271
+ case "warn": return {
2272
+ backgroundColor: "#f59e0b",
2273
+ icon: "exclamation-triangle",
2274
+ iconColor: "#78350f",
2275
+ textColor: "#111827"
2276
+ };
2277
+ case "err": return {
2278
+ backgroundColor: "#e11d48",
2279
+ icon: "exclamation-circle",
2280
+ iconColor: "#ffe4e6",
2281
+ textColor: "#ffffff"
2282
+ };
2283
+ default: return {
2284
+ backgroundColor: "#0f172a",
2285
+ icon: "megaphone",
2286
+ iconColor: "#cbd5e1",
2287
+ textColor: "#ffffff"
2288
+ };
2289
+ }
2290
+ }
2291
+ function overlayPlacementStyle(placement) {
2292
+ switch (placement) {
2293
+ case "top": return styles$1.overlayTop;
2294
+ case "bottom": return styles$1.overlayBottom;
2295
+ case "fill": return styles$1.overlayFill;
2296
+ default: return styles$1.overlayCenter;
2297
+ }
2298
+ }
2299
+ function toastPositionStyle(position) {
2300
+ switch (position) {
2301
+ case "top": return styles$1.toastSlotTop;
2302
+ case "center": return styles$1.toastSlotCenter;
2303
+ default: return styles$1.toastSlotBottom;
2304
+ }
2305
+ }
2306
+ //#endregion
2307
+ //#region src/provider/OrihaProvider.tsx
2308
+ const DEFAULT_MEASURE_TIMEOUT_MS = 5e3;
2309
+ function OrihaProvider({ children, measurementTimeoutMs = DEFAULT_MEASURE_TIMEOUT_MS, debugMeasurementLogs = false, fontRegistry, locale, messages }) {
2310
+ const nextOverlayId = (0, react.useRef)(0);
2311
+ const nextToastId = (0, react.useRef)(0);
2312
+ const [overlays, setOverlays] = (0, react.useState)([]);
2313
+ const [toasts, setToasts] = (0, react.useState)([]);
2314
+ const fontState = useProviderFonts(fontRegistry);
2315
+ const { fontRegistryState, installedFonts, setFontRegistryError } = fontState;
2316
+ const i18n = (0, react.useMemo)(() => createOrihaI18n(locale, messages), [locale, messages]);
2317
+ const { webViewRef, installedFontFaceCss, measurementWebViewHtml, measureTextBatch, handleMessage, handleMeasurementWebViewLoad } = useTextMeasurementBridge({
2318
+ installedFonts,
2319
+ measurementTimeoutMs,
2320
+ debugMeasurementLogs,
2321
+ formatMessage: i18n.formatMessage,
2322
+ setFontRegistryError
2323
+ });
2324
+ const dismissOverlay = (0, react.useCallback)((id) => {
2325
+ setOverlays((current) => current.filter((entry) => entry.id !== id));
2326
+ }, []);
2327
+ const presentOverlay = (0, react.useCallback)((node, options) => {
2328
+ var _options$id, _options$placement, _options$pointerEvent;
2329
+ const id = (_options$id = options === null || options === void 0 ? void 0 : options.id) !== null && _options$id !== void 0 ? _options$id : `overlay-${Date.now()}-${nextOverlayId.current++}`;
2330
+ const entry = {
2331
+ id,
2332
+ node,
2333
+ placement: (_options$placement = options === null || options === void 0 ? void 0 : options.placement) !== null && _options$placement !== void 0 ? _options$placement : "center",
2334
+ pointerEvents: (_options$pointerEvent = options === null || options === void 0 ? void 0 : options.pointerEvents) !== null && _options$pointerEvent !== void 0 ? _options$pointerEvent : "box-none",
2335
+ style: options === null || options === void 0 ? void 0 : options.style
2336
+ };
2337
+ setOverlays((current) => [...current.filter((existing) => existing.id !== id), entry]);
2338
+ return () => {
2339
+ dismissOverlay(id);
2340
+ };
2341
+ }, [dismissOverlay]);
2342
+ const dismissToast = (0, react.useCallback)((id) => {
2343
+ setToasts((current) => current.filter((toast) => toast.id !== id));
2344
+ }, []);
2345
+ const showToast = (0, react.useCallback)((message, options) => {
2346
+ var _options$id2, _options$durationMs, _options$position, _options$variant;
2347
+ const id = (_options$id2 = options === null || options === void 0 ? void 0 : options.id) !== null && _options$id2 !== void 0 ? _options$id2 : `toast-${Date.now()}-${nextToastId.current++}`;
2348
+ const entry = {
2349
+ id,
2350
+ message,
2351
+ durationMs: (_options$durationMs = options === null || options === void 0 ? void 0 : options.durationMs) !== null && _options$durationMs !== void 0 ? _options$durationMs : 1800,
2352
+ position: (_options$position = options === null || options === void 0 ? void 0 : options.position) !== null && _options$position !== void 0 ? _options$position : "top",
2353
+ variant: (_options$variant = options === null || options === void 0 ? void 0 : options.variant) !== null && _options$variant !== void 0 ? _options$variant : "neutral"
2354
+ };
2355
+ setToasts((current) => [...current.filter((toast) => toast.id !== id), entry]);
2356
+ return () => {
2357
+ dismissToast(id);
2358
+ };
2359
+ }, [dismissToast]);
2360
+ useInitializeProviderFonts(fontRegistry, fontState);
2361
+ const contextValue = (0, react.useMemo)(() => ({
2362
+ measureTextBatch,
2363
+ fontRegistry: fontRegistryState,
2364
+ installedFontFaceCss,
2365
+ presentOverlay,
2366
+ dismissOverlay,
2367
+ showToast,
2368
+ dismissToast,
2369
+ i18n,
2370
+ formatMessage: i18n.formatMessage
2371
+ }), [
2372
+ dismissOverlay,
2373
+ dismissToast,
2374
+ fontRegistryState,
2375
+ i18n,
2376
+ installedFontFaceCss,
2377
+ measureTextBatch,
2378
+ presentOverlay,
2379
+ showToast
2380
+ ]);
2381
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OrihaContext.Provider, {
2382
+ value: contextValue,
2383
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.View, {
2384
+ style: styles$1.root,
2385
+ children: [
2386
+ children,
2387
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.View, {
2388
+ pointerEvents: "box-none",
2389
+ style: styles$1.overlayHost,
2390
+ children: [overlays.map((entry) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
2391
+ pointerEvents: entry.pointerEvents,
2392
+ style: [
2393
+ styles$1.overlaySlot,
2394
+ overlayPlacementStyle(entry.placement),
2395
+ entry.style
2396
+ ],
2397
+ children: entry.node
2398
+ }, entry.id)), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
2399
+ pointerEvents: "box-none",
2400
+ style: styles$1.toastHost,
2401
+ children: TOAST_POSITIONS.map((position) => {
2402
+ const positionedToasts = toasts.filter((toast) => toast.position === position);
2403
+ if (positionedToasts.length === 0) return null;
2404
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
2405
+ pointerEvents: "box-none",
2406
+ style: [styles$1.toastSlot, toastPositionStyle(position)],
2407
+ children: positionedToasts.map((toast) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
2408
+ style: styles$1.toastItem,
2409
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OrihaToast, {
2410
+ toast,
2411
+ onDismiss: dismissToast
2412
+ })
2413
+ }, toast.id))
2414
+ }, position);
2415
+ })
2416
+ })]
2417
+ }),
2418
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
2419
+ collapsable: false,
2420
+ pointerEvents: "none",
2421
+ style: styles$1.measurementHost,
2422
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native_webview.WebView, {
2423
+ ref: webViewRef,
2424
+ allowFileAccess: true,
2425
+ originWhitelist: ["*"],
2426
+ source: { html: measurementWebViewHtml },
2427
+ onLoadEnd: handleMeasurementWebViewLoad,
2428
+ onMessage: handleMessage,
2429
+ scrollEnabled: false,
2430
+ style: styles$1.measurementWebView
2431
+ })
2432
+ })
2433
+ ]
2434
+ })
2435
+ });
2436
+ }
2437
+ //#endregion
2438
+ //#region src/preview/orihaPreviewHtml.ts
2439
+ const CODE_COPY_MESSAGE_TYPE = "oriha.codeCopyResult";
2440
+ const EXTERNAL_LINK_MESSAGE_TYPE = "oriha.openExternalLink";
2441
+ const MATH_FONT_MIME_TYPE = "font/otf";
2442
+ const MATH_FONT_FAMILY = "ORIHA STIX Two Math";
2443
+ function parseViewerPatchResultMessage(data) {
2444
+ let message;
2445
+ try {
2446
+ message = JSON.parse(data);
2447
+ } catch {
2448
+ return null;
2449
+ }
2450
+ if (message.type !== "oriha.patchResult" || typeof message.generationId !== "number" || typeof message.ok !== "boolean") return null;
2451
+ return message;
2452
+ }
2453
+ function shouldOpenExternally(url) {
2454
+ if (!url) return false;
2455
+ const lowerUrl = url.trim().toLowerCase();
2456
+ if (lowerUrl.startsWith("#") || lowerUrl.startsWith("about:") || lowerUrl.startsWith("blob:") || lowerUrl.startsWith("data:") || lowerUrl.startsWith("file:")) return false;
2457
+ return /^(https?:|mailto:|tel:|sms:|geo:|maps:)/i.test(lowerUrl);
2458
+ }
2459
+ function buildViewerHtml(output, localFontFaceCss) {
2460
+ return buildDocumentHtml({
2461
+ body: `<div data-oriha-patch-root="true">${output.html}</div>
2462
+ ${viewerExternalLinkScript()}
2463
+ ${viewerPatchScript()}
2464
+ ${viewerCodeCopyScript()}`,
2465
+ localFontFaceCss,
2466
+ output
2467
+ });
2468
+ }
2469
+ function buildPdfHtml(output, localFontFaceCss) {
2470
+ return buildDocumentHtml({
2471
+ body: output.html,
2472
+ localFontFaceCss,
2473
+ output
2474
+ });
2475
+ }
2476
+ function buildDocumentHtml({ body, localFontFaceCss, output }) {
2477
+ var _output$css;
2478
+ const outputCss = (_output$css = output.css) !== null && _output$css !== void 0 ? _output$css : "";
2479
+ return `<!doctype html>
2480
+ <html>
2481
+ <head>
2482
+ <meta charset="utf-8" />
2483
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
2484
+ <style>
2485
+ ${[
2486
+ outputCss.includes("ORIHA STIX Two Math") ? "" : buildBundledFontFaceCss(output),
2487
+ localFontFaceCss,
2488
+ outputCss
2489
+ ].filter((chunk) => chunk.length > 0).join("\n").replace(/<\/style/gi, "<\\/style")}
2490
+ html, body { margin: 0; padding: 0; background: transparent; }
2491
+ body { -webkit-text-size-adjust: 100%; }
2492
+ </style>
2493
+ </head>
2494
+ <body>
2495
+ ${body}
2496
+ </body>
2497
+ </html>`;
2498
+ }
2499
+ function buildBundledFontFaceCss(output) {
2500
+ const asset = output.assets.find((entry) => entry.id === "oriha-stix-two-math" && entry.mimeType === "font/otf" && entry.content.length > 0);
2501
+ if (!asset) return "";
2502
+ return [
2503
+ "@font-face {",
2504
+ ` font-family: "${MATH_FONT_FAMILY}";`,
2505
+ ` src: url("data:${MATH_FONT_MIME_TYPE};base64,${asset.content}") format("opentype");`,
2506
+ " font-weight: 400;",
2507
+ " font-style: normal;",
2508
+ " font-display: block;",
2509
+ "}",
2510
+ `.oriha-math-inline svg text, .oriha-math-block svg text { font-family: "${MATH_FONT_FAMILY}", "Cambria Math", "STIX Two Math", serif; }`
2511
+ ].join("\n");
2512
+ }
2513
+ function viewerExternalLinkScript() {
2514
+ return `<script>
2515
+ (function() {
2516
+ var EXTERNAL_SCHEME = /^(https?:|mailto:|tel:|sms:|geo:|maps:)/i;
2517
+
2518
+ function postExternalLink(url) {
2519
+ if (!window.ReactNativeWebView || !window.ReactNativeWebView.postMessage) {
2520
+ return;
2521
+ }
2522
+ window.ReactNativeWebView.postMessage(JSON.stringify({
2523
+ type: "${EXTERNAL_LINK_MESSAGE_TYPE}",
2524
+ url: url
2525
+ }));
2526
+ }
2527
+
2528
+ function externalHref(anchor) {
2529
+ var rawHref = anchor && anchor.getAttribute ? anchor.getAttribute("href") : "";
2530
+ if (!rawHref || rawHref.charAt(0) === "#") {
2531
+ return null;
2532
+ }
2533
+ if (/^\\s*javascript:/i.test(rawHref)) {
2534
+ return null;
2535
+ }
2536
+ try {
2537
+ var resolved = new URL(rawHref, window.location.href);
2538
+ if (!EXTERNAL_SCHEME.test(resolved.protocol)) {
2539
+ return null;
2540
+ }
2541
+ return resolved.href;
2542
+ } catch (_) {
2543
+ return EXTERNAL_SCHEME.test(rawHref) ? rawHref : null;
2544
+ }
2545
+ }
2546
+
2547
+ function configureExternalLinks(root) {
2548
+ var anchors = (root || document).querySelectorAll("a[href]");
2549
+ for (var index = 0; index < anchors.length; index += 1) {
2550
+ var href = externalHref(anchors[index]);
2551
+ if (!href) {
2552
+ continue;
2553
+ }
2554
+ anchors[index].setAttribute("target", "_blank");
2555
+ anchors[index].setAttribute("rel", "noopener noreferrer");
2556
+ }
2557
+ }
2558
+
2559
+ window.orihaConfigureExternalLinks = configureExternalLinks;
2560
+ configureExternalLinks(document);
2561
+ document.addEventListener("DOMContentLoaded", function() {
2562
+ configureExternalLinks(document);
2563
+ });
2564
+
2565
+ document.addEventListener("click", function(event) {
2566
+ var anchor = event.target.closest && event.target.closest("a[href]");
2567
+ var href = externalHref(anchor);
2568
+ if (!href) {
2569
+ return;
2570
+ }
2571
+
2572
+ event.preventDefault();
2573
+ postExternalLink(href);
2574
+ }, true);
2575
+ })();
2576
+ <\/script>`;
2577
+ }
2578
+ function viewerPatchScript() {
2579
+ return `<script>
2580
+ (function() {
2581
+ function patchRoot() {
2582
+ return document.querySelector("[data-oriha-patch-root]") ||
2583
+ document.querySelector(".oriha-document") ||
2584
+ document.body;
2585
+ }
2586
+
2587
+ function findStableBlock(root, stableId) {
2588
+ if (!stableId) {
2589
+ return null;
2590
+ }
2591
+ var blocks = root.querySelectorAll("[data-oriha-stable-id]");
2592
+ var expected = String(stableId);
2593
+ for (var index = 0; index < blocks.length; index += 1) {
2594
+ if (blocks[index].getAttribute("data-oriha-stable-id") === expected) {
2595
+ return blocks[index];
2596
+ }
2597
+ }
2598
+ return null;
2599
+ }
2600
+
2601
+ function nodesFromHtml(html) {
2602
+ var template = document.createElement("template");
2603
+ template.innerHTML = html || "";
2604
+ return Array.prototype.slice.call(template.content.childNodes);
2605
+ }
2606
+
2607
+ function firstVisibleStableBlock(root) {
2608
+ var blocks = root.querySelectorAll("[data-oriha-stable-id]");
2609
+ var viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
2610
+ for (var index = 0; index < blocks.length; index += 1) {
2611
+ var rect = blocks[index].getBoundingClientRect();
2612
+ if (rect.bottom >= 0 && rect.top <= viewportHeight) {
2613
+ return {
2614
+ stableId: blocks[index].getAttribute("data-oriha-stable-id"),
2615
+ top: rect.top
2616
+ };
2617
+ }
2618
+ }
2619
+ return null;
2620
+ }
2621
+
2622
+ function restoreScroll(root, anchor) {
2623
+ if (!anchor || !anchor.stableId) {
2624
+ return;
2625
+ }
2626
+ var block = findStableBlock(root, anchor.stableId);
2627
+ if (!block) {
2628
+ return;
2629
+ }
2630
+ var nextTop = block.getBoundingClientRect().top;
2631
+ window.scrollBy(0, nextTop - anchor.top);
2632
+ }
2633
+
2634
+ function configureExternalLinks(root) {
2635
+ if (window.orihaConfigureExternalLinks) {
2636
+ window.orihaConfigureExternalLinks(root || document);
2637
+ }
2638
+ }
2639
+
2640
+ function replaceAll(root, html) {
2641
+ var anchor = firstVisibleStableBlock(root);
2642
+ root.innerHTML = html || "";
2643
+ configureExternalLinks(root);
2644
+ restoreScroll(root, anchor);
2645
+ return true;
2646
+ }
2647
+
2648
+ function replaceBlocks(root, operation) {
2649
+ var removeStableIds = operation.removeStableIds || [];
2650
+ var insertAfter = operation.insertAfterStableId ?
2651
+ findStableBlock(root, operation.insertAfterStableId) :
2652
+ null;
2653
+ var insertBefore = operation.insertBeforeStableId ?
2654
+ findStableBlock(root, operation.insertBeforeStableId) :
2655
+ null;
2656
+
2657
+ if (operation.insertAfterStableId && !insertAfter) {
2658
+ return false;
2659
+ }
2660
+ if (operation.insertBeforeStableId && !insertBefore) {
2661
+ return false;
2662
+ }
2663
+
2664
+ var anchor = firstVisibleStableBlock(root);
2665
+ var fallbackParent = null;
2666
+ for (var index = 0; index < removeStableIds.length; index += 1) {
2667
+ var block = findStableBlock(root, removeStableIds[index]);
2668
+ if (!block) {
2669
+ return false;
2670
+ }
2671
+ if (block.parentNode) {
2672
+ if (!fallbackParent) {
2673
+ fallbackParent = block.parentNode;
2674
+ }
2675
+ block.parentNode.removeChild(block);
2676
+ }
2677
+ }
2678
+
2679
+ var nodes = nodesFromHtml(operation.html);
2680
+ if (nodes.length > 0) {
2681
+ var parent = fallbackParent || root.querySelector(".oriha-document") || root;
2682
+ var reference = null;
2683
+ if (insertBefore && insertBefore.parentNode) {
2684
+ parent = insertBefore.parentNode;
2685
+ reference = insertBefore;
2686
+ } else if (insertAfter && insertAfter.parentNode) {
2687
+ parent = insertAfter.parentNode;
2688
+ reference = insertAfter.nextSibling;
2689
+ }
2690
+ for (var nodeIndex = 0; nodeIndex < nodes.length; nodeIndex += 1) {
2691
+ parent.insertBefore(nodes[nodeIndex], reference);
2692
+ }
2693
+ configureExternalLinks(parent);
2694
+ }
2695
+
2696
+ restoreScroll(root, anchor);
2697
+ return true;
2698
+ }
2699
+
2700
+ window.orihaApplyPatch = function(payload) {
2701
+ var root = patchRoot();
2702
+ if (!root || !payload || !Array.isArray(payload.patches)) {
2703
+ return false;
2704
+ }
2705
+
2706
+ for (var index = 0; index < payload.patches.length; index += 1) {
2707
+ var operation = payload.patches[index];
2708
+ var ok = false;
2709
+ if (operation && operation.op === "replaceAll") {
2710
+ ok = replaceAll(root, operation.html);
2711
+ } else if (operation && operation.op === "replaceBlocks") {
2712
+ ok = replaceBlocks(root, operation);
2713
+ }
2714
+ if (!ok) {
2715
+ return false;
2716
+ }
2717
+ }
2718
+ return true;
2719
+ };
2720
+ })();
2721
+ <\/script>`;
2722
+ }
2723
+ function viewerCodeCopyScript() {
2724
+ return `<script>
2725
+ (function() {
2726
+ function postCodeCopyResult(status) {
2727
+ if (!window.ReactNativeWebView || !window.ReactNativeWebView.postMessage) {
2728
+ return;
2729
+ }
2730
+ window.ReactNativeWebView.postMessage(JSON.stringify({
2731
+ type: "${CODE_COPY_MESSAGE_TYPE}",
2732
+ status: status
2733
+ }));
2734
+ }
2735
+
2736
+ function fallbackCopy(text) {
2737
+ var textarea = document.createElement("textarea");
2738
+ textarea.value = text;
2739
+ textarea.setAttribute("readonly", "");
2740
+ textarea.style.position = "fixed";
2741
+ textarea.style.left = "-9999px";
2742
+ document.body.appendChild(textarea);
2743
+ textarea.select();
2744
+ try {
2745
+ if (document.execCommand("copy")) {
2746
+ return Promise.resolve();
2747
+ }
2748
+ return Promise.reject(new Error("copy command rejected"));
2749
+ } finally {
2750
+ document.body.removeChild(textarea);
2751
+ }
2752
+ }
2753
+
2754
+ function copyText(text) {
2755
+ if (navigator.clipboard && navigator.clipboard.writeText) {
2756
+ return navigator.clipboard.writeText(text);
2757
+ }
2758
+ return fallbackCopy(text);
2759
+ }
2760
+
2761
+ document.addEventListener("click", function(event) {
2762
+ var button = event.target.closest && event.target.closest("[data-oriha-copy-button]");
2763
+ if (!button) {
2764
+ return;
2765
+ }
2766
+
2767
+ var wrapper = button.closest(".oriha-code-block-wrapper");
2768
+ if (!wrapper) {
2769
+ return;
2770
+ }
2771
+
2772
+ event.preventDefault();
2773
+ copyText(wrapper.getAttribute("data-oriha-code-copy") || "").then(function() {
2774
+ postCodeCopyResult("success");
2775
+ }, function() {
2776
+ postCodeCopyResult("error");
2777
+ });
2778
+ }, true);
2779
+ })();
2780
+ <\/script>`;
2781
+ }
2782
+ //#endregion
2783
+ //#region src/preview/orihaPreviewPdf.ts
2784
+ const DEFAULT_PDF_MARGIN = "12mm";
2785
+ const DEFAULT_PDF_WATERMARK_TEXT = "Generated with markup";
2786
+ const DEFAULT_PDF_ORIENTATION = "Portrait";
2787
+ const DEFAULT_PDF_PAPER_SIZE = "A4";
2788
+ const LANDSCAPE_PDF_ORIENTATION = "Landscape";
2789
+ function normalizePdfExportOptions(options) {
2790
+ var _options$margin, _options$orientation, _options$paperSize;
2791
+ return {
2792
+ margin: (_options$margin = options === null || options === void 0 ? void 0 : options.margin) !== null && _options$margin !== void 0 ? _options$margin : DEFAULT_PDF_MARGIN,
2793
+ orientation: (_options$orientation = options === null || options === void 0 ? void 0 : options.orientation) !== null && _options$orientation !== void 0 ? _options$orientation : DEFAULT_PDF_ORIENTATION,
2794
+ paperSize: (_options$paperSize = options === null || options === void 0 ? void 0 : options.paperSize) !== null && _options$paperSize !== void 0 ? _options$paperSize : DEFAULT_PDF_PAPER_SIZE
2795
+ };
2796
+ }
2797
+ function buildPdfRenderInput(baseInput, options, normalizedOptions) {
2798
+ var _baseInput$print;
2799
+ const renderingOptionsOverride = options === null || options === void 0 ? void 0 : options.renderingOptions;
2800
+ const renderingOptions = {
2801
+ ...baseInput.renderingOptions,
2802
+ ...renderingOptionsOverride !== null && renderingOptionsOverride !== void 0 ? renderingOptionsOverride : {}
2803
+ };
2804
+ const mergedInput = {
2805
+ ...baseInput,
2806
+ markdown: baseInput.markdown,
2807
+ renderingOptions
2808
+ };
2809
+ const watermark = resolvePdfWatermark(baseInput.watermark, options === null || options === void 0 ? void 0 : options.watermark);
2810
+ return {
2811
+ ...mergedInput,
2812
+ print: {
2813
+ ...(_baseInput$print = baseInput.print) !== null && _baseInput$print !== void 0 ? _baseInput$print : {},
2814
+ margin: normalizedOptions.margin,
2815
+ pageSize: pdfPageSizeCss(normalizedOptions.paperSize, normalizedOptions.orientation)
2816
+ },
2817
+ watermark
2818
+ };
2819
+ }
2820
+ function resolvePdfWatermark(existingWatermark, requestedWatermark) {
2821
+ if (requestedWatermark === false) return;
2822
+ if (requestedWatermark) return normalizeWatermark({
2823
+ ...defaultPdfWatermark(),
2824
+ ...existingWatermark,
2825
+ ...requestedWatermark
2826
+ });
2827
+ return existingWatermark;
2828
+ }
2829
+ function defaultPdfWatermark() {
2830
+ return { text: DEFAULT_PDF_WATERMARK_TEXT };
2831
+ }
2832
+ function normalizeWatermark(watermark) {
2833
+ return {
2834
+ imageSrc: watermark.imageSrc,
2835
+ opacity: watermark.opacity,
2836
+ text: typeof watermark.text === "string" && watermark.text.trim().length > 0 ? watermark.text : DEFAULT_PDF_WATERMARK_TEXT
2837
+ };
2838
+ }
2839
+ function pdfPageSizeCss(paperSize, orientation) {
2840
+ return `${paperSize} ${pdfOrientationCss(orientation)}`;
2841
+ }
2842
+ function pdfOrientationCss(orientation) {
2843
+ switch (orientation) {
2844
+ case LANDSCAPE_PDF_ORIENTATION: return "landscape";
2845
+ default: return "portrait";
2846
+ }
2847
+ }
2848
+ function pdfPageDimensions(paperSize, orientation) {
2849
+ const dimensions = PDF_PAGE_DIMENSIONS[paperSize];
2850
+ if (orientation === LANDSCAPE_PDF_ORIENTATION) return {
2851
+ height: dimensions.width,
2852
+ width: dimensions.height
2853
+ };
2854
+ return dimensions;
2855
+ }
2856
+ const PDF_PAGE_DIMENSIONS = {
2857
+ A4: {
2858
+ height: 842,
2859
+ width: 595
2860
+ },
2861
+ B4: {
2862
+ height: 1032,
2863
+ width: 729
2864
+ },
2865
+ Letter: {
2866
+ height: 792,
2867
+ width: 612
2868
+ }
2869
+ };
2870
+ //#endregion
2871
+ //#region src/bridge/ExpoOrihaModule.ts
2872
+ var ExpoOrihaModule_default = (0, expo.requireNativeModule)("ExpoOriha");
2873
+ //#endregion
2874
+ //#region src/bridge/json.ts
2875
+ function stringifyBridgePayload(value) {
2876
+ const json = JSON.stringify(value);
2877
+ if (json === void 0) throw new Error("Cannot serialize undefined native bridge payload");
2878
+ return json;
2879
+ }
2880
+ function stringifyOptionalBridgePayload(value) {
2881
+ return value == null ? null : stringifyBridgePayload(value);
2882
+ }
2883
+ function parseBridgePayload(json) {
2884
+ return JSON.parse(json);
2885
+ }
2886
+ //#endregion
2887
+ //#region src/bridge/render.ts
2888
+ async function prepareMarkdownLayout(input) {
2889
+ return parseBridgePayload(await ExpoOrihaModule_default.prepareMarkdownLayout(stringifyBridgePayload(normalizeBridgeRenderInput(input))));
2890
+ }
2891
+ async function prepareMarkdownPatch(previousSnapshot, input) {
2892
+ return parseBridgePayload(await ExpoOrihaModule_default.prepareMarkdownPatch(stringifyOptionalBridgePayload(previousSnapshot), stringifyBridgePayload(normalizeBridgeRenderInput(input))));
2893
+ }
2894
+ async function prepareHtmlExport(input, options) {
2895
+ return parseBridgePayload(await ExpoOrihaModule_default.prepareHtmlExport(stringifyBridgePayload(normalizeBridgeRenderInput(input)), stringifyOptionalBridgePayload(options)));
2896
+ }
2897
+ async function resolveRenderSettings(input) {
2898
+ return parseBridgePayload(await ExpoOrihaModule_default.resolveRenderSettings(stringifyBridgePayload(input)));
2899
+ }
2900
+ async function renderPreparedMarkdown(layout, measureResults) {
2901
+ return parseBridgePayload(await ExpoOrihaModule_default.renderPreparedMarkdown(stringifyBridgePayload(layout), stringifyBridgePayload(measureResults)));
2902
+ }
2903
+ async function renderPreparedMarkdownPatch(preparedPatch, measureResults) {
2904
+ return parseBridgePayload(await ExpoOrihaModule_default.renderPreparedMarkdownPatch(stringifyBridgePayload(preparedPatch), stringifyBridgePayload(measureResults)));
2905
+ }
2906
+ async function renderPreparedHtmlExport(preparedExport, measureResults) {
2907
+ return parseBridgePayload(await ExpoOrihaModule_default.renderPreparedHtmlExport(stringifyBridgePayload(preparedExport), stringifyBridgePayload(measureResults)));
2908
+ }
2909
+ async function exportHtml(input, options, measureTextBatch) {
2910
+ const preparedExport = await prepareHtmlExport(input, options);
2911
+ return renderPreparedHtmlExport(preparedExport, preparedExport.textMeasurements.requests.length > 0 ? await measureRequiredHtmlExportText(preparedExport, measureTextBatch) : []);
2912
+ }
2913
+ async function measureRequiredHtmlExportText(preparedExport, measureTextBatch) {
2914
+ if (!measureTextBatch) throw new Error("exportHtml requires measureTextBatch when the prepared export has text measurement requests");
2915
+ return measureTextBatch(preparedExport.textMeasurements.requests);
2916
+ }
2917
+ function normalizeBridgeRenderInput(input) {
2918
+ var _input$plan, _input$print, _ref, _input$renderMode, _input$watermark, _ref2, _input$sourceAttribut, _ref3, _input$tableOfContent;
2919
+ const legacyInput = input;
2920
+ const legacyExportOptions = legacyInput.exportOptions;
2921
+ return {
2922
+ markdown: input.markdown,
2923
+ locale: input.locale,
2924
+ plan: (_input$plan = input.plan) !== null && _input$plan !== void 0 ? _input$plan : "free",
2925
+ renderingOptions: normalizeBridgeRenderingOptions(input.renderingOptions),
2926
+ print: (_input$print = input.print) !== null && _input$print !== void 0 ? _input$print : legacyExportOptions === null || legacyExportOptions === void 0 ? void 0 : legacyExportOptions.print,
2927
+ renderMode: (_ref = (_input$renderMode = input.renderMode) !== null && _input$renderMode !== void 0 ? _input$renderMode : legacyInput.mode) !== null && _ref !== void 0 ? _ref : "styledHtml",
2928
+ watermark: (_input$watermark = input.watermark) !== null && _input$watermark !== void 0 ? _input$watermark : legacyExportOptions === null || legacyExportOptions === void 0 ? void 0 : legacyExportOptions.watermark,
2929
+ sourceAttributes: (_ref2 = (_input$sourceAttribut = input.sourceAttributes) !== null && _input$sourceAttribut !== void 0 ? _input$sourceAttribut : legacyExportOptions === null || legacyExportOptions === void 0 ? void 0 : legacyExportOptions.sourceAttributes) !== null && _ref2 !== void 0 ? _ref2 : false,
2930
+ tableOfContents: (_ref3 = (_input$tableOfContent = input.tableOfContents) !== null && _input$tableOfContent !== void 0 ? _input$tableOfContent : legacyExportOptions === null || legacyExportOptions === void 0 ? void 0 : legacyExportOptions.tableOfContents) !== null && _ref3 !== void 0 ? _ref3 : false,
2931
+ viewport: input.viewport
2932
+ };
2933
+ }
2934
+ function normalizeBridgeRenderingOptions(options) {
2935
+ var _options$colorScheme, _options$appearanceSt, _options$syntaxTheme, _options$headingFont, _options$bodyFont, _options$codeFont, _options$tableBorderS, _options$roundedCorne, _options$shadows, _options$fullTableDat, _options$blockBorders;
2936
+ return {
2937
+ colorScheme: (_options$colorScheme = options === null || options === void 0 ? void 0 : options.colorScheme) !== null && _options$colorScheme !== void 0 ? _options$colorScheme : "light",
2938
+ appearanceStyle: (_options$appearanceSt = options === null || options === void 0 ? void 0 : options.appearanceStyle) !== null && _options$appearanceSt !== void 0 ? _options$appearanceSt : "rich",
2939
+ syntaxTheme: (_options$syntaxTheme = options === null || options === void 0 ? void 0 : options.syntaxTheme) !== null && _options$syntaxTheme !== void 0 ? _options$syntaxTheme : "github-light",
2940
+ customSyntaxTheme: options === null || options === void 0 ? void 0 : options.customSyntaxTheme,
2941
+ headingFont: (_options$headingFont = options === null || options === void 0 ? void 0 : options.headingFont) !== null && _options$headingFont !== void 0 ? _options$headingFont : "system-default",
2942
+ customHeadingFont: options === null || options === void 0 ? void 0 : options.customHeadingFont,
2943
+ bodyFont: (_options$bodyFont = options === null || options === void 0 ? void 0 : options.bodyFont) !== null && _options$bodyFont !== void 0 ? _options$bodyFont : "system-default",
2944
+ customBodyFont: options === null || options === void 0 ? void 0 : options.customBodyFont,
2945
+ bodyFontSizePx: options === null || options === void 0 ? void 0 : options.bodyFontSizePx,
2946
+ codeFont: (_options$codeFont = options === null || options === void 0 ? void 0 : options.codeFont) !== null && _options$codeFont !== void 0 ? _options$codeFont : "system-default",
2947
+ customCodeFont: options === null || options === void 0 ? void 0 : options.customCodeFont,
2948
+ tableBorderStyle: (_options$tableBorderS = options === null || options === void 0 ? void 0 : options.tableBorderStyle) !== null && _options$tableBorderS !== void 0 ? _options$tableBorderS : "inner",
2949
+ roundedCorners: (_options$roundedCorne = options === null || options === void 0 ? void 0 : options.roundedCorners) !== null && _options$roundedCorne !== void 0 ? _options$roundedCorne : true,
2950
+ shadows: (_options$shadows = options === null || options === void 0 ? void 0 : options.shadows) !== null && _options$shadows !== void 0 ? _options$shadows : true,
2951
+ fullTableData: (_options$fullTableDat = options === null || options === void 0 ? void 0 : options.fullTableData) !== null && _options$fullTableDat !== void 0 ? _options$fullTableDat : false,
2952
+ blockBorders: (_options$blockBorders = options === null || options === void 0 ? void 0 : options.blockBorders) !== null && _options$blockBorders !== void 0 ? _options$blockBorders : false
2953
+ };
2954
+ }
2955
+ //#endregion
2956
+ //#region src/preview/previewRendering.tsx
2957
+ async function renderPreview({ input, generationId, measureTextBatch }) {
2958
+ const layout = await prepareMarkdownLayout(input);
2959
+ const measureRequests = layout.textMeasurements.requests;
2960
+ return renderPreparedMarkdown(layout, measureTextBatch && measureRequests.length > 0 ? await measureTextBatch(measureRequests, { generationId }) : []);
2961
+ }
2962
+ async function renderPreviewPatch({ input, generationId, measureTextBatch, previousSnapshot }) {
2963
+ const preparedPatch = await prepareMarkdownPatch(previousSnapshot, input);
2964
+ const measureRequests = preparedPatch.textMeasurements.requests;
2965
+ return renderPreparedMarkdownPatch(preparedPatch, measureTextBatch && measureRequests.length > 0 ? await measureTextBatch(measureRequests, { generationId }) : []);
2966
+ }
2967
+ //#endregion
2968
+ //#region src/preview/previewPdfExport.tsx
2969
+ const PDF_MIME_TYPE = "application/pdf";
2970
+ async function exportPreviewSnapshotToPdf({ generationId, options, snapshot }) {
2971
+ var _pdfInput$renderingOp, _pdfInput$renderingOp2, _pdfInput$renderingOp3, _pdfFile$info$size;
2972
+ const normalizedOptions = normalizePdfExportOptions(options);
2973
+ const pdfInput = buildPdfRenderInput(snapshot.input, options, normalizedOptions);
2974
+ const html = buildPdfHtml(await renderPreview({
2975
+ generationId,
2976
+ input: pdfInput,
2977
+ measureTextBatch: snapshot.measureTextBatch
2978
+ }), await buildInstalledFontFaceCss(snapshot.installedFonts, [
2979
+ (_pdfInput$renderingOp = pdfInput.renderingOptions) === null || _pdfInput$renderingOp === void 0 ? void 0 : _pdfInput$renderingOp.customHeadingFont,
2980
+ (_pdfInput$renderingOp2 = pdfInput.renderingOptions) === null || _pdfInput$renderingOp2 === void 0 ? void 0 : _pdfInput$renderingOp2.customBodyFont,
2981
+ (_pdfInput$renderingOp3 = pdfInput.renderingOptions) === null || _pdfInput$renderingOp3 === void 0 ? void 0 : _pdfInput$renderingOp3.customCodeFont
2982
+ ]));
2983
+ const dimensions = pdfPageDimensions(normalizedOptions.paperSize, normalizedOptions.orientation);
2984
+ const printed = await expo_print.printToFileAsync({
2985
+ base64: false,
2986
+ height: dimensions.height,
2987
+ html,
2988
+ width: dimensions.width
2989
+ });
2990
+ const temporaryUri = printed.uri;
2991
+ const pdfFile = new expo_file_system.File(temporaryUri);
2992
+ const blob = pdfFile;
2993
+ return {
2994
+ blob,
2995
+ byteLength: typeof blob.size === "number" ? blob.size : (_pdfFile$info$size = pdfFile.info().size) !== null && _pdfFile$info$size !== void 0 ? _pdfFile$info$size : 0,
2996
+ dispose: () => expo_file_system_legacy.deleteAsync(temporaryUri, { idempotent: true }),
2997
+ mimeType: PDF_MIME_TYPE,
2998
+ pageCount: printed.numberOfPages,
2999
+ temporaryUri
3000
+ };
3001
+ }
3002
+ //#endregion
3003
+ //#region src/preview/orihaPreviewDebug.ts
3004
+ const DEFAULT_DEBUG_RENDERED_HTML_FILE_NAME = "oriha-rendered-preview.html";
3005
+ function normalizeOrihaPreviewDebugOptions(debug, formatMessage) {
3006
+ var _debug$enabled, _debug$renderedHtmlFi, _debug$shareRenderedH;
3007
+ const shareRenderedHtmlLabel = formatMessage("debug.shareRenderedHtml");
3008
+ if (debug === true) return {
3009
+ enabled: true,
3010
+ renderedHtmlFileName: DEFAULT_DEBUG_RENDERED_HTML_FILE_NAME,
3011
+ shareRenderedHtmlLabel
3012
+ };
3013
+ if (!debug) return {
3014
+ enabled: false,
3015
+ renderedHtmlFileName: DEFAULT_DEBUG_RENDERED_HTML_FILE_NAME,
3016
+ shareRenderedHtmlLabel
3017
+ };
3018
+ return {
3019
+ enabled: (_debug$enabled = debug.enabled) !== null && _debug$enabled !== void 0 ? _debug$enabled : true,
3020
+ renderedHtmlFileName: (_debug$renderedHtmlFi = debug.renderedHtmlFileName) !== null && _debug$renderedHtmlFi !== void 0 ? _debug$renderedHtmlFi : DEFAULT_DEBUG_RENDERED_HTML_FILE_NAME,
3021
+ shareRenderedHtmlLabel: (_debug$shareRenderedH = debug.shareRenderedHtmlLabel) !== null && _debug$shareRenderedH !== void 0 ? _debug$shareRenderedH : shareRenderedHtmlLabel
3022
+ };
3023
+ }
3024
+ function ensureTrailingSlash$1(value) {
3025
+ return value.endsWith("/") ? value : `${value}/`;
3026
+ }
3027
+ function sanitizeDebugRenderedHtmlFileName(value) {
3028
+ const name = value.trim().replace(/[^A-Za-z0-9._-]+/g, "-");
3029
+ const htmlName = name.length > 0 ? name : DEFAULT_DEBUG_RENDERED_HTML_FILE_NAME;
3030
+ return htmlName.toLowerCase().endsWith(".html") ? htmlName : `${htmlName}.html`;
3031
+ }
3032
+ //#endregion
3033
+ //#region src/preview/orihaPreviewPatchController.ts
3034
+ const PATCH_RESULT_TIMEOUT_MS = 1500;
3035
+ const PATCH_RESULT_MESSAGE_TYPE = "oriha.patchResult";
3036
+ const INCREMENTAL_PATCH_STRATEGY = "incremental";
3037
+ function decidePreviewPatchApplication({ generationId, hasWebView, patchOutput, previousSnapshot, webViewReady }) {
3038
+ if (!previousSnapshot) return {
3039
+ action: "fullReload",
3040
+ generationId,
3041
+ reason: "missingPreviousSnapshot"
3042
+ };
3043
+ if (patchOutput.strategy !== INCREMENTAL_PATCH_STRATEGY) return {
3044
+ action: "fullReload",
3045
+ generationId,
3046
+ reason: "replaceAllStrategy"
3047
+ };
3048
+ if (!webViewReady) return {
3049
+ action: "fullReload",
3050
+ generationId,
3051
+ reason: "webViewNotReady"
3052
+ };
3053
+ if (!hasWebView) return {
3054
+ action: "fullReload",
3055
+ generationId,
3056
+ reason: "webViewUnavailable"
3057
+ };
3058
+ return {
3059
+ action: "inject",
3060
+ generationId,
3061
+ patchCount: patchOutput.patches.length,
3062
+ script: buildPatchInjectionScript({
3063
+ generationId,
3064
+ patches: patchOutput.patches
3065
+ })
3066
+ };
3067
+ }
3068
+ function decidePreviewPatchResult({ currentGenerationId, patchResult, pendingGenerationId }) {
3069
+ const patchGenerationId = patchResult.generationId;
3070
+ const normalizedPendingGenerationId = pendingGenerationId !== null && pendingGenerationId !== void 0 ? pendingGenerationId : null;
3071
+ if (typeof patchGenerationId !== "number") return {
3072
+ action: "stale",
3073
+ currentGenerationId,
3074
+ generationId: -1,
3075
+ pendingGenerationId: normalizedPendingGenerationId
3076
+ };
3077
+ if (normalizedPendingGenerationId !== patchGenerationId || currentGenerationId !== patchGenerationId) return {
3078
+ action: "stale",
3079
+ currentGenerationId,
3080
+ generationId: patchGenerationId,
3081
+ pendingGenerationId: normalizedPendingGenerationId
3082
+ };
3083
+ if (patchResult.ok) return {
3084
+ action: "incrementalCommit",
3085
+ generationId: patchGenerationId
3086
+ };
3087
+ return {
3088
+ action: "fullFallback",
3089
+ generationId: patchGenerationId,
3090
+ message: patchResult.message
3091
+ };
3092
+ }
3093
+ function shouldRecoverPreviewSourceAfterLoad({ hasOutput, webViewSourceStale }) {
3094
+ return webViewSourceStale && hasOutput;
3095
+ }
3096
+ function buildPatchInjectionScript({ generationId, patches }) {
3097
+ return `
3098
+ (function() {
3099
+ var payload = ${JSON.stringify({
3100
+ generationId,
3101
+ patches
3102
+ })};
3103
+ var ok = false;
3104
+ var message = null;
3105
+ try {
3106
+ ok = Boolean(window.orihaApplyPatch && window.orihaApplyPatch(payload));
3107
+ } catch (error) {
3108
+ ok = false;
3109
+ message = error && error.message ? String(error.message) : String(error);
3110
+ }
3111
+ if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
3112
+ window.ReactNativeWebView.postMessage(JSON.stringify({
3113
+ type: "${PATCH_RESULT_MESSAGE_TYPE}",
3114
+ generationId: payload.generationId,
3115
+ ok: ok,
3116
+ message: message
3117
+ }));
3118
+ }
3119
+ true;
3120
+ })();
3121
+ `;
3122
+ }
3123
+ //#endregion
3124
+ //#region src/preview/stableSerialize.ts
3125
+ function stableSerialize(value) {
3126
+ return JSON.stringify(stableSerializableValue(value));
3127
+ }
3128
+ function stableSerializableValue(value) {
3129
+ if (Array.isArray(value)) return value.map(stableSerializableValue);
3130
+ if (value !== null && typeof value === "object") {
3131
+ const sortedValue = {};
3132
+ for (const [key, childValue] of Object.entries(value).sort(([left], [right]) => left.localeCompare(right))) if (childValue !== void 0) sortedValue[key] = stableSerializableValue(childValue);
3133
+ return sortedValue;
3134
+ }
3135
+ return value;
3136
+ }
3137
+ //#endregion
3138
+ //#region src/preview/previewLogs.tsx
3139
+ function debugLogIfEnabled(enabled, event, payload) {
3140
+ if (enabled) debugLog(event, payload);
3141
+ }
3142
+ function debugLog(event, payload) {
3143
+ console.debug("[OrihaPreview]", {
3144
+ event,
3145
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3146
+ ...payload
3147
+ });
3148
+ }
3149
+ function formatDebugError(error) {
3150
+ return error instanceof Error ? error.message : String(error);
3151
+ }
3152
+ function formatError(error) {
3153
+ return error instanceof Error ? error.message : String(error);
3154
+ }
3155
+ //#endregion
3156
+ //#region src/preview/previewRenderEffect.tsx
3157
+ function usePreviewRenderingEffect({ generationRef, latestPreviewInputRef, clearPendingPatch, latestPatchSnapshotRef, latestOutputRef, setError, setOutput, setRenderedInput, setRenderedInputKey, webViewRef, webViewReadyRef, setPendingPatch, commitFullPatchRender, latestViewerFontFaceCssRef, latestOnRenderedRef, latestOnRenderErrorRef, lifecycleDebugEnabled, previewInputKey, measureTextBatch }) {
3158
+ (0, react.useEffect)(() => {
3159
+ let cancelled = false;
3160
+ const generationId = generationRef.current + 1;
3161
+ generationRef.current = generationId;
3162
+ const inputForRender = latestPreviewInputRef.current;
3163
+ const hadPendingPatch = clearPendingPatch() !== null;
3164
+ const previousSnapshot = hadPendingPatch ? null : latestPatchSnapshotRef.current;
3165
+ if (!inputForRender) return;
3166
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:start", {
3167
+ generationId,
3168
+ inputKeyLength: previewInputKey.length,
3169
+ markdownLength: inputForRender.markdown.length,
3170
+ hadOutput: Boolean(latestOutputRef.current),
3171
+ hadPendingPatch,
3172
+ hadSnapshot: Boolean(previousSnapshot)
3173
+ });
3174
+ setError(null);
3175
+ if (!latestOutputRef.current) {
3176
+ setOutput(null);
3177
+ setRenderedInput(null);
3178
+ setRenderedInputKey(null);
3179
+ }
3180
+ renderPreviewPatch({
3181
+ input: inputForRender,
3182
+ generationId,
3183
+ measureTextBatch,
3184
+ previousSnapshot
3185
+ }).then((nextPatchOutput) => {
3186
+ var _nextPatchOutput$outp, _nextPatchOutput$outp2, _latestOnRenderedRef$;
3187
+ if (cancelled) return;
3188
+ if (generationRef.current !== generationId) return;
3189
+ const patchApplicationDecision = decidePreviewPatchApplication({
3190
+ generationId,
3191
+ hasWebView: Boolean(webViewRef.current),
3192
+ patchOutput: nextPatchOutput,
3193
+ previousSnapshot,
3194
+ webViewReady: webViewReadyRef.current
3195
+ });
3196
+ if (patchApplicationDecision.action === "inject") {
3197
+ var _webViewRef$current;
3198
+ setPendingPatch({
3199
+ generationId,
3200
+ input: inputForRender,
3201
+ inputKey: previewInputKey,
3202
+ patchOutput: nextPatchOutput
3203
+ });
3204
+ (_webViewRef$current = webViewRef.current) === null || _webViewRef$current === void 0 || _webViewRef$current.injectJavaScript(patchApplicationDecision.script);
3205
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:patch-injected", {
3206
+ generationId,
3207
+ patchCount: patchApplicationDecision.patchCount
3208
+ });
3209
+ return;
3210
+ }
3211
+ commitFullPatchRender(nextPatchOutput, inputForRender, previewInputKey, latestViewerFontFaceCssRef.current);
3212
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:ready", {
3213
+ generationId,
3214
+ cssLength: (_nextPatchOutput$outp = (_nextPatchOutput$outp2 = nextPatchOutput.output.css) === null || _nextPatchOutput$outp2 === void 0 ? void 0 : _nextPatchOutput$outp2.length) !== null && _nextPatchOutput$outp !== void 0 ? _nextPatchOutput$outp : 0,
3215
+ htmlLength: nextPatchOutput.output.html.length,
3216
+ strategy: nextPatchOutput.strategy
3217
+ });
3218
+ (_latestOnRenderedRef$ = latestOnRenderedRef.current) === null || _latestOnRenderedRef$ === void 0 || _latestOnRenderedRef$.call(latestOnRenderedRef, nextPatchOutput.output);
3219
+ }).catch((nextError) => {
3220
+ var _latestOnRenderErrorR;
3221
+ if (cancelled) return;
3222
+ if (generationRef.current !== generationId) return;
3223
+ setError(nextError);
3224
+ if (!latestOutputRef.current) {
3225
+ setRenderedInput(null);
3226
+ setRenderedInputKey(null);
3227
+ }
3228
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:error", {
3229
+ generationId,
3230
+ message: formatDebugError(nextError)
3231
+ });
3232
+ (_latestOnRenderErrorR = latestOnRenderErrorRef.current) === null || _latestOnRenderErrorR === void 0 || _latestOnRenderErrorR.call(latestOnRenderErrorRef, nextError);
3233
+ });
3234
+ return () => {
3235
+ cancelled = true;
3236
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:cancel", { generationId });
3237
+ };
3238
+ }, [
3239
+ clearPendingPatch,
3240
+ commitFullPatchRender,
3241
+ generationRef,
3242
+ latestOnRenderErrorRef,
3243
+ latestOnRenderedRef,
3244
+ latestOutputRef,
3245
+ latestPatchSnapshotRef,
3246
+ latestPreviewInputRef,
3247
+ latestViewerFontFaceCssRef,
3248
+ lifecycleDebugEnabled,
3249
+ measureTextBatch,
3250
+ previewInputKey,
3251
+ setError,
3252
+ setOutput,
3253
+ setPendingPatch,
3254
+ setRenderedInput,
3255
+ setRenderedInputKey,
3256
+ webViewReadyRef,
3257
+ webViewRef
3258
+ ]);
3259
+ }
3260
+ //#endregion
3261
+ //#region src/preview/previewRenderController.tsx
3262
+ const EMPTY_INSTALLED_FONTS = [];
3263
+ function usePreviewRenderController({ markdown, input, debug, onRendered, onRenderError, oriha }) {
3264
+ var _oriha$formatMessage, _oriha$fontRegistry$i, _previewInput$renderi4, _previewInput$renderi5, _previewInput$renderi6;
3265
+ const generationRef = (0, react.useRef)(0);
3266
+ const latestOnRenderedRef = (0, react.useRef)(onRendered);
3267
+ const latestOnRenderErrorRef = (0, react.useRef)(onRenderError);
3268
+ const latestPreviewInputRef = (0, react.useRef)(null);
3269
+ const latestOutputRef = (0, react.useRef)(null);
3270
+ const latestPatchSnapshotRef = (0, react.useRef)(null);
3271
+ const latestViewerFontFaceCssRef = (0, react.useRef)("");
3272
+ const pendingPatchRef = (0, react.useRef)(null);
3273
+ const webViewReadyRef = (0, react.useRef)(false);
3274
+ const webViewSourceStaleRef = (0, react.useRef)(false);
3275
+ const webViewRef = (0, react.useRef)(null);
3276
+ const [output, setOutput] = (0, react.useState)(null);
3277
+ const [error, setError] = (0, react.useState)(null);
3278
+ const [webViewHtml, setWebViewHtml] = (0, react.useState)("");
3279
+ const [renderedInput, setRenderedInput] = (0, react.useState)(null);
3280
+ const [renderedInputKey, setRenderedInputKey] = (0, react.useState)(null);
3281
+ const [viewerFontFaceCss, setViewerFontFaceCss] = (0, react.useState)("");
3282
+ const [viewerFontFaceCssReady, setViewerFontFaceCssReady] = (0, react.useState)(false);
3283
+ const [viewerFontFaceCssError, setViewerFontFaceCssError] = (0, react.useState)(null);
3284
+ const formatMessage = (_oriha$formatMessage = oriha === null || oriha === void 0 ? void 0 : oriha.formatMessage) !== null && _oriha$formatMessage !== void 0 ? _oriha$formatMessage : defaultOrihaFormatMessage;
3285
+ const debugOptions = normalizeOrihaPreviewDebugOptions(debug, formatMessage);
3286
+ const lifecycleDebugEnabled = debug === true || typeof debug === "object" && debug !== null;
3287
+ const installedFonts = (_oriha$fontRegistry$i = oriha === null || oriha === void 0 ? void 0 : oriha.fontRegistry.installedFonts) !== null && _oriha$fontRegistry$i !== void 0 ? _oriha$fontRegistry$i : EMPTY_INSTALLED_FONTS;
3288
+ const latestInstalledFontsRef = (0, react.useRef)(installedFonts);
3289
+ const previewInput = (0, react.useMemo)(() => {
3290
+ var _input$renderingOptio;
3291
+ return normalizeBridgeRenderInput({
3292
+ plan: "free",
3293
+ locale: oriha === null || oriha === void 0 ? void 0 : oriha.i18n.locale,
3294
+ ...input,
3295
+ renderingOptions: {
3296
+ colorScheme: "light",
3297
+ ...(_input$renderingOptio = input === null || input === void 0 ? void 0 : input.renderingOptions) !== null && _input$renderingOptio !== void 0 ? _input$renderingOptio : {}
3298
+ },
3299
+ markdown
3300
+ });
3301
+ }, [
3302
+ input,
3303
+ markdown,
3304
+ oriha === null || oriha === void 0 ? void 0 : oriha.i18n.locale
3305
+ ]);
3306
+ const previewInputKey = (0, react.useMemo)(() => stableSerialize(previewInput), [previewInput]);
3307
+ const installedFontsKey = (0, react.useMemo)(() => stableSerialize(installedFonts), [installedFonts]);
3308
+ latestPreviewInputRef.current = previewInput;
3309
+ latestOnRenderedRef.current = onRendered;
3310
+ latestOnRenderErrorRef.current = onRenderError;
3311
+ latestViewerFontFaceCssRef.current = viewerFontFaceCss;
3312
+ const selectedPreviewFontSpecs = (0, react.useMemo)(() => {
3313
+ var _previewInput$renderi, _previewInput$renderi2, _previewInput$renderi3;
3314
+ return [
3315
+ (_previewInput$renderi = previewInput.renderingOptions) === null || _previewInput$renderi === void 0 ? void 0 : _previewInput$renderi.customHeadingFont,
3316
+ (_previewInput$renderi2 = previewInput.renderingOptions) === null || _previewInput$renderi2 === void 0 ? void 0 : _previewInput$renderi2.customBodyFont,
3317
+ (_previewInput$renderi3 = previewInput.renderingOptions) === null || _previewInput$renderi3 === void 0 ? void 0 : _previewInput$renderi3.customCodeFont
3318
+ ];
3319
+ }, [
3320
+ (_previewInput$renderi4 = previewInput.renderingOptions) === null || _previewInput$renderi4 === void 0 ? void 0 : _previewInput$renderi4.customBodyFont,
3321
+ (_previewInput$renderi5 = previewInput.renderingOptions) === null || _previewInput$renderi5 === void 0 ? void 0 : _previewInput$renderi5.customCodeFont,
3322
+ (_previewInput$renderi6 = previewInput.renderingOptions) === null || _previewInput$renderi6 === void 0 ? void 0 : _previewInput$renderi6.customHeadingFont
3323
+ ]);
3324
+ const latestSelectedPreviewFontSpecsRef = (0, react.useRef)(selectedPreviewFontSpecs);
3325
+ latestInstalledFontsRef.current = installedFonts;
3326
+ latestOutputRef.current = output;
3327
+ latestSelectedPreviewFontSpecsRef.current = selectedPreviewFontSpecs;
3328
+ const selectedPreviewFontSpecsKey = (0, react.useMemo)(() => stableSerialize(selectedPreviewFontSpecs), [selectedPreviewFontSpecs]);
3329
+ const clearPendingPatch = (0, react.useCallback)(function clearPendingPatch() {
3330
+ const pendingPatch = pendingPatchRef.current;
3331
+ if (pendingPatch === null || pendingPatch === void 0 ? void 0 : pendingPatch.timeoutId) clearTimeout(pendingPatch.timeoutId);
3332
+ pendingPatchRef.current = null;
3333
+ return pendingPatch;
3334
+ }, []);
3335
+ const commitFullPatchRender = (0, react.useCallback)(function commitFullPatchRender(patchOutput, nextInput, nextInputKey, fontFaceCss) {
3336
+ const nextOutput = patchOutput.output;
3337
+ const nextHtml = buildViewerHtml(nextOutput, fontFaceCss);
3338
+ latestOutputRef.current = nextOutput;
3339
+ latestPatchSnapshotRef.current = patchOutput.snapshot;
3340
+ webViewSourceStaleRef.current = false;
3341
+ clearPendingPatch();
3342
+ webViewReadyRef.current = false;
3343
+ setWebViewHtml(nextHtml);
3344
+ setOutput(nextOutput);
3345
+ setError(null);
3346
+ setRenderedInput(nextInput);
3347
+ setRenderedInputKey(nextInputKey);
3348
+ }, [clearPendingPatch]);
3349
+ const commitIncrementalPatchRender = (0, react.useCallback)(function commitIncrementalPatchRender(patchOutput, nextInput, nextInputKey) {
3350
+ const nextOutput = patchOutput.output;
3351
+ latestOutputRef.current = nextOutput;
3352
+ latestPatchSnapshotRef.current = patchOutput.snapshot;
3353
+ webViewSourceStaleRef.current = true;
3354
+ clearPendingPatch();
3355
+ setOutput(nextOutput);
3356
+ setError(null);
3357
+ setRenderedInput(nextInput);
3358
+ setRenderedInputKey(nextInputKey);
3359
+ }, [clearPendingPatch]);
3360
+ const setPendingPatch = (0, react.useCallback)(function setPendingPatch(pendingPatch) {
3361
+ pendingPatch.timeoutId = setTimeout(() => {
3362
+ var _latestOnRenderedRef$;
3363
+ if (pendingPatchRef.current !== pendingPatch || generationRef.current !== pendingPatch.generationId) return;
3364
+ commitFullPatchRender(pendingPatch.patchOutput, pendingPatch.input, pendingPatch.inputKey, latestViewerFontFaceCssRef.current);
3365
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:patch-timeout", { generationId: pendingPatch.generationId });
3366
+ (_latestOnRenderedRef$ = latestOnRenderedRef.current) === null || _latestOnRenderedRef$ === void 0 || _latestOnRenderedRef$.call(latestOnRenderedRef, pendingPatch.patchOutput.output);
3367
+ }, PATCH_RESULT_TIMEOUT_MS);
3368
+ pendingPatchRef.current = pendingPatch;
3369
+ }, [commitFullPatchRender, lifecycleDebugEnabled]);
3370
+ (0, react.useEffect)(() => () => {
3371
+ clearPendingPatch();
3372
+ }, [clearPendingPatch]);
3373
+ (0, react.useEffect)(() => {
3374
+ let cancelled = false;
3375
+ const activeInstalledFonts = latestInstalledFontsRef.current;
3376
+ const activeSelectedPreviewFontSpecs = latestSelectedPreviewFontSpecsRef.current;
3377
+ setViewerFontFaceCssReady(false);
3378
+ setViewerFontFaceCssError(null);
3379
+ buildInstalledFontFaceCss(activeInstalledFonts, activeSelectedPreviewFontSpecs).then((nextFontFaceCss) => {
3380
+ if (cancelled) return;
3381
+ setViewerFontFaceCss(nextFontFaceCss);
3382
+ setViewerFontFaceCssReady(true);
3383
+ }).catch((nextError) => {
3384
+ var _latestOnRenderErrorR;
3385
+ if (cancelled) return;
3386
+ setViewerFontFaceCss("");
3387
+ setViewerFontFaceCssError(nextError);
3388
+ setViewerFontFaceCssReady(true);
3389
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:font-css-error", { message: formatDebugError(nextError) });
3390
+ (_latestOnRenderErrorR = latestOnRenderErrorRef.current) === null || _latestOnRenderErrorR === void 0 || _latestOnRenderErrorR.call(latestOnRenderErrorRef, nextError);
3391
+ });
3392
+ return () => {
3393
+ cancelled = true;
3394
+ };
3395
+ }, [
3396
+ installedFontsKey,
3397
+ lifecycleDebugEnabled,
3398
+ selectedPreviewFontSpecsKey
3399
+ ]);
3400
+ usePreviewRenderingEffect({
3401
+ generationRef,
3402
+ latestPreviewInputRef,
3403
+ clearPendingPatch,
3404
+ latestPatchSnapshotRef,
3405
+ latestOutputRef,
3406
+ setError,
3407
+ setOutput,
3408
+ setRenderedInput,
3409
+ setRenderedInputKey,
3410
+ webViewRef,
3411
+ webViewReadyRef,
3412
+ setPendingPatch,
3413
+ commitFullPatchRender,
3414
+ latestViewerFontFaceCssRef,
3415
+ latestOnRenderedRef,
3416
+ latestOnRenderErrorRef,
3417
+ lifecycleDebugEnabled,
3418
+ previewInputKey,
3419
+ measureTextBatch: oriha === null || oriha === void 0 ? void 0 : oriha.measureTextBatch
3420
+ });
3421
+ (0, react.useEffect)(() => {
3422
+ if (!viewerFontFaceCssReady || !latestOutputRef.current) return;
3423
+ const pendingPatch = pendingPatchRef.current;
3424
+ if (pendingPatch) {
3425
+ var _latestOnRenderedRef$2;
3426
+ commitFullPatchRender(pendingPatch.patchOutput, pendingPatch.input, pendingPatch.inputKey, viewerFontFaceCss);
3427
+ (_latestOnRenderedRef$2 = latestOnRenderedRef.current) === null || _latestOnRenderedRef$2 === void 0 || _latestOnRenderedRef$2.call(latestOnRenderedRef, pendingPatch.patchOutput.output);
3428
+ return;
3429
+ }
3430
+ const nextHtml = buildViewerHtml(latestOutputRef.current, viewerFontFaceCss);
3431
+ clearPendingPatch();
3432
+ webViewSourceStaleRef.current = false;
3433
+ webViewReadyRef.current = false;
3434
+ setWebViewHtml(nextHtml);
3435
+ }, [
3436
+ viewerFontFaceCss,
3437
+ viewerFontFaceCssReady,
3438
+ commitFullPatchRender,
3439
+ clearPendingPatch
3440
+ ]);
3441
+ return {
3442
+ generationRef,
3443
+ latestOnRenderedRef,
3444
+ latestOnRenderErrorRef,
3445
+ latestOutputRef,
3446
+ latestViewerFontFaceCssRef,
3447
+ pendingPatchRef,
3448
+ webViewReadyRef,
3449
+ webViewSourceStaleRef,
3450
+ webViewRef,
3451
+ output,
3452
+ error,
3453
+ webViewHtml,
3454
+ renderedInput,
3455
+ renderedInputKey,
3456
+ viewerFontFaceCss,
3457
+ viewerFontFaceCssReady,
3458
+ viewerFontFaceCssError,
3459
+ formatMessage,
3460
+ debugOptions,
3461
+ lifecycleDebugEnabled,
3462
+ installedFonts,
3463
+ previewInput,
3464
+ previewInputKey,
3465
+ commitFullPatchRender,
3466
+ commitIncrementalPatchRender,
3467
+ clearPendingPatch,
3468
+ setWebViewHtml
3469
+ };
3470
+ }
3471
+ //#endregion
3472
+ //#region src/preview/previewLinks.tsx
3473
+ function handleExternalLinkMessage(data, showToast, formatMessage = defaultOrihaFormatMessage) {
3474
+ let message;
3475
+ try {
3476
+ message = JSON.parse(data);
3477
+ } catch {
3478
+ return;
3479
+ }
3480
+ if (message.type !== "oriha.openExternalLink" || !message.url) return;
3481
+ if (!shouldOpenExternally(message.url)) return;
3482
+ openExternalUrl(message.url, showToast, formatMessage);
3483
+ }
3484
+ function openExternalUrl(url, showToast, formatMessage = defaultOrihaFormatMessage) {
3485
+ react_native.Linking.openURL(url).catch(() => {
3486
+ showToast === null || showToast === void 0 || showToast(formatMessage("externalLink.openFailed"), {
3487
+ position: "top",
3488
+ variant: "err"
3489
+ });
3490
+ });
3491
+ }
3492
+ function handleCodeCopyMessage(data, showToast, formatMessage = defaultOrihaFormatMessage) {
3493
+ var _message$message;
3494
+ if (!showToast) return;
3495
+ let message;
3496
+ try {
3497
+ message = JSON.parse(data);
3498
+ } catch {
3499
+ return;
3500
+ }
3501
+ if (message.type !== "oriha.codeCopyResult") return;
3502
+ const isError = message.status === "error";
3503
+ showToast((_message$message = message.message) !== null && _message$message !== void 0 ? _message$message : formatMessage(isError ? "codeCopy.failure" : "codeCopy.success"), {
3504
+ position: "top",
3505
+ variant: isError ? "err" : "success"
3506
+ });
3507
+ }
3508
+ //#endregion
3509
+ //#region src/preview/previewViewerEvents.tsx
3510
+ function usePreviewViewerEvents({ state, webViewProps, oriha }) {
3511
+ const { pendingPatchRef, generationRef, commitIncrementalPatchRender, commitFullPatchRender, latestViewerFontFaceCssRef, latestOnRenderedRef, webViewReadyRef, latestOutputRef, webViewSourceStaleRef, setWebViewHtml, formatMessage, lifecycleDebugEnabled } = state;
3512
+ return {
3513
+ handleViewerMessage: (0, react.useMemo)(() => {
3514
+ const onMessage = webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onMessage;
3515
+ return (event) => {
3516
+ const patchResult = parseViewerPatchResultMessage(event.nativeEvent.data);
3517
+ if (patchResult) {
3518
+ const pendingPatch = pendingPatchRef.current;
3519
+ const patchResultDecision = decidePreviewPatchResult({
3520
+ currentGenerationId: generationRef.current,
3521
+ patchResult,
3522
+ pendingGenerationId: pendingPatch === null || pendingPatch === void 0 ? void 0 : pendingPatch.generationId
3523
+ });
3524
+ if (pendingPatch) {
3525
+ var _latestOnRenderedRef$;
3526
+ if (patchResultDecision.action === "incrementalCommit") {
3527
+ commitIncrementalPatchRender(pendingPatch.patchOutput, pendingPatch.input, pendingPatch.inputKey);
3528
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:patch-ready", {
3529
+ generationId: pendingPatch.generationId,
3530
+ patchCount: pendingPatch.patchOutput.patches.length
3531
+ });
3532
+ } else if (patchResultDecision.action === "fullFallback") {
3533
+ var _patchResultDecision$;
3534
+ commitFullPatchRender(pendingPatch.patchOutput, pendingPatch.input, pendingPatch.inputKey, latestViewerFontFaceCssRef.current);
3535
+ debugLogIfEnabled(lifecycleDebugEnabled, "render:patch-fallback", {
3536
+ generationId: pendingPatch.generationId,
3537
+ message: (_patchResultDecision$ = patchResultDecision.message) !== null && _patchResultDecision$ !== void 0 ? _patchResultDecision$ : null
3538
+ });
3539
+ } else return;
3540
+ (_latestOnRenderedRef$ = latestOnRenderedRef.current) === null || _latestOnRenderedRef$ === void 0 || _latestOnRenderedRef$.call(latestOnRenderedRef, pendingPatch.patchOutput.output);
3541
+ }
3542
+ return;
3543
+ }
3544
+ handleExternalLinkMessage(event.nativeEvent.data, oriha === null || oriha === void 0 ? void 0 : oriha.showToast, formatMessage);
3545
+ handleCodeCopyMessage(event.nativeEvent.data, oriha === null || oriha === void 0 ? void 0 : oriha.showToast, formatMessage);
3546
+ onMessage === null || onMessage === void 0 || onMessage(event);
3547
+ };
3548
+ }, [
3549
+ commitFullPatchRender,
3550
+ commitIncrementalPatchRender,
3551
+ formatMessage,
3552
+ generationRef,
3553
+ latestOnRenderedRef,
3554
+ latestViewerFontFaceCssRef,
3555
+ lifecycleDebugEnabled,
3556
+ oriha === null || oriha === void 0 ? void 0 : oriha.showToast,
3557
+ pendingPatchRef,
3558
+ webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onMessage
3559
+ ]),
3560
+ handleViewerLoadStart: (0, react.useMemo)(() => {
3561
+ const onLoadStart = webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onLoadStart;
3562
+ return (event) => {
3563
+ webViewReadyRef.current = false;
3564
+ onLoadStart === null || onLoadStart === void 0 || onLoadStart(event);
3565
+ };
3566
+ }, [webViewReadyRef, webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onLoadStart]),
3567
+ handleViewerLoadEnd: (0, react.useMemo)(() => {
3568
+ const onLoadEnd = webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onLoadEnd;
3569
+ return (event) => {
3570
+ webViewReadyRef.current = true;
3571
+ const latestOutput = latestOutputRef.current;
3572
+ if (latestOutput && shouldRecoverPreviewSourceAfterLoad({
3573
+ hasOutput: true,
3574
+ webViewSourceStale: webViewSourceStaleRef.current
3575
+ })) {
3576
+ webViewSourceStaleRef.current = false;
3577
+ webViewReadyRef.current = false;
3578
+ setWebViewHtml(buildViewerHtml(latestOutput, latestViewerFontFaceCssRef.current));
3579
+ }
3580
+ onLoadEnd === null || onLoadEnd === void 0 || onLoadEnd(event);
3581
+ };
3582
+ }, [
3583
+ latestOutputRef,
3584
+ latestViewerFontFaceCssRef,
3585
+ setWebViewHtml,
3586
+ webViewReadyRef,
3587
+ webViewSourceStaleRef,
3588
+ webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onLoadEnd
3589
+ ]),
3590
+ handleShouldStartLoadWithRequest: (0, react.useMemo)(() => {
3591
+ const onShouldStartLoadWithRequest = webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onShouldStartLoadWithRequest;
3592
+ return (request) => {
3593
+ var _onShouldStartLoadWit;
3594
+ if (shouldOpenExternally(request.url)) {
3595
+ openExternalUrl(request.url, oriha === null || oriha === void 0 ? void 0 : oriha.showToast, formatMessage);
3596
+ return false;
3597
+ }
3598
+ return (_onShouldStartLoadWit = onShouldStartLoadWithRequest === null || onShouldStartLoadWithRequest === void 0 ? void 0 : onShouldStartLoadWithRequest(request)) !== null && _onShouldStartLoadWit !== void 0 ? _onShouldStartLoadWit : true;
3599
+ };
3600
+ }, [
3601
+ formatMessage,
3602
+ oriha === null || oriha === void 0 ? void 0 : oriha.showToast,
3603
+ webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.onShouldStartLoadWithRequest
3604
+ ])
3605
+ };
3606
+ }
3607
+ //#endregion
3608
+ //#region src/preview/previewDebugExport.tsx
3609
+ async function saveRenderedHtmlDebugFile(html, fileName, unavailableMessage) {
3610
+ var _FileSystem$cacheDire;
3611
+ const rootDirectory = (_FileSystem$cacheDire = expo_file_system_legacy.cacheDirectory) !== null && _FileSystem$cacheDire !== void 0 ? _FileSystem$cacheDire : expo_file_system_legacy.documentDirectory;
3612
+ if (!rootDirectory) throw new Error(unavailableMessage);
3613
+ const directory = `${ensureTrailingSlash$1(rootDirectory)}oriha-debug/`;
3614
+ await expo_file_system_legacy.makeDirectoryAsync(directory, { intermediates: true });
3615
+ const fileUri = `${directory}${sanitizeDebugRenderedHtmlFileName(fileName)}`;
3616
+ await expo_file_system_legacy.writeAsStringAsync(fileUri, html, { encoding: expo_file_system_legacy.EncodingType.UTF8 });
3617
+ return fileUri;
3618
+ }
3619
+ //#endregion
3620
+ //#region src/preview/previewStyles.tsx
3621
+ const styles = react_native.StyleSheet.create({
3622
+ previewContainer: { flex: 1 },
3623
+ webView: {
3624
+ backgroundColor: "transparent",
3625
+ flex: 1
3626
+ },
3627
+ debugOverlay: {
3628
+ alignItems: "flex-end",
3629
+ bottom: 18,
3630
+ gap: 8,
3631
+ left: 16,
3632
+ position: "absolute",
3633
+ right: 16
3634
+ },
3635
+ debugButton: {
3636
+ alignItems: "center",
3637
+ backgroundColor: "#0f172a",
3638
+ borderColor: "#020617",
3639
+ borderRadius: 8,
3640
+ borderWidth: react_native.StyleSheet.hairlineWidth,
3641
+ justifyContent: "center",
3642
+ minHeight: 42,
3643
+ paddingHorizontal: 14
3644
+ },
3645
+ debugButtonPressed: { opacity: .8 },
3646
+ debugButtonText: {
3647
+ color: "#ffffff",
3648
+ fontSize: 13,
3649
+ fontWeight: "700"
3650
+ }
3651
+ });
3652
+ //#endregion
3653
+ //#region src/preview/OrihaPreview.tsx
3654
+ const OrihaPreview = react.default.forwardRef(function OrihaPreview({ markdown, input, loadingFallback, debug, onRendered, onRenderError, webViewProps }, ref) {
3655
+ var _webViewProps$allowFi;
3656
+ const oriha = useOrihaContext();
3657
+ const pdfGenerationRef = (0, react.useRef)(0);
3658
+ const exportSnapshotRef = (0, react.useRef)(null);
3659
+ const renderState = usePreviewRenderController({
3660
+ markdown,
3661
+ input,
3662
+ debug,
3663
+ onRendered,
3664
+ onRenderError,
3665
+ oriha
3666
+ });
3667
+ const { output, error, webViewHtml, renderedInput, renderedInputKey, viewerFontFaceCss, viewerFontFaceCssReady, viewerFontFaceCssError, formatMessage, debugOptions, lifecycleDebugEnabled, installedFonts, previewInput, previewInputKey, webViewRef } = renderState;
3668
+ const { style: webViewStyle, ...webViewRestProps } = webViewProps !== null && webViewProps !== void 0 ? webViewProps : {};
3669
+ (0, react.useEffect)(() => {
3670
+ exportSnapshotRef.current = {
3671
+ input: renderedInput !== null && renderedInput !== void 0 ? renderedInput : previewInput,
3672
+ installedFonts: [...installedFonts],
3673
+ isReady: Boolean(output) && !error && !viewerFontFaceCssError && viewerFontFaceCssReady && renderedInputKey === previewInputKey,
3674
+ measureTextBatch: oriha === null || oriha === void 0 ? void 0 : oriha.measureTextBatch
3675
+ };
3676
+ }, [
3677
+ error,
3678
+ installedFonts,
3679
+ oriha === null || oriha === void 0 ? void 0 : oriha.measureTextBatch,
3680
+ output,
3681
+ previewInput,
3682
+ previewInputKey,
3683
+ renderedInput,
3684
+ renderedInputKey,
3685
+ viewerFontFaceCssError,
3686
+ viewerFontFaceCssReady
3687
+ ]);
3688
+ (0, react.useImperativeHandle)(ref, () => ({ exportPdf: async (options) => {
3689
+ var _snapshot$isReady, _result$pageCount;
3690
+ const snapshot = exportSnapshotRef.current;
3691
+ debugLogIfEnabled(lifecycleDebugEnabled, "exportPdf:requested", {
3692
+ hasSnapshot: Boolean(snapshot),
3693
+ isReady: (_snapshot$isReady = snapshot === null || snapshot === void 0 ? void 0 : snapshot.isReady) !== null && _snapshot$isReady !== void 0 ? _snapshot$isReady : false,
3694
+ options
3695
+ });
3696
+ if (!(snapshot === null || snapshot === void 0 ? void 0 : snapshot.isReady)) throw new Error("Markdown preview is not ready for PDF export");
3697
+ pdfGenerationRef.current += 1;
3698
+ const generationId = -pdfGenerationRef.current;
3699
+ const result = await exportPreviewSnapshotToPdf({
3700
+ generationId: -pdfGenerationRef.current,
3701
+ options,
3702
+ snapshot
3703
+ });
3704
+ debugLogIfEnabled(lifecycleDebugEnabled, "exportPdf:ready", {
3705
+ byteLength: result.byteLength,
3706
+ generationId,
3707
+ pageCount: (_result$pageCount = result.pageCount) !== null && _result$pageCount !== void 0 ? _result$pageCount : null
3708
+ });
3709
+ return result;
3710
+ } }), [lifecycleDebugEnabled]);
3711
+ const { handleViewerMessage, handleViewerLoadStart, handleViewerLoadEnd, handleShouldStartLoadWithRequest } = usePreviewViewerEvents({
3712
+ state: renderState,
3713
+ webViewProps,
3714
+ oriha
3715
+ });
3716
+ const shareRenderedHtml = async () => {
3717
+ if (!debugViewerHtml) return;
3718
+ try {
3719
+ const fileUri = await saveRenderedHtmlDebugFile(debugViewerHtml, debugOptions.renderedHtmlFileName, formatMessage("debug.fileSystemDirectoryUnavailable"));
3720
+ if (await expo_sharing.isAvailableAsync()) await expo_sharing.shareAsync(fileUri, {
3721
+ dialogTitle: formatMessage("debug.shareDialogTitle"),
3722
+ mimeType: "text/html",
3723
+ UTI: "public.html"
3724
+ });
3725
+ else {
3726
+ var _oriha$showToast;
3727
+ oriha === null || oriha === void 0 || (_oriha$showToast = oriha.showToast) === null || _oriha$showToast === void 0 || _oriha$showToast.call(oriha, formatMessage("debug.renderedHtmlSaved", { fileUri }), {
3728
+ position: "top",
3729
+ variant: "success"
3730
+ });
3731
+ }
3732
+ } catch (nextError) {
3733
+ var _oriha$showToast2;
3734
+ const message = formatMessage("debug.shareFailed", { message: formatError(nextError) });
3735
+ oriha === null || oriha === void 0 || (_oriha$showToast2 = oriha.showToast) === null || _oriha$showToast2 === void 0 || _oriha$showToast2.call(oriha, message, {
3736
+ position: "top",
3737
+ variant: "err"
3738
+ });
3739
+ }
3740
+ };
3741
+ const previewError = error !== null && error !== void 0 ? error : viewerFontFaceCssError;
3742
+ const debugViewerHtml = (0, react.useMemo)(() => output ? buildViewerHtml(output, viewerFontFaceCss) : webViewHtml, [
3743
+ output,
3744
+ viewerFontFaceCss,
3745
+ webViewHtml
3746
+ ]);
3747
+ const webViewSource = (0, react.useMemo)(() => ({ html: webViewHtml }), [webViewHtml]);
3748
+ const showPreviewLoading = shouldShowPreviewLoading(output, previewError);
3749
+ (0, react.useEffect)(() => {
3750
+ if (!lifecycleDebugEnabled || !showPreviewLoading && !previewError) return;
3751
+ debugLog("view-state", {
3752
+ hasOutput: Boolean(output),
3753
+ hasPreviewError: Boolean(previewError),
3754
+ renderedInputMatches: renderedInputKey === previewInputKey,
3755
+ showPreviewLoading,
3756
+ viewerHtmlLength: debugViewerHtml.length
3757
+ });
3758
+ }, [
3759
+ debugViewerHtml.length,
3760
+ lifecycleDebugEnabled,
3761
+ output,
3762
+ previewError,
3763
+ previewInputKey,
3764
+ renderedInputKey,
3765
+ showPreviewLoading
3766
+ ]);
3767
+ if (showPreviewLoading) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
3768
+ style: [styles.previewContainer, webViewStyle],
3769
+ children: loadingFallback !== null && loadingFallback !== void 0 ? loadingFallback : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.ActivityIndicator, {})
3770
+ });
3771
+ if (!output || previewError) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, { style: [styles.previewContainer, webViewStyle] });
3772
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.View, {
3773
+ style: [styles.previewContainer, webViewStyle],
3774
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native_webview.WebView, {
3775
+ ...webViewRestProps,
3776
+ ref: webViewRef,
3777
+ allowFileAccess: (_webViewProps$allowFi = webViewProps === null || webViewProps === void 0 ? void 0 : webViewProps.allowFileAccess) !== null && _webViewProps$allowFi !== void 0 ? _webViewProps$allowFi : true,
3778
+ originWhitelist: ["*"],
3779
+ onLoadEnd: handleViewerLoadEnd,
3780
+ onLoadStart: handleViewerLoadStart,
3781
+ onMessage: handleViewerMessage,
3782
+ onShouldStartLoadWithRequest: handleShouldStartLoadWithRequest,
3783
+ source: webViewSource,
3784
+ style: styles.webView
3785
+ }), debugOptions.enabled ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
3786
+ pointerEvents: "box-none",
3787
+ style: styles.debugOverlay,
3788
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.Pressable, {
3789
+ accessibilityRole: "button",
3790
+ onPress: shareRenderedHtml,
3791
+ style: ({ pressed }) => [styles.debugButton, pressed ? styles.debugButtonPressed : null],
3792
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.Text, {
3793
+ style: styles.debugButtonText,
3794
+ children: debugOptions.shareRenderedHtmlLabel
3795
+ })
3796
+ })
3797
+ }) : null]
3798
+ });
3799
+ });
3800
+ OrihaPreview.displayName = "OrihaPreview";
3801
+ function shouldShowPreviewLoading(output, previewError) {
3802
+ return !output && !previewError;
3803
+ }
3804
+ //#endregion
3805
+ //#region src/settings/renderSettingsModel.ts
3806
+ const DEFAULT_ORIHA_RENDER_SETTINGS_DRAFT = {
3807
+ plan: "free",
3808
+ colorScheme: "light",
3809
+ syntaxTheme: "github-light",
3810
+ headingFont: "system-default",
3811
+ bodyFont: "system-default",
3812
+ bodyFontSizePx: 16,
3813
+ codeFont: "system-default",
3814
+ tableBorderStyle: "inner",
3815
+ mode: "styledHtml"
3816
+ };
3817
+ const EMPTY_INSTALLED_ORIHA_FONTS = [];
3818
+ function createOrihaRenderSettingsDraft(patch = {}) {
3819
+ return {
3820
+ ...DEFAULT_ORIHA_RENDER_SETTINGS_DRAFT,
3821
+ ...patch
3822
+ };
3823
+ }
3824
+ function createOrihaRenderSettingsInput({ draft, installedFonts = [], locale }) {
3825
+ const selectedHeadingInstalledFont = installedOrihaFontBySelection(installedFonts, draft.headingFont, "heading");
3826
+ const selectedBodyInstalledFont = installedOrihaFontBySelection(installedFonts, draft.bodyFont, "body");
3827
+ const selectedCodeInstalledFont = installedOrihaFontBySelection(installedFonts, draft.codeFont, "code");
3828
+ return {
3829
+ mode: draft.mode,
3830
+ locale,
3831
+ plan: draft.plan,
3832
+ renderingOptions: normalizeBridgeRenderingOptions({
3833
+ colorScheme: draft.colorScheme,
3834
+ appearanceStyle: draft.appearanceStyle,
3835
+ syntaxTheme: draft.syntaxTheme,
3836
+ customSyntaxTheme: draft.customSyntaxTheme,
3837
+ headingFont: selectedHeadingInstalledFont ? "custom" : bridgeOrihaFontSelection(draft.headingFont, "system-default"),
3838
+ customHeadingFont: selectedHeadingInstalledFont === null || selectedHeadingInstalledFont === void 0 ? void 0 : selectedHeadingInstalledFont.fontFamilySpec,
3839
+ bodyFont: selectedBodyInstalledFont ? "custom" : bridgeOrihaFontSelection(draft.bodyFont, "system-default"),
3840
+ customBodyFont: selectedBodyInstalledFont === null || selectedBodyInstalledFont === void 0 ? void 0 : selectedBodyInstalledFont.fontFamilySpec,
3841
+ bodyFontSizePx: draft.bodyFontSizePx,
3842
+ codeFont: selectedCodeInstalledFont ? "custom" : bridgeOrihaFontSelection(draft.codeFont, "system-default"),
3843
+ customCodeFont: selectedCodeInstalledFont === null || selectedCodeInstalledFont === void 0 ? void 0 : selectedCodeInstalledFont.fontFamilySpec,
3844
+ tableBorderStyle: draft.tableBorderStyle,
3845
+ roundedCorners: draft.roundedCorners,
3846
+ shadows: draft.shadows,
3847
+ fullTableData: draft.fullTableData,
3848
+ blockBorders: draft.blockBorders
3849
+ }),
3850
+ viewport: draft.viewport
3851
+ };
3852
+ }
3853
+ function createOrihaRenderSettingsControls({ controls, resolved, resolvingReason, unavailableReason }) {
3854
+ return {
3855
+ plan: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.plan, resolved, {
3856
+ resolvingReason,
3857
+ unavailableReason
3858
+ }),
3859
+ colorScheme: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.colorScheme, resolved, {
3860
+ resolvingReason,
3861
+ unavailableReason
3862
+ }),
3863
+ locale: { disabled: false },
3864
+ syntaxTheme: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.syntaxTheme, resolved, {
3865
+ resolvingReason,
3866
+ unavailableReason
3867
+ }),
3868
+ headingFont: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.headingFont, resolved, {
3869
+ resolvingReason,
3870
+ unavailableReason
3871
+ }),
3872
+ bodyFont: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.bodyFont, resolved, {
3873
+ resolvingReason,
3874
+ unavailableReason
3875
+ }),
3876
+ codeFont: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.codeFont, resolved, {
3877
+ resolvingReason,
3878
+ unavailableReason
3879
+ }),
3880
+ tableBorderStyle: orihaRenderSettingsControlState(controls === null || controls === void 0 ? void 0 : controls.tableBorderStyle, resolved, {
3881
+ resolvingReason,
3882
+ unavailableReason
3883
+ })
3884
+ };
3885
+ }
3886
+ function createOrihaRenderSettingsOptions({ availableOptions, installedFonts = [] }) {
3887
+ var _availableOptions$pla, _availableOptions$col, _availableOptions$loc, _availableOptions$syn, _availableOptions$hea, _availableOptions$bod, _availableOptions$cod, _availableOptions$tab;
3888
+ return {
3889
+ plan: typedOptions((_availableOptions$pla = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.plan) !== null && _availableOptions$pla !== void 0 ? _availableOptions$pla : []),
3890
+ colorScheme: typedOptions((_availableOptions$col = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.colorScheme) !== null && _availableOptions$col !== void 0 ? _availableOptions$col : []),
3891
+ locale: markdownLocaleOptions((_availableOptions$loc = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.locale) !== null && _availableOptions$loc !== void 0 ? _availableOptions$loc : []),
3892
+ syntaxTheme: typedOptions((_availableOptions$syn = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.syntaxTheme) !== null && _availableOptions$syn !== void 0 ? _availableOptions$syn : []),
3893
+ headingFont: orihaFontOptionsForKind(typedOptions((_availableOptions$hea = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.headingFont) !== null && _availableOptions$hea !== void 0 ? _availableOptions$hea : []), installedFonts, "heading"),
3894
+ bodyFont: orihaFontOptionsForKind(typedOptions((_availableOptions$bod = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.bodyFont) !== null && _availableOptions$bod !== void 0 ? _availableOptions$bod : []), installedFonts, "body"),
3895
+ codeFont: orihaFontOptionsForKind(typedOptions((_availableOptions$cod = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.codeFont) !== null && _availableOptions$cod !== void 0 ? _availableOptions$cod : []), installedFonts, "code"),
3896
+ tableBorderStyle: typedOptions((_availableOptions$tab = availableOptions === null || availableOptions === void 0 ? void 0 : availableOptions.tableBorderStyle) !== null && _availableOptions$tab !== void 0 ? _availableOptions$tab : [])
3897
+ };
3898
+ }
3899
+ function orihaFontOptionsForKind(bridgeOptions, installedFonts, kind) {
3900
+ return [...bridgeOptions.filter((option) => option.id !== "custom"), ...installedFonts.filter((font) => font.kinds.includes(kind)).map((font) => ({
3901
+ id: installedOrihaFontSelectionId(font.id),
3902
+ label: font.label,
3903
+ description: font.description
3904
+ }))];
3905
+ }
3906
+ function installedOrihaFontBySelection(fonts, selectedId, kind) {
3907
+ var _fonts$find;
3908
+ if (!selectedId.startsWith("installed:")) return null;
3909
+ const fontId = selectedId.slice(10);
3910
+ return (_fonts$find = fonts.find((font) => font.id === fontId && font.kinds.includes(kind))) !== null && _fonts$find !== void 0 ? _fonts$find : null;
3911
+ }
3912
+ function installedOrihaFontSelectionId(fontId) {
3913
+ return `installed:${fontId}`;
3914
+ }
3915
+ function bridgeOrihaFontSelection(selectedId, defaultValue) {
3916
+ return selectedId.startsWith("installed:") ? defaultValue : selectedId;
3917
+ }
3918
+ function orihaRenderSettingsControlState(control, resolved, options = {}) {
3919
+ if (!resolved) {
3920
+ var _options$resolvingRea;
3921
+ return {
3922
+ disabled: true,
3923
+ reason: (_options$resolvingRea = options.resolvingReason) !== null && _options$resolvingRea !== void 0 ? _options$resolvingRea : "Resolving settings..."
3924
+ };
3925
+ }
3926
+ if ((control === null || control === void 0 ? void 0 : control.enabled) === false) {
3927
+ var _ref, _control$reason;
3928
+ return {
3929
+ disabled: true,
3930
+ reason: (_ref = (_control$reason = control.reason) !== null && _control$reason !== void 0 ? _control$reason : options.unavailableReason) !== null && _ref !== void 0 ? _ref : "Unavailable for this plan."
3931
+ };
3932
+ }
3933
+ return { disabled: false };
3934
+ }
3935
+ function markdownLocaleOptions(options) {
3936
+ return typedOptions(options);
3937
+ }
3938
+ function typedOptions(options) {
3939
+ return options.map((option) => ({
3940
+ ...option,
3941
+ id: option.id
3942
+ }));
3943
+ }
3944
+ function formatRenderSettingsError(error) {
3945
+ return error instanceof Error ? error.message : String(error);
3946
+ }
3947
+ //#endregion
3948
+ //#region src/settings/orihaRenderSettings.ts
3949
+ function useOrihaRenderSettings({ locale, initialDraft, installedFonts, resolvingReason, unavailableReason } = {}) {
3950
+ var _resolvedSettings$eff, _effectiveInput$local, _effectiveInput$rende;
3951
+ const fontRegistry = useOrihaFonts();
3952
+ const activeInstalledFonts = installedFonts !== null && installedFonts !== void 0 ? installedFonts : fontRegistry.installedFonts.length > 0 ? fontRegistry.installedFonts : EMPTY_INSTALLED_ORIHA_FONTS;
3953
+ const activeLocale = locale !== null && locale !== void 0 ? locale : "en";
3954
+ const [draft, setDraft] = (0, react.useState)(() => createOrihaRenderSettingsDraft(initialDraft));
3955
+ const setDraftValue = (0, react.useCallback)((key, value) => {
3956
+ setDraft((current) => current[key] === value ? current : {
3957
+ ...current,
3958
+ [key]: value
3959
+ });
3960
+ }, []);
3961
+ const selectedInput = (0, react.useMemo)(() => createOrihaRenderSettingsInput({
3962
+ draft,
3963
+ installedFonts: activeInstalledFonts,
3964
+ locale: activeLocale
3965
+ }), [
3966
+ activeInstalledFonts,
3967
+ activeLocale,
3968
+ draft
3969
+ ]);
3970
+ const [resolverState, setResolverState] = (0, react.useState)({
3971
+ resolvedSettings: null,
3972
+ error: null,
3973
+ isResolving: true
3974
+ });
3975
+ (0, react.useEffect)(() => {
3976
+ let cancelled = false;
3977
+ setResolverState((current) => ({
3978
+ ...current,
3979
+ error: null,
3980
+ isResolving: true
3981
+ }));
3982
+ resolveRenderSettings(selectedInput).then((nextSettings) => {
3983
+ if (!cancelled) setResolverState({
3984
+ resolvedSettings: nextSettings,
3985
+ error: null,
3986
+ isResolving: false
3987
+ });
3988
+ }).catch((error) => {
3989
+ if (!cancelled) setResolverState((current) => ({
3990
+ ...current,
3991
+ error: formatRenderSettingsError(error),
3992
+ isResolving: false
3993
+ }));
3994
+ });
3995
+ return () => {
3996
+ cancelled = true;
3997
+ };
3998
+ }, [selectedInput]);
3999
+ const resolvedSettings = resolverState.resolvedSettings;
4000
+ const effectiveInput = (_resolvedSettings$eff = resolvedSettings === null || resolvedSettings === void 0 ? void 0 : resolvedSettings.effectiveInput) !== null && _resolvedSettings$eff !== void 0 ? _resolvedSettings$eff : selectedInput;
4001
+ const effectiveLocale = (_effectiveInput$local = effectiveInput.locale) !== null && _effectiveInput$local !== void 0 ? _effectiveInput$local : activeLocale;
4002
+ const effectiveTableBorderStyle = (_effectiveInput$rende = effectiveInput.renderingOptions.tableBorderStyle) !== null && _effectiveInput$rende !== void 0 ? _effectiveInput$rende : draft.tableBorderStyle;
4003
+ const previewInput = (0, react.useMemo)(() => ({
4004
+ locale: effectiveLocale,
4005
+ plan: effectiveInput.plan,
4006
+ renderingOptions: normalizeBridgeRenderingOptions(effectiveInput.renderingOptions),
4007
+ print: void 0,
4008
+ renderMode: effectiveInput.mode,
4009
+ watermark: void 0,
4010
+ sourceAttributes: false,
4011
+ tableOfContents: false,
4012
+ viewport: effectiveInput.viewport
4013
+ }), [effectiveInput, effectiveLocale]);
4014
+ const controls = (0, react.useMemo)(() => createOrihaRenderSettingsControls({
4015
+ controls: resolvedSettings === null || resolvedSettings === void 0 ? void 0 : resolvedSettings.controls,
4016
+ resolved: resolvedSettings !== null,
4017
+ resolvingReason,
4018
+ unavailableReason
4019
+ }), [
4020
+ resolvedSettings,
4021
+ resolvingReason,
4022
+ unavailableReason
4023
+ ]);
4024
+ const options = (0, react.useMemo)(() => createOrihaRenderSettingsOptions({
4025
+ availableOptions: resolvedSettings === null || resolvedSettings === void 0 ? void 0 : resolvedSettings.availableOptions,
4026
+ installedFonts: activeInstalledFonts
4027
+ }), [activeInstalledFonts, resolvedSettings]);
4028
+ return {
4029
+ draft,
4030
+ setDraft,
4031
+ setDraftValue,
4032
+ selectedInput,
4033
+ resolvedSettings,
4034
+ effectiveInput,
4035
+ effectiveLocale,
4036
+ effectiveTableBorderStyle,
4037
+ previewInput,
4038
+ availableOptions: options,
4039
+ options,
4040
+ controls,
4041
+ isResolving: resolverState.isResolving,
4042
+ error: resolverState.error
4043
+ };
4044
+ }
4045
+ //#endregion
4046
+ //#region src/bridge/version.ts
4047
+ async function nativeBridgeVersionInfo() {
4048
+ return ExpoOrihaModule_default.nativeBridgeVersionInfo();
4049
+ }
4050
+ //#endregion
4051
+ //#region src/usage-analytics/usageAnalytics.ts
4052
+ async function usageAnalyticsOutboxStartEnqueue(input, nowMs) {
4053
+ return parseBridgePayload(await ExpoOrihaModule_default.usageAnalyticsOutboxStartEnqueue(stringifyBridgePayload(input), nowMs));
4054
+ }
4055
+ async function usageAnalyticsOutboxStartDrain(input, nowMs) {
4056
+ return parseBridgePayload(await ExpoOrihaModule_default.usageAnalyticsOutboxStartDrain(stringifyBridgePayload(input), nowMs));
4057
+ }
4058
+ async function usageAnalyticsOutboxStartDeliveryStateChange(input) {
4059
+ return parseBridgePayload(await ExpoOrihaModule_default.usageAnalyticsOutboxStartDeliveryStateChange(stringifyBridgePayload(input)));
4060
+ }
4061
+ async function usageAnalyticsOutboxResume(input, nowMs) {
4062
+ return parseBridgePayload(await ExpoOrihaModule_default.usageAnalyticsOutboxResume(stringifyBridgePayload(input), nowMs));
4063
+ }
4064
+ //#endregion
4065
+ //#region src/usage-analytics/usageAnalyticsOutboxCore.ts
4066
+ var UsageAnalyticsOutboxCore = class {
4067
+ constructor(options) {
4068
+ var _options$nowMs, _options$isDeliveryEn;
4069
+ this.deliveryGeneration = 0;
4070
+ this.serialOperation = Promise.resolve();
4071
+ this.config = options.config;
4072
+ this.store = options.store;
4073
+ this.transport = options.transport;
4074
+ this.engine = options.engine;
4075
+ this.nowMs = (_options$nowMs = options.nowMs) !== null && _options$nowMs !== void 0 ? _options$nowMs : Date.now;
4076
+ this.logger = options.logger;
4077
+ this.deliveryEnabled = (_options$isDeliveryEn = options.isDeliveryEnabled) !== null && _options$isDeliveryEn !== void 0 ? _options$isDeliveryEn : false;
4078
+ }
4079
+ get isDeliveryEnabled() {
4080
+ return this.deliveryEnabled;
4081
+ }
4082
+ get generation() {
4083
+ return this.deliveryGeneration;
4084
+ }
4085
+ enqueue(renderPayload) {
4086
+ return this.enqueueOperation(async () => {
4087
+ var _this$logger, _this$logger$debug;
4088
+ if (!this.deliveryEnabled) return;
4089
+ const generation = this.deliveryGeneration;
4090
+ (_this$logger = this.logger) === null || _this$logger === void 0 || (_this$logger$debug = _this$logger.debug) === null || _this$logger$debug === void 0 || _this$logger$debug.call(_this$logger, "Usage analytics outbox enqueue", `generation=${generation}`);
4091
+ const step = await this.engine.startEnqueue({
4092
+ config: this.config,
4093
+ renderPayload,
4094
+ isDeliveryEnabled: true,
4095
+ deliveryGeneration: generation
4096
+ }, this.nowMs());
4097
+ await this.runStep(step, generation);
4098
+ });
4099
+ }
4100
+ drain() {
4101
+ return this.enqueueOperation(async () => {
4102
+ const generation = this.deliveryGeneration;
4103
+ await this.startDrain(generation);
4104
+ });
4105
+ }
4106
+ setDeliveryEnabled(isEnabled) {
4107
+ var _this$logger2, _this$logger2$debug;
4108
+ if (this.deliveryEnabled === isEnabled) return this.serialOperation;
4109
+ this.deliveryEnabled = isEnabled;
4110
+ this.deliveryGeneration += 1;
4111
+ this.cancelScheduledDrain();
4112
+ const generation = this.deliveryGeneration;
4113
+ (_this$logger2 = this.logger) === null || _this$logger2 === void 0 || (_this$logger2$debug = _this$logger2.debug) === null || _this$logger2$debug === void 0 || _this$logger2$debug.call(_this$logger2, "Usage analytics outbox delivery state changed", `enabled=${isEnabled}`, `generation=${generation}`);
4114
+ return this.enqueueOperation(async () => {
4115
+ const step = await this.engine.startDeliveryStateChange({
4116
+ isDeliveryEnabled: isEnabled,
4117
+ deliveryGeneration: generation
4118
+ });
4119
+ await this.runStep(step, generation, { allowDisabled: !isEnabled });
4120
+ if (isEnabled) await this.startDrain(generation);
4121
+ });
4122
+ }
4123
+ purge() {
4124
+ this.deliveryEnabled = false;
4125
+ this.deliveryGeneration += 1;
4126
+ this.cancelScheduledDrain();
4127
+ const generation = this.deliveryGeneration;
4128
+ return this.enqueueOperation(async () => {
4129
+ const step = await this.engine.startDeliveryStateChange({
4130
+ isDeliveryEnabled: false,
4131
+ deliveryGeneration: generation
4132
+ });
4133
+ await this.runStep(step, generation, { allowDisabled: true });
4134
+ });
4135
+ }
4136
+ pendingCount() {
4137
+ var _this$store$pendingCo, _this$store$pendingCo2, _this$store;
4138
+ return (_this$store$pendingCo = (_this$store$pendingCo2 = (_this$store = this.store).pendingCount) === null || _this$store$pendingCo2 === void 0 ? void 0 : _this$store$pendingCo2.call(_this$store)) !== null && _this$store$pendingCo !== void 0 ? _this$store$pendingCo : Promise.resolve(0);
4139
+ }
4140
+ async runStep(initialStep, generation, options) {
4141
+ let step = initialStep;
4142
+ while (!step.isComplete) {
4143
+ if (!step.stepToken || step.commands.length === 0) return;
4144
+ if (!this.canContinue(generation, options)) return;
4145
+ const results = await executeUsageAnalyticsOutboxCommands(step.commands, {
4146
+ store: this.store,
4147
+ transport: this.transport,
4148
+ logger: this.logger
4149
+ });
4150
+ if (!this.canContinue(generation, options)) return;
4151
+ step = await this.engine.resume({
4152
+ stepToken: step.stepToken,
4153
+ results,
4154
+ isDeliveryEnabled: this.deliveryEnabled,
4155
+ deliveryGeneration: this.deliveryGeneration
4156
+ }, this.nowMs());
4157
+ }
4158
+ if (this.canContinue(generation, options)) this.scheduleDrain(step.nextDrainDelayMs, generation);
4159
+ }
4160
+ async startDrain(generation) {
4161
+ if (!this.canContinue(generation)) return;
4162
+ const step = await this.engine.startDrain({
4163
+ config: this.config,
4164
+ isDeliveryEnabled: true,
4165
+ deliveryGeneration: generation
4166
+ }, this.nowMs());
4167
+ await this.runStep(step, generation);
4168
+ }
4169
+ canContinue(generation, options) {
4170
+ return generation === this.deliveryGeneration && ((options === null || options === void 0 ? void 0 : options.allowDisabled) === true || this.deliveryEnabled);
4171
+ }
4172
+ scheduleDrain(delayMs, generation) {
4173
+ if (delayMs === void 0 || delayMs === null || !this.deliveryEnabled) return;
4174
+ this.cancelScheduledDrain();
4175
+ this.scheduledDrain = setTimeout(() => {
4176
+ this.scheduledDrain = void 0;
4177
+ if (generation === this.deliveryGeneration && this.deliveryEnabled) this.drain();
4178
+ }, Math.max(0, delayMs));
4179
+ }
4180
+ cancelScheduledDrain() {
4181
+ if (this.scheduledDrain !== void 0) {
4182
+ clearTimeout(this.scheduledDrain);
4183
+ this.scheduledDrain = void 0;
4184
+ }
4185
+ }
4186
+ enqueueOperation(operation) {
4187
+ const next = this.serialOperation.then(operation, operation);
4188
+ this.serialOperation = next.catch((error) => {
4189
+ var _this$logger3, _this$logger3$warn;
4190
+ (_this$logger3 = this.logger) === null || _this$logger3 === void 0 || (_this$logger3$warn = _this$logger3.warn) === null || _this$logger3$warn === void 0 || _this$logger3$warn.call(_this$logger3, "Usage analytics outbox operation failed", error);
4191
+ });
4192
+ return next;
4193
+ }
4194
+ };
4195
+ async function executeUsageAnalyticsOutboxCommands(commands, dependencies) {
4196
+ const results = [];
4197
+ for (const command of commands) results.push(await executeUsageAnalyticsOutboxCommand(command, dependencies));
4198
+ return results;
4199
+ }
4200
+ async function executeUsageAnalyticsOutboxCommand(command, dependencies) {
4201
+ try {
4202
+ switch (command.kind) {
4203
+ case "loadEnvelopes": return commandResult(command, { storedEnvelopes: await dependencies.store.loadEnvelopes() });
4204
+ case "writeEnvelope":
4205
+ var _dependencies$logger, _dependencies$logger$;
4206
+ if (!command.envelopeId || !command.envelopeJson) return commandResult(command, { succeeded: false });
4207
+ await dependencies.store.writeEnvelope({
4208
+ id: command.envelopeId,
4209
+ envelopeJson: command.envelopeJson
4210
+ });
4211
+ (_dependencies$logger = dependencies.logger) === null || _dependencies$logger === void 0 || (_dependencies$logger$ = _dependencies$logger.debug) === null || _dependencies$logger$ === void 0 || _dependencies$logger$.call(_dependencies$logger, "Usage analytics outbox enqueue", `envelopeId=${command.envelopeId}`);
4212
+ return commandResult(command);
4213
+ case "deleteEnvelope":
4214
+ if (!command.envelopeId) return commandResult(command, { succeeded: false });
4215
+ await dependencies.store.deleteEnvelope(command.envelopeId);
4216
+ return commandResult(command);
4217
+ case "purgeEnvelopes":
4218
+ var _dependencies$logger2, _dependencies$logger3;
4219
+ await dependencies.store.purgeEnvelopes();
4220
+ (_dependencies$logger2 = dependencies.logger) === null || _dependencies$logger2 === void 0 || (_dependencies$logger3 = _dependencies$logger2.debug) === null || _dependencies$logger3 === void 0 || _dependencies$logger3.call(_dependencies$logger2, "Usage analytics outbox purged");
4221
+ return commandResult(command);
4222
+ case "sendHttp": return sendHttp(command, dependencies.transport, dependencies.logger);
4223
+ default: return commandResult(command, { succeeded: false });
4224
+ }
4225
+ } catch (error) {
4226
+ var _dependencies$logger4, _dependencies$logger5;
4227
+ (_dependencies$logger4 = dependencies.logger) === null || _dependencies$logger4 === void 0 || (_dependencies$logger5 = _dependencies$logger4.debug) === null || _dependencies$logger5 === void 0 || _dependencies$logger5.call(_dependencies$logger4, "Usage analytics outbox command failed", error);
4228
+ return commandResult(command, { succeeded: false });
4229
+ }
4230
+ }
4231
+ async function sendHttp(command, transport, logger) {
4232
+ var _logger$debug;
4233
+ const context = command.httpContext;
4234
+ if (!context) return commandResult(command, { succeeded: false });
4235
+ logger === null || logger === void 0 || (_logger$debug = logger.debug) === null || _logger$debug === void 0 || _logger$debug.call(logger, "Usage analytics outbox send", `requestId=${command.id}`);
4236
+ return commandResult(command, { statusCode: (await transport.send(context)).statusCode });
4237
+ }
4238
+ function commandResult(command, options) {
4239
+ var _options$succeeded, _options$storedEnvelo;
4240
+ return {
4241
+ commandId: command.id,
4242
+ succeeded: (_options$succeeded = options === null || options === void 0 ? void 0 : options.succeeded) !== null && _options$succeeded !== void 0 ? _options$succeeded : true,
4243
+ storedEnvelopes: (_options$storedEnvelo = options === null || options === void 0 ? void 0 : options.storedEnvelopes) !== null && _options$storedEnvelo !== void 0 ? _options$storedEnvelo : [],
4244
+ statusCode: options === null || options === void 0 ? void 0 : options.statusCode
4245
+ };
4246
+ }
4247
+ //#endregion
4248
+ //#region src/usage-analytics/usageAnalyticsOutboxStore.ts
4249
+ const DEFAULT_STORAGE_NAMESPACE = "default";
4250
+ const OUTBOX_DIR = "usage-analytics-outbox";
4251
+ const ENVELOPE_FILE_EXTENSION = ".json";
4252
+ function createExpoUsageAnalyticsOutboxStore(config) {
4253
+ var _config$rootDirectory, _config$storageNamesp;
4254
+ const rootDirectory = (_config$rootDirectory = config === null || config === void 0 ? void 0 : config.rootDirectory) !== null && _config$rootDirectory !== void 0 ? _config$rootDirectory : expo_file_system_legacy.documentDirectory;
4255
+ if (!rootDirectory) throw new Error("Expo FileSystem documentDirectory is not available");
4256
+ return new ExpoUsageAnalyticsOutboxStore(`${ensureTrailingSlash(rootDirectory)}${VENDOR_STORAGE_DIR}/${sanitizeStorageNamespace((_config$storageNamesp = config === null || config === void 0 ? void 0 : config.storageNamespace) !== null && _config$storageNamesp !== void 0 ? _config$storageNamesp : DEFAULT_STORAGE_NAMESPACE)}/${OUTBOX_DIR}/`);
4257
+ }
4258
+ var ExpoUsageAnalyticsOutboxStore = class {
4259
+ constructor(directoryUri) {
4260
+ this.directoryUri = directoryUri;
4261
+ }
4262
+ async loadEnvelopes() {
4263
+ await this.ensureDirectory();
4264
+ const fileNames = await expo_file_system_legacy.readDirectoryAsync(this.directoryUri);
4265
+ return (await Promise.all(fileNames.map((fileName) => envelopeIdFromFileName(fileName)).filter((id) => id !== null).map(async (id) => {
4266
+ try {
4267
+ return {
4268
+ id,
4269
+ envelopeJson: await expo_file_system_legacy.readAsStringAsync(this.envelopeUri(id))
4270
+ };
4271
+ } catch {
4272
+ return null;
4273
+ }
4274
+ }))).filter((envelope) => envelope !== null);
4275
+ }
4276
+ async writeEnvelope(envelope) {
4277
+ await this.ensureDirectory();
4278
+ const finalUri = this.envelopeUri(envelope.id);
4279
+ const temporaryUri = this.temporaryEnvelopeUri(envelope.id);
4280
+ try {
4281
+ await expo_file_system_legacy.writeAsStringAsync(temporaryUri, envelope.envelopeJson);
4282
+ await expo_file_system_legacy.deleteAsync(finalUri, { idempotent: true });
4283
+ await expo_file_system_legacy.moveAsync({
4284
+ from: temporaryUri,
4285
+ to: finalUri
4286
+ });
4287
+ } catch (error) {
4288
+ await deleteIfExists(temporaryUri);
4289
+ throw error;
4290
+ }
4291
+ }
4292
+ async deleteEnvelope(id) {
4293
+ await expo_file_system_legacy.deleteAsync(this.envelopeUri(id), { idempotent: true });
4294
+ }
4295
+ async purgeEnvelopes() {
4296
+ await expo_file_system_legacy.deleteAsync(this.directoryUri, { idempotent: true });
4297
+ }
4298
+ async pendingCount() {
4299
+ await this.ensureDirectory();
4300
+ return (await expo_file_system_legacy.readDirectoryAsync(this.directoryUri)).filter((fileName) => envelopeIdFromFileName(fileName) !== null).length;
4301
+ }
4302
+ envelopeUri(id) {
4303
+ return `${this.directoryUri}${encodeURIComponent(id)}${ENVELOPE_FILE_EXTENSION}`;
4304
+ }
4305
+ temporaryEnvelopeUri(id) {
4306
+ return `${this.directoryUri}${encodeURIComponent(id)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
4307
+ }
4308
+ async ensureDirectory() {
4309
+ await expo_file_system_legacy.makeDirectoryAsync(this.directoryUri, { intermediates: true });
4310
+ }
4311
+ };
4312
+ function envelopeIdFromFileName(fileName) {
4313
+ if (!fileName.endsWith(ENVELOPE_FILE_EXTENSION)) return null;
4314
+ try {
4315
+ const id = decodeURIComponent(fileName.slice(0, -5));
4316
+ return id.length > 0 ? id : null;
4317
+ } catch {
4318
+ return null;
4319
+ }
4320
+ }
4321
+ function sanitizeStorageNamespace(value) {
4322
+ const namespace = value.trim() || DEFAULT_STORAGE_NAMESPACE;
4323
+ return encodeURIComponent(namespace);
4324
+ }
4325
+ function ensureTrailingSlash(value) {
4326
+ return value.endsWith("/") ? value : `${value}/`;
4327
+ }
4328
+ async function deleteIfExists(uri) {
4329
+ try {
4330
+ await expo_file_system_legacy.deleteAsync(uri, { idempotent: true });
4331
+ } catch {}
4332
+ }
4333
+ //#endregion
4334
+ //#region src/usage-analytics/usageAnalyticsOutboxTransport.ts
4335
+ function createFetchUsageAnalyticsTransport(options) {
4336
+ var _options$fetch;
4337
+ const fetchImplementation = (_options$fetch = options === null || options === void 0 ? void 0 : options.fetch) !== null && _options$fetch !== void 0 ? _options$fetch : globalThis.fetch;
4338
+ return { async send(context) {
4339
+ if (!fetchImplementation) return {};
4340
+ let timeoutId;
4341
+ const controller = context.timeoutMs > 0 && typeof AbortController !== "undefined" ? new AbortController() : void 0;
4342
+ if (controller) timeoutId = setTimeout(() => controller.abort(), context.timeoutMs);
4343
+ try {
4344
+ return { statusCode: (await fetchImplementation(context.url, {
4345
+ method: context.method,
4346
+ headers: headersFromContext(context),
4347
+ body: context.body,
4348
+ signal: controller === null || controller === void 0 ? void 0 : controller.signal
4349
+ })).status };
4350
+ } catch {
4351
+ return {};
4352
+ } finally {
4353
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
4354
+ }
4355
+ } };
4356
+ }
4357
+ function headersFromContext(context) {
4358
+ return Object.fromEntries(context.headers.map((header) => [header.name, header.value]));
4359
+ }
4360
+ //#endregion
4361
+ //#region src/usage-analytics/usageAnalyticsOutbox.ts
4362
+ const nativeUsageAnalyticsOutboxEngine = {
4363
+ startEnqueue: usageAnalyticsOutboxStartEnqueue,
4364
+ startDrain: usageAnalyticsOutboxStartDrain,
4365
+ startDeliveryStateChange: usageAnalyticsOutboxStartDeliveryStateChange,
4366
+ resume: usageAnalyticsOutboxResume
4367
+ };
4368
+ function createUsageAnalyticsOutbox(config, options) {
4369
+ return new UsageAnalyticsOutbox(config, options);
4370
+ }
4371
+ var UsageAnalyticsOutbox = class extends UsageAnalyticsOutboxCore {
4372
+ constructor(config, options) {
4373
+ var _options$store, _options$transport, _options$engine;
4374
+ super({
4375
+ config,
4376
+ store: (_options$store = options === null || options === void 0 ? void 0 : options.store) !== null && _options$store !== void 0 ? _options$store : createExpoUsageAnalyticsOutboxStore({
4377
+ rootDirectory: options === null || options === void 0 ? void 0 : options.rootDirectory,
4378
+ storageNamespace: options === null || options === void 0 ? void 0 : options.storageNamespace
4379
+ }),
4380
+ transport: (_options$transport = options === null || options === void 0 ? void 0 : options.transport) !== null && _options$transport !== void 0 ? _options$transport : createFetchUsageAnalyticsTransport(),
4381
+ engine: (_options$engine = options === null || options === void 0 ? void 0 : options.engine) !== null && _options$engine !== void 0 ? _options$engine : nativeUsageAnalyticsOutboxEngine,
4382
+ isDeliveryEnabled: options === null || options === void 0 ? void 0 : options.isDeliveryEnabled,
4383
+ nowMs: options === null || options === void 0 ? void 0 : options.nowMs,
4384
+ logger: options === null || options === void 0 ? void 0 : options.logger
4385
+ });
4386
+ }
4387
+ };
4388
+ //#endregion
4389
+ //#region src/usage-analytics/usageAnalyticsReporter.ts
4390
+ function createUsageAnalyticsReporter(outboxConfig, context, options) {
4391
+ return new UsageAnalyticsReporter(outboxConfig, context, options);
4392
+ }
4393
+ var UsageAnalyticsReporter = class {
4394
+ constructor(outboxConfig, context, options) {
4395
+ var _options$outbox;
4396
+ this.context = context;
4397
+ this.outbox = (_options$outbox = options === null || options === void 0 ? void 0 : options.outbox) !== null && _options$outbox !== void 0 ? _options$outbox : createUsageAnalyticsOutbox(outboxConfig, options);
4398
+ }
4399
+ updateContext(context) {
4400
+ this.context = {
4401
+ ...this.context,
4402
+ ...context
4403
+ };
4404
+ }
4405
+ setDeliveryEnabled(isEnabled) {
4406
+ return this.outbox.setDeliveryEnabled(isEnabled);
4407
+ }
4408
+ drain() {
4409
+ return this.outbox.drain();
4410
+ }
4411
+ purge() {
4412
+ return this.outbox.purge();
4413
+ }
4414
+ async recordRenderComplete(input) {
4415
+ var _input$eventId;
4416
+ if (!this.outbox.isDeliveryEnabled) return;
4417
+ await this.outbox.enqueue({
4418
+ ...this.context,
4419
+ ...input.context,
4420
+ stats: input.stats,
4421
+ eventId: (_input$eventId = input.eventId) !== null && _input$eventId !== void 0 ? _input$eventId : makeUsageAnalyticsEventId()
4422
+ });
4423
+ }
4424
+ };
4425
+ function makeUsageAnalyticsEventId() {
4426
+ var _globalCrypto$getRand;
4427
+ const expoCrypto = expo_crypto;
4428
+ if (typeof expoCrypto.randomUUID === "function") return expoCrypto.randomUUID();
4429
+ const globalCrypto = globalThis.crypto;
4430
+ if (typeof (globalCrypto === null || globalCrypto === void 0 ? void 0 : globalCrypto.randomUUID) === "function") return globalCrypto.randomUUID();
4431
+ const bytes = typeof expoCrypto.getRandomBytes === "function" ? expoCrypto.getRandomBytes(16) : globalCrypto === null || globalCrypto === void 0 || (_globalCrypto$getRand = globalCrypto.getRandomValues) === null || _globalCrypto$getRand === void 0 ? void 0 : _globalCrypto$getRand.call(globalCrypto, new Uint8Array(16));
4432
+ if (!bytes) throw new Error("A UUID v4 random source is not available");
4433
+ bytes[6] = bytes[6] & 15 | 64;
4434
+ bytes[8] = bytes[8] & 63 | 128;
4435
+ return bytesToUuid(bytes);
4436
+ }
4437
+ function bytesToUuid(bytes) {
4438
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));
4439
+ return [
4440
+ hex.slice(0, 4).join(""),
4441
+ hex.slice(4, 6).join(""),
4442
+ hex.slice(6, 8).join(""),
4443
+ hex.slice(8, 10).join(""),
4444
+ hex.slice(10, 16).join("")
4445
+ ].join("-");
4446
+ }
4447
+ //#endregion
4448
+ exports.AppearanceStyle = AppearanceStyle;
4449
+ exports.BodyFont = BodyFont;
4450
+ exports.BridgeFeature = BridgeFeature;
4451
+ exports.CodeFont = CodeFont;
4452
+ exports.ColorScheme = ColorScheme;
4453
+ exports.DEFAULT_ORIHA_LOCALE = DEFAULT_ORIHA_LOCALE;
4454
+ exports.DEFAULT_ORIHA_RENDER_SETTINGS_DRAFT = DEFAULT_ORIHA_RENDER_SETTINGS_DRAFT;
4455
+ exports.HeadingFont = HeadingFont;
4456
+ exports.ORIHA_MESSAGE_KEYS = ORIHA_MESSAGE_KEYS;
4457
+ exports.OrihaOverlayPlacement = OrihaOverlayPlacement;
4458
+ exports.OrihaPdfOrientation = OrihaPdfOrientation;
4459
+ exports.OrihaPdfPaperSize = OrihaPdfPaperSize;
4460
+ exports.OrihaPreview = OrihaPreview;
4461
+ exports.OrihaProvider = OrihaProvider;
4462
+ exports.OrihaToastPosition = OrihaToastPosition;
4463
+ exports.OrihaToastVariant = OrihaToastVariant;
4464
+ exports.Plan = Plan;
4465
+ exports.RenderAssetKind = RenderAssetKind;
4466
+ exports.RenderDiagnosticEngine = RenderDiagnosticEngine;
4467
+ exports.RenderDiagnosticSeverity = RenderDiagnosticSeverity;
4468
+ exports.RenderMode = RenderMode;
4469
+ exports.RenderPatchFallbackReason = RenderPatchFallbackReason;
4470
+ exports.RenderPatchStrategy = RenderPatchStrategy;
4471
+ exports.SyntaxTheme = SyntaxTheme;
4472
+ exports.TableBorderStyle = TableBorderStyle;
4473
+ exports.UsageAnalyticsOutbox = UsageAnalyticsOutbox;
4474
+ exports.UsageAnalyticsOutboxCommandKind = UsageAnalyticsOutboxCommandKind;
4475
+ exports.UsageAnalyticsReporter = UsageAnalyticsReporter;
4476
+ exports.bridgeOrihaFontSelection = bridgeOrihaFontSelection;
4477
+ exports.createExpoUsageAnalyticsOutboxStore = createExpoUsageAnalyticsOutboxStore;
4478
+ exports.createFetchUsageAnalyticsTransport = createFetchUsageAnalyticsTransport;
4479
+ exports.createOrihaI18n = createOrihaI18n;
4480
+ exports.createOrihaRenderSettingsControls = createOrihaRenderSettingsControls;
4481
+ exports.createOrihaRenderSettingsDraft = createOrihaRenderSettingsDraft;
4482
+ exports.createOrihaRenderSettingsInput = createOrihaRenderSettingsInput;
4483
+ exports.createOrihaRenderSettingsOptions = createOrihaRenderSettingsOptions;
4484
+ exports.createUsageAnalyticsOutbox = createUsageAnalyticsOutbox;
4485
+ exports.createUsageAnalyticsReporter = createUsageAnalyticsReporter;
4486
+ exports.defaultOrihaFormatMessage = defaultOrihaFormatMessage;
4487
+ exports.executeUsageAnalyticsOutboxCommands = executeUsageAnalyticsOutboxCommands;
4488
+ exports.exportHtml = exportHtml;
4489
+ exports.formatOrihaMessage = formatOrihaMessage;
4490
+ Object.defineProperty(exports, "generatedBridgeTypes", {
4491
+ enumerable: true,
4492
+ get: function() {
4493
+ return generatedBridgeTypes_exports;
4494
+ }
4495
+ });
4496
+ exports.installedOrihaFontBySelection = installedOrihaFontBySelection;
4497
+ exports.installedOrihaFontSelectionId = installedOrihaFontSelectionId;
4498
+ exports.makeUsageAnalyticsEventId = makeUsageAnalyticsEventId;
4499
+ exports.nativeBridgeVersionInfo = nativeBridgeVersionInfo;
4500
+ exports.nativeUsageAnalyticsOutboxEngine = nativeUsageAnalyticsOutboxEngine;
4501
+ exports.orihaFontOptionsForKind = orihaFontOptionsForKind;
4502
+ exports.orihaRenderSettingsControlState = orihaRenderSettingsControlState;
4503
+ exports.prepareHtmlExport = prepareHtmlExport;
4504
+ exports.prepareMarkdownLayout = prepareMarkdownLayout;
4505
+ exports.prepareMarkdownPatch = prepareMarkdownPatch;
4506
+ exports.renderPreparedHtmlExport = renderPreparedHtmlExport;
4507
+ exports.renderPreparedMarkdown = renderPreparedMarkdown;
4508
+ exports.renderPreparedMarkdownPatch = renderPreparedMarkdownPatch;
4509
+ exports.resolveRenderSettings = resolveRenderSettings;
4510
+ exports.usageAnalyticsOutboxResume = usageAnalyticsOutboxResume;
4511
+ exports.usageAnalyticsOutboxStartDeliveryStateChange = usageAnalyticsOutboxStartDeliveryStateChange;
4512
+ exports.usageAnalyticsOutboxStartDrain = usageAnalyticsOutboxStartDrain;
4513
+ exports.usageAnalyticsOutboxStartEnqueue = usageAnalyticsOutboxStartEnqueue;
4514
+ exports.useOrihaFonts = useOrihaFonts;
4515
+ exports.useOrihaI18n = useOrihaI18n;
4516
+ exports.useOrihaOverlay = useOrihaOverlay;
4517
+ exports.useOrihaRenderSettings = useOrihaRenderSettings;