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