@smartcat/sanity-plugin 1.0.0 → 1.1.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 (121) hide show
  1. package/README.md +294 -0
  2. package/dist/_chunks-cjs/constants.cjs +13 -0
  3. package/dist/_chunks-cjs/constants.cjs.map +1 -0
  4. package/dist/_chunks-cjs/index.cjs +174 -0
  5. package/dist/_chunks-cjs/index.cjs.map +1 -0
  6. package/dist/_chunks-cjs/index2.cjs +338 -0
  7. package/dist/_chunks-cjs/index2.cjs.map +1 -0
  8. package/dist/_chunks-cjs/workflow.cjs +16 -0
  9. package/dist/_chunks-cjs/workflow.cjs.map +1 -0
  10. package/dist/_chunks-es/constants.js +14 -0
  11. package/dist/_chunks-es/constants.js.map +1 -0
  12. package/dist/_chunks-es/index.js +175 -0
  13. package/dist/_chunks-es/index.js.map +1 -0
  14. package/dist/_chunks-es/index2.js +340 -0
  15. package/dist/_chunks-es/index2.js.map +1 -0
  16. package/dist/_chunks-es/workflow.js +17 -0
  17. package/dist/_chunks-es/workflow.js.map +1 -0
  18. package/dist/export.cjs +160 -0
  19. package/dist/export.cjs.map +1 -0
  20. package/dist/export.d.cts +162 -0
  21. package/dist/export.d.ts +162 -0
  22. package/dist/export.js +162 -0
  23. package/dist/export.js.map +1 -0
  24. package/dist/import.cjs +169 -0
  25. package/dist/import.cjs.map +1 -0
  26. package/dist/import.d.cts +155 -0
  27. package/dist/import.d.ts +155 -0
  28. package/dist/import.js +169 -0
  29. package/dist/import.js.map +1 -0
  30. package/dist/index.cjs +2172 -0
  31. package/dist/index.cjs.map +1 -0
  32. package/dist/index.d.cts +122 -0
  33. package/dist/index.d.ts +122 -0
  34. package/dist/index.js +2179 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/locjson.cjs +12 -0
  37. package/dist/locjson.cjs.map +1 -0
  38. package/dist/locjson.d.cts +291 -0
  39. package/dist/locjson.d.ts +291 -0
  40. package/dist/locjson.js +12 -0
  41. package/dist/locjson.js.map +1 -0
  42. package/dist/progress.cjs +16 -0
  43. package/dist/progress.cjs.map +1 -0
  44. package/dist/progress.d.cts +277 -0
  45. package/dist/progress.d.ts +277 -0
  46. package/dist/progress.js +16 -0
  47. package/dist/progress.js.map +1 -0
  48. package/dist/smartcat.cjs +287 -0
  49. package/dist/smartcat.cjs.map +1 -0
  50. package/dist/smartcat.d.cts +234 -0
  51. package/dist/smartcat.d.ts +234 -0
  52. package/dist/smartcat.js +287 -0
  53. package/dist/smartcat.js.map +1 -0
  54. package/dist/templates.cjs +12 -0
  55. package/dist/templates.cjs.map +1 -0
  56. package/dist/templates.d.cts +52 -0
  57. package/dist/templates.d.ts +52 -0
  58. package/dist/templates.js +12 -0
  59. package/dist/templates.js.map +1 -0
  60. package/package.json +101 -15
  61. package/src/actions/AddToProjectAction.tsx +274 -0
  62. package/src/export/export.test.ts +537 -0
  63. package/src/export/index.ts +393 -0
  64. package/src/form/TranslationStatusInput.tsx +212 -0
  65. package/src/import/import.test.ts +346 -0
  66. package/src/import/index.ts +418 -0
  67. package/src/index.ts +63 -0
  68. package/src/lib/constants.ts +23 -0
  69. package/src/lib/documentTitle.test.ts +43 -0
  70. package/src/lib/documentTitle.ts +30 -0
  71. package/src/lib/languageMap.test.ts +56 -0
  72. package/src/lib/languageMap.ts +71 -0
  73. package/src/lib/linkedDocuments.test.ts +56 -0
  74. package/src/lib/linkedDocuments.ts +100 -0
  75. package/src/lib/locjson/deserialize.ts +60 -0
  76. package/src/lib/locjson/fields.ts +355 -0
  77. package/src/lib/locjson/filename.ts +34 -0
  78. package/src/lib/locjson/index.ts +10 -0
  79. package/src/lib/locjson/locjson.test.ts +615 -0
  80. package/src/lib/locjson/paths.test.ts +41 -0
  81. package/src/lib/locjson/paths.ts +73 -0
  82. package/src/lib/locjson/portableText.ts +157 -0
  83. package/src/lib/locjson/serialize.ts +124 -0
  84. package/src/lib/locjson/types.ts +106 -0
  85. package/src/lib/log.ts +33 -0
  86. package/src/lib/projectItems.ts +31 -0
  87. package/src/lib/resolveConfig.test.ts +62 -0
  88. package/src/lib/resolveConfig.ts +54 -0
  89. package/src/lib/workflow.test.ts +37 -0
  90. package/src/lib/workflow.ts +48 -0
  91. package/src/lib/zip.fixtures.ts +75 -0
  92. package/src/lib/zip.test.ts +110 -0
  93. package/src/lib/zip.ts +164 -0
  94. package/src/progress/core.ts +409 -0
  95. package/src/progress/index.ts +7 -0
  96. package/src/progress/progress.test.ts +290 -0
  97. package/src/schema/settings.ts +55 -0
  98. package/src/schema/translatableOptions.ts +25 -0
  99. package/src/schema/translationProject.ts +268 -0
  100. package/src/smartcat/client.test.ts +222 -0
  101. package/src/smartcat/client.ts +351 -0
  102. package/src/smartcat/index.ts +10 -0
  103. package/src/smartcat/types.ts +99 -0
  104. package/src/templates/core.ts +55 -0
  105. package/src/templates/index.ts +5 -0
  106. package/src/templates/templates.test.ts +50 -0
  107. package/src/tool/Dashboard.tsx +46 -0
  108. package/src/tool/ItemProgress.tsx +176 -0
  109. package/src/tool/LogPanel.tsx +207 -0
  110. package/src/tool/ProjectView.tsx +1004 -0
  111. package/src/tool/ProjectsView.tsx +208 -0
  112. package/src/tool/StatusBadge.tsx +33 -0
  113. package/src/tool/StudioInit.tsx +42 -0
  114. package/src/tool/WorkflowSelect.tsx +41 -0
  115. package/src/tool/data.ts +86 -0
  116. package/src/tool/index.ts +19 -0
  117. package/src/tool/processing.test.ts +698 -0
  118. package/src/tool/processing.ts +839 -0
  119. package/src/tool/useTemplates.ts +84 -0
  120. package/src/tool/useWorkflowSelection.ts +65 -0
  121. package/src/types.ts +77 -0
@@ -0,0 +1,175 @@
1
+ function buildLanguageMappings(languages, ids) {
2
+ const byId = new Map(languages.map((l) => [l.id, l.smartcatLanguage || l.id]));
3
+ return ids.map((id) => ({ sanityId: id, smartcatLanguage: byId.get(id) || id }));
4
+ }
5
+ function toSmartcatLanguage(mappings, sanityId) {
6
+ return mappings?.find((m) => m.sanityId === sanityId)?.smartcatLanguage ?? sanityId;
7
+ }
8
+ function toSanityLanguage(mappings, smartcatLanguage) {
9
+ return mappings?.find((m) => m.smartcatLanguage === smartcatLanguage)?.sanityId ?? smartcatLanguage;
10
+ }
11
+ function findDuplicateSmartcatLanguages(mappings) {
12
+ const byCode = /* @__PURE__ */ new Map();
13
+ for (const m of mappings) {
14
+ const ids = byCode.get(m.smartcatLanguage) ?? [];
15
+ ids.push(m.sanityId), byCode.set(m.smartcatLanguage, ids);
16
+ }
17
+ return [...byCode.entries()].filter(([, ids]) => ids.length > 1).map(([smartcatLanguage, sanityIds]) => ({ smartcatLanguage, sanityIds }));
18
+ }
19
+ const ITEM_ID = "coalesce(docId, _ref)", ITEM_ID_FROM_SUBQUERY = "coalesce(^.docId, ^._ref)", itemDocDeref = (projection = "") => `*[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection}`, itemDocDerefRespectingDraft = (projection = "") => `select(sourceIsPublished == true => *[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection}, coalesce(*[_id == "drafts." + ${ITEM_ID_FROM_SUBQUERY}][0]${projection}, *[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection}))`;
20
+ function keyify(value) {
21
+ return value.replace(/[^a-zA-Z0-9_-]/g, "-") || "x";
22
+ }
23
+ function targetKey(sourceDocId, language) {
24
+ return keyify(`${sourceDocId}__${language}`);
25
+ }
26
+ function clampPercent(value) {
27
+ return typeof value != "number" || Number.isNaN(value) ? 0 : Math.max(0, Math.min(100, Math.round(value)));
28
+ }
29
+ function stripDraft(id) {
30
+ return id.replace(/^drafts\./, "");
31
+ }
32
+ function titleCase(value) {
33
+ return value && value.charAt(0).toUpperCase() + value.slice(1);
34
+ }
35
+ function buildStageNameMap(scProject) {
36
+ const map = /* @__PURE__ */ new Map();
37
+ return (scProject.workflowStages ?? []).forEach((stage, i) => {
38
+ stage.id && map.set(stage.id, titleCase(stage.stageType || stage.stageName || `Stage ${i + 1}`));
39
+ }), map;
40
+ }
41
+ function stagesFromDocument(doc, stageNames) {
42
+ return (doc.workflowStages ?? []).map((stage, i) => ({
43
+ _key: stage.id || `s${i}`,
44
+ name: stage.id && stageNames.get(stage.id) || titleCase(stage.stageType || stage.stageName || `Stage ${i + 1}`),
45
+ percent: clampPercent(stage.progress)
46
+ }));
47
+ }
48
+ function isTargetComplete(stages) {
49
+ return stages.length > 0 && stages.every((s) => s.percent >= 100);
50
+ }
51
+ function hasConfirmedContent(stages) {
52
+ return stages.some((s) => s.percent > 0);
53
+ }
54
+ function targetPercent(stages) {
55
+ return stages.length === 0 ? 0 : Math.round(stages.reduce((sum, s) => sum + s.percent, 0) / stages.length);
56
+ }
57
+ function sourceIdPrefix(doc) {
58
+ return ((doc.name || doc.filename || doc.fullPath || "").split("/").pop() ?? "").replace(/\.locjson$/i, "").replace(/-draft$/, "").slice(-8);
59
+ }
60
+ function buildProgress(items, scProject, previous, now, mappings) {
61
+ const stageNames = buildStageNameMap(scProject), importedSet = /* @__PURE__ */ new Set(), titleByDoc = /* @__PURE__ */ new Map();
62
+ for (const doc of previous ?? []) {
63
+ doc.title && titleByDoc.set(doc.sourceDocId, doc.title);
64
+ for (const target of doc.targets)
65
+ target.imported && importedSet.add(`${doc.sourceDocId}__${target.language}`);
66
+ }
67
+ const itemByPrefix = /* @__PURE__ */ new Map();
68
+ for (const item of items) itemByPrefix.set(stripDraft(item._id).slice(0, 8), item);
69
+ const byDoc = /* @__PURE__ */ new Map();
70
+ for (const scDoc of scProject.documents ?? []) {
71
+ if (!scDoc.targetLanguage) continue;
72
+ const item = itemByPrefix.get(sourceIdPrefix(scDoc));
73
+ if (!item) continue;
74
+ const language = toSanityLanguage(mappings, scDoc.targetLanguage);
75
+ let docProgress = byDoc.get(item._id);
76
+ if (!docProgress) {
77
+ const title = item.title || titleByDoc.get(item._id);
78
+ docProgress = { _key: targetKey(item._id, "doc"), sourceDocId: item._id, title, targets: [] }, byDoc.set(item._id, docProgress);
79
+ }
80
+ const stages = stagesFromDocument(scDoc, stageNames);
81
+ docProgress.targets.push({
82
+ _key: targetKey(item._id, language),
83
+ language,
84
+ smartcatDocumentId: scDoc.id,
85
+ stages,
86
+ complete: isTargetComplete(stages),
87
+ imported: importedSet.has(`${item._id}__${language}`),
88
+ syncedAt: now
89
+ });
90
+ }
91
+ const result = [];
92
+ for (const item of items) {
93
+ const docProgress = byDoc.get(item._id);
94
+ docProgress && (docProgress.targets.sort((a, b) => a.language.localeCompare(b.language)), result.push(docProgress));
95
+ }
96
+ return result;
97
+ }
98
+ function summarizeCompletion(progress) {
99
+ let total = 0, complete = 0, imported = 0, anyProgress = !1;
100
+ for (const doc of progress)
101
+ for (const target of doc.targets)
102
+ total++, target.complete && complete++, target.imported && imported++, target.stages.some((s) => s.percent > 0) && (anyProgress = !0);
103
+ return {
104
+ total,
105
+ complete,
106
+ imported,
107
+ allDone: total > 0 && complete === total && imported === total,
108
+ anyProgress
109
+ };
110
+ }
111
+ const PROGRESS_QUERY = `*[_id == $id][0]{
112
+ _id,
113
+ status,
114
+ smartcatProjectId,
115
+ smartcatLanguages[]{sanityId, smartcatLanguage},
116
+ "items": items[]{ "_id": ${ITEM_ID}, "title": ${itemDocDerefRespectingDraft(".title")} },
117
+ progress[]{_key, sourceDocId, title, targets[]{_key, language, smartcatDocumentId, stages, complete, imported, syncedAt}}
118
+ }`;
119
+ function itemsFromProject(project) {
120
+ const result = [];
121
+ for (const item of project.items ?? []) {
122
+ const _id = item?._id ?? item?.doc?._id;
123
+ _id && result.push({ _id, title: item?.title ?? item?.doc?.title ?? void 0 });
124
+ }
125
+ return result;
126
+ }
127
+ async function runProgressSync(options) {
128
+ const { sanity, smartcat, projectId, now = () => (/* @__PURE__ */ new Date()).toISOString() } = options, project = await sanity.fetch(PROGRESS_QUERY, { id: projectId });
129
+ if (!project) throw new Error(`Translation project ${projectId} not found`);
130
+ if (!project.smartcatProjectId)
131
+ throw new Error("Project has no smartcatProjectId \u2014 export it first");
132
+ const timestamp = now(), log = [];
133
+ smartcat.setRequestLogger?.(({ method, path, status, body }) => {
134
+ status >= 200 && status < 300 || (log.push({
135
+ level: "error",
136
+ message: status ? `Error ${status} while performing ${method} ${path}` : `${method} ${path} did not complete`
137
+ }), body && log.push({ level: "error", indent: !0, message: body }));
138
+ });
139
+ try {
140
+ const scProject = await smartcat.getProject(project.smartcatProjectId), progress = buildProgress(
141
+ itemsFromProject(project),
142
+ scProject,
143
+ project.progress,
144
+ timestamp,
145
+ project.smartcatLanguages
146
+ ), summary = summarizeCompletion(progress), patch = { progress, progressSyncedAt: timestamp, lastError: null };
147
+ return project.status === "sent" && summary.anyProgress && (patch.status = "translating"), await sanity.patch(projectId).set(patch).commit(), { summary };
148
+ } catch (err) {
149
+ const message = err instanceof Error ? err.message : String(err);
150
+ return log.some((l) => l.level === "error") || log.push({ level: "error", message }), await sanity.patch(projectId).set({ lastError: message, functionLog: JSON.stringify(log), progressSyncedAt: timestamp }).commit().catch(() => {
151
+ }), { summary: summarizeCompletion(project.progress ?? []), error: message };
152
+ }
153
+ }
154
+ export {
155
+ ITEM_ID,
156
+ ITEM_ID_FROM_SUBQUERY,
157
+ buildLanguageMappings,
158
+ buildProgress,
159
+ buildStageNameMap,
160
+ findDuplicateSmartcatLanguages,
161
+ hasConfirmedContent,
162
+ isTargetComplete,
163
+ itemDocDeref,
164
+ itemDocDerefRespectingDraft,
165
+ itemsFromProject,
166
+ keyify,
167
+ runProgressSync,
168
+ sourceIdPrefix,
169
+ stagesFromDocument,
170
+ summarizeCompletion,
171
+ targetKey,
172
+ targetPercent,
173
+ toSmartcatLanguage
174
+ };
175
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/lib/languageMap.ts","../../src/lib/projectItems.ts","../../src/progress/core.ts"],"sourcesContent":["/**\n * Sanity ↔ Smartcat language-code mapping.\n *\n * Sanity locale tags (`id`) don't always match the codes Smartcat understands\n * (e.g. Sanity \"PL-PL\" vs Smartcat \"pl\"). The browser resolves the mapping from\n * plugin config and stamps the relevant pairs onto the project; the thin\n * Functions read them back. This module is dependency-free so it bundles into\n * both the Studio and the Functions.\n *\n * The invariant: everything stored in Sanity uses the Sanity `id`; only the\n * Smartcat HTTP calls use `smartcatLanguage`. So callers map forward (id → code)\n * when talking to Smartcat and invert (code → id) when storing what comes back.\n */\n\nexport interface SmartcatLanguageMapping {\n sanityId: string\n smartcatLanguage: string\n}\n\n/** Minimal language shape needed to build mappings (a subset of SmartcatLanguage). */\ninterface MappableLanguage {\n id: string\n smartcatLanguage?: string\n}\n\n/**\n * Builds the mapping pairs for the given Sanity ids, resolving each to its\n * configured `smartcatLanguage` (falling back to the id when not configured).\n */\nexport function buildLanguageMappings(\n languages: MappableLanguage[],\n ids: string[],\n): SmartcatLanguageMapping[] {\n const byId = new Map(languages.map((l) => [l.id, l.smartcatLanguage || l.id]))\n return ids.map((id) => ({sanityId: id, smartcatLanguage: byId.get(id) || id}))\n}\n\n/** Sanity id → Smartcat code. Identity when no mapping is found. */\nexport function toSmartcatLanguage(\n mappings: SmartcatLanguageMapping[] | undefined,\n sanityId: string,\n): string {\n return mappings?.find((m) => m.sanityId === sanityId)?.smartcatLanguage ?? sanityId\n}\n\n/** Smartcat code → Sanity id. Identity when no mapping is found. */\nexport function toSanityLanguage(\n mappings: SmartcatLanguageMapping[] | undefined,\n smartcatLanguage: string,\n): string {\n return mappings?.find((m) => m.smartcatLanguage === smartcatLanguage)?.sanityId ?? smartcatLanguage\n}\n\n/**\n * Finds Smartcat codes that more than one Sanity id maps to. A non-empty result\n * means the inverse (code → id) is ambiguous, so translations can't be routed\n * back — callers should reject such a configuration.\n */\nexport function findDuplicateSmartcatLanguages(\n mappings: SmartcatLanguageMapping[],\n): {smartcatLanguage: string; sanityIds: string[]}[] {\n const byCode = new Map<string, string[]>()\n for (const m of mappings) {\n const ids = byCode.get(m.smartcatLanguage) ?? []\n ids.push(m.sanityId)\n byCode.set(m.smartcatLanguage, ids)\n }\n return [...byCode.entries()]\n .filter(([, ids]) => ids.length > 1)\n .map(([smartcatLanguage, sanityIds]) => ({smartcatLanguage, sanityIds}))\n}\n","/**\n * GROQ fragments for reading a translation project's `items`.\n *\n * An item is either the current `smartcat.projectItem` shape (`{docId, docType}`)\n * or a legacy weak reference (`{_ref}`) from before the migration. These\n * fragments normalize across both so the old/new tolerance lives in one place —\n * interpolate them into item queries rather than re-writing `coalesce(...)`.\n */\n\n/** Normalized item id, evaluated in the item's own scope (inside `items[...]`). */\nexport const ITEM_ID = 'coalesce(docId, _ref)'\n\n/** Normalized item id, evaluated from a subquery nested under an item (via `^`). */\nexport const ITEM_ID_FROM_SUBQUERY = 'coalesce(^.docId, ^._ref)'\n\n/** Dereference an item's document, with an optional projection e.g. `{_id, _type}`. */\nexport const itemDocDeref = (projection = ''): string => `*[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection}`\n\n/**\n * Dereference an item's document, honoring where it was added from: items added\n * in the **published** perspective (`sourceIsPublished == true`) resolve the\n * published document only; every other item (including legacy items with no\n * flag) prefers the **draft**, falling back to published. This makes the export\n * translate the content the editor was actually viewing, and gives pre-existing\n * projects the draft-preferring default for free.\n */\nexport const itemDocDerefRespectingDraft = (projection = ''): string =>\n `select(` +\n `sourceIsPublished == true => *[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection}, ` +\n `coalesce(*[_id == \"drafts.\" + ${ITEM_ID_FROM_SUBQUERY}][0]${projection}, *[_id == ${ITEM_ID_FROM_SUBQUERY}][0]${projection})` +\n `)`\n","import type {SmartcatProject, SmartcatDocument, RequestLogger} from '../smartcat/types'\nimport {toSanityLanguage, type SmartcatLanguageMapping} from '../lib/languageMap'\nimport {ITEM_ID, itemDocDerefRespectingDraft} from '../lib/projectItems'\nimport type {LogLine} from '../lib/log'\n\n/**\n * Per-document, per-language, per-stage translation progress mirrored from\n * Smartcat onto a `smartcat.translationProject`.\n *\n * This module is intentionally **dependency-free** (no DOM, no @sanity/* runtime)\n * so it bundles cleanly into the thin `smartcat-progress` / `smartcat-import`\n * Functions. All keys are deterministic, so repeated refreshes patch the same\n * array members in place instead of churning `_key`s.\n */\n\nexport interface StageProgress {\n /** Stable key for the Sanity array item (always set by `stagesFromDocument`). */\n _key?: string\n name: string\n /** 0–100, rounded. */\n percent: number\n}\n\nexport interface TargetProgress {\n _key: string\n language: string\n /** Smartcat target document id (`<fileGuid>_<languageNumber>`). */\n smartcatDocumentId?: string\n stages: StageProgress[]\n /** All stages at 100%. */\n complete: boolean\n /** A locale variant has been built from this target (set by the browser). */\n imported: boolean\n syncedAt?: string\n}\n\nexport interface DocProgress {\n _key: string\n sourceDocId: string\n title?: string\n targets: TargetProgress[]\n}\n\n/** Sanitizes an arbitrary string into a stable, Sanity-safe array `_key`. */\nexport function keyify(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '-') || 'x'\n}\n\n/** Builds a progress target's `_key` from its document + language. */\nexport function targetKey(sourceDocId: string, language: string): string {\n return keyify(`${sourceDocId}__${language}`)\n}\n\nfunction clampPercent(value: number | undefined): number {\n if (typeof value !== 'number' || Number.isNaN(value)) return 0\n return Math.max(0, Math.min(100, Math.round(value)))\n}\n\n/** Strips a `drafts.` prefix from a Sanity document id. */\nfunction stripDraft(id: string): string {\n return id.replace(/^drafts\\./, '')\n}\n\nfunction titleCase(value: string): string {\n return value ? value.charAt(0).toUpperCase() + value.slice(1) : value\n}\n\n/**\n * Builds a stage-id → display-name map from a project's `workflowStages`. On\n * Smartcat, document-level stages carry only `{id, progress}` — the human name\n * (`stageType`, e.g. \"translation\") lives on the project-level stages.\n */\nexport function buildStageNameMap(scProject: SmartcatProject): Map<string, string> {\n const map = new Map<string, string>()\n ;(scProject.workflowStages ?? []).forEach((stage, i) => {\n if (stage.id) map.set(stage.id, titleCase(stage.stageType || stage.stageName || `Stage ${i + 1}`))\n })\n return map\n}\n\n/** Maps a Smartcat document's workflow stages to display-ready stage progress. */\nexport function stagesFromDocument(\n doc: SmartcatDocument,\n stageNames: Map<string, string>,\n): StageProgress[] {\n const stages = doc.workflowStages ?? []\n return stages.map((stage, i) => ({\n _key: stage.id || `s${i}`,\n name:\n (stage.id && stageNames.get(stage.id)) ||\n titleCase(stage.stageType || stage.stageName || `Stage ${i + 1}`),\n percent: clampPercent(stage.progress),\n }))\n}\n\n/** A target is complete when it has stages and every one is at 100%. */\nexport function isTargetComplete(stages: StageProgress[]): boolean {\n return stages.length > 0 && stages.every((s) => s.percent >= 100)\n}\n\n/**\n * Whether a target has any content confirmed at any stage — i.e. there is\n * something worth importing. Used to gate `mode=confirmed` downloads so we skip\n * targets with nothing confirmed yet (which would otherwise come back as source).\n */\nexport function hasConfirmedContent(stages: StageProgress[]): boolean {\n return stages.some((s) => s.percent > 0)\n}\n\n/** Average completion across a target's stages (0–100). */\nexport function targetPercent(stages: StageProgress[]): number {\n if (stages.length === 0) return 0\n return Math.round(stages.reduce((sum, s) => sum + s.percent, 0) / stages.length)\n}\n\n/** A project item we correlate Smartcat documents back to. */\nexport interface ProjectItem {\n _id: string\n title?: string\n}\n\n/**\n * Extracts the 8-char source-id prefix Smartcat preserves in a document's\n * filename (built as `<title>-<idPrefix>.locjson`, or `<title>-<idPrefix>-draft.locjson`\n * when the content came from the document's draft). Used to correlate a Smartcat\n * document back to a Sanity source document.\n *\n * A trailing `-draft` marker is stripped first, so a draft-sourced file resolves\n * to the same id as its published counterpart. The prefix is then always the\n * final 8 characters before the (marker and) extension, so take the tail rather\n * than splitting on a dash — the title or the id prefix itself can\n * contain dashes (e.g. a custom id like `demo-pdpA` → prefix `demo-pdp`), which\n * would make a last-dash split return the wrong fragment.\n *\n * Only a literal `.locjson` extension is stripped (Smartcat's API often returns\n * the name without it). A generic strip-after-last-dot would eat the tail of any\n * DOTTED title — e.g. micro-copy keys like `aiAssistantModal.resetChat-11AKrV8G`\n * — leaving the wrong 8 chars, so those documents silently never correlate,\n * never import, and re-syncs duplicate them instead of updating.\n */\nexport function sourceIdPrefix(doc: SmartcatDocument): string {\n const base = doc.name || doc.filename || doc.fullPath || ''\n const leaf = base.split('/').pop() ?? ''\n const noExt = leaf.replace(/\\.locjson$/i, '')\n // Draft-sourced files carry a trailing `-draft` marker (informational only, so\n // a project never holds both a document's draft and its published version).\n // Strip it before taking the tail so a draft file correlates to the same source\n // id as its published counterpart — the id prefix is what identifies the item.\n const noDraft = noExt.replace(/-draft$/, '')\n return noDraft.slice(-8)\n}\n\n/**\n * Builds the full progress array from a freshly fetched Smartcat project and the\n * project's items — independent of any export-time skeleton, so it works for\n * projects exported before progress tracking existed.\n *\n * Documents are correlated to items by the 8-char id prefix in their filename;\n * `imported` flags are carried over from the previous progress (by source doc +\n * language) so importing isn't forgotten on refresh.\n *\n * `mappings` invert Smartcat's returned target codes back to Sanity ids, so all\n * stored progress uses Sanity locale tags. When omitted, codes pass through\n * unchanged (identity) — keeping legacy projects working.\n */\nexport function buildProgress(\n items: ProjectItem[],\n scProject: SmartcatProject,\n previous: DocProgress[] | undefined,\n now: string,\n mappings?: SmartcatLanguageMapping[],\n): DocProgress[] {\n const stageNames = buildStageNameMap(scProject)\n\n const importedSet = new Set<string>()\n // Titles are computed Sanity-native in the Studio and shipped on the outbox, so\n // they may not be re-derivable server-side. Carry the previously-stored title\n // forward so a progress sync (which only has the raw `doc.title`) can't clobber\n // it with an \"Untitled\" for types that have no literal title field.\n const titleByDoc = new Map<string, string>()\n for (const doc of previous ?? []) {\n if (doc.title) titleByDoc.set(doc.sourceDocId, doc.title)\n for (const target of doc.targets) {\n if (target.imported) importedSet.add(`${doc.sourceDocId}__${target.language}`)\n }\n }\n\n const itemByPrefix = new Map<string, ProjectItem>()\n for (const item of items) itemByPrefix.set(stripDraft(item._id).slice(0, 8), item)\n\n const byDoc = new Map<string, DocProgress>()\n for (const scDoc of scProject.documents ?? []) {\n if (!scDoc.targetLanguage) continue\n const item = itemByPrefix.get(sourceIdPrefix(scDoc))\n if (!item) continue\n\n // Store the Sanity locale tag, not Smartcat's code.\n const language = toSanityLanguage(mappings, scDoc.targetLanguage)\n\n let docProgress = byDoc.get(item._id)\n if (!docProgress) {\n const title = item.title || titleByDoc.get(item._id)\n docProgress = {_key: targetKey(item._id, 'doc'), sourceDocId: item._id, title, targets: []}\n byDoc.set(item._id, docProgress)\n }\n const stages = stagesFromDocument(scDoc, stageNames)\n docProgress.targets.push({\n _key: targetKey(item._id, language),\n language,\n smartcatDocumentId: scDoc.id,\n stages,\n complete: isTargetComplete(stages),\n imported: importedSet.has(`${item._id}__${language}`),\n syncedAt: now,\n })\n }\n\n // Preserve item order; sort each doc's targets by language for stable display.\n const result: DocProgress[] = []\n for (const item of items) {\n const docProgress = byDoc.get(item._id)\n if (!docProgress) continue\n docProgress.targets.sort((a, b) => a.language.localeCompare(b.language))\n result.push(docProgress)\n }\n return result\n}\n\nexport interface CompletionSummary {\n /** Total (document × language) targets. */\n total: number\n /** Targets whose stages are all at 100%. */\n complete: number\n /** Targets a variant has been built for. */\n imported: number\n /** True when every target is complete and imported (and there is ≥1 target). */\n allDone: boolean\n /** True when at least one stage shows any progress. */\n anyProgress: boolean\n}\n\n/** Summarizes a progress array for status decisions and the dashboard. */\nexport function summarizeCompletion(progress: DocProgress[]): CompletionSummary {\n let total = 0\n let complete = 0\n let imported = 0\n let anyProgress = false\n for (const doc of progress) {\n for (const target of doc.targets) {\n total++\n if (target.complete) complete++\n if (target.imported) imported++\n if (target.stages.some((s) => s.percent > 0)) anyProgress = true\n }\n }\n return {\n total,\n complete,\n imported,\n allDone: total > 0 && complete === total && imported === total,\n anyProgress,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Function-side orchestration: refresh progress from Smartcat\n// ---------------------------------------------------------------------------\n\n/** Minimal structural subset of @sanity/client used by the progress refresh. */\nexport interface SanityLikeClient {\n fetch<T = unknown>(query: string, params?: Record<string, unknown>): Promise<T>\n patch(id: string): {\n set(attrs: Record<string, unknown>): {commit(): Promise<unknown>}\n }\n}\n\n/** Structural subset of SmartcatClient the progress refresh needs. */\nexport interface SmartcatProgressClient {\n getProject(projectId: string): Promise<SmartcatProject>\n /** Optional: trace every HTTP call so a timeout/error reaches the functionLog. */\n setRequestLogger?(logger: RequestLogger): void\n}\n\nexport interface RunProgressSyncOptions {\n sanity: SanityLikeClient\n smartcat: SmartcatProgressClient\n /** `_id` of the `smartcat.translationProject` to refresh. */\n projectId: string\n now?: () => string\n}\n\nexport interface RunProgressSyncResult {\n summary: CompletionSummary\n /** Set when the Smartcat fetch failed (e.g. timed out); the run was recorded, not thrown. */\n error?: string\n}\n\nconst PROGRESS_QUERY = `*[_id == $id][0]{\n _id,\n status,\n smartcatProjectId,\n smartcatLanguages[]{sanityId, smartcatLanguage},\n \"items\": items[]{ \"_id\": ${ITEM_ID}, \"title\": ${itemDocDerefRespectingDraft('.title')} },\n progress[]{_key, sourceDocId, title, targets[]{_key, language, smartcatDocumentId, stages, complete, imported, syncedAt}}\n}`\n\ninterface ProgressProjectData {\n _id: string\n status?: string\n smartcatProjectId?: string\n smartcatLanguages?: SmartcatLanguageMapping[]\n items?: ProjectItemRef[]\n progress?: DocProgress[]\n}\n\n/** A project item as read for correlation: its stored id (always present) plus a\n * best-effort title. `doc` is the legacy shape — some callers still project it. */\ninterface ProjectItemRef {\n _id?: string\n title?: string\n doc?: {_id?: string; title?: string} | null\n}\n\n/**\n * Resolves a project's items into the lightweight shape we correlate on. The id\n * is the item's stored `docId` — NOT a dereferenced document — so an item whose\n * document exists only as a draft (never published) still correlates instead of\n * being silently dropped. Tolerates the legacy `{doc}` projection.\n */\nexport function itemsFromProject(project: {items?: ProjectItemRef[]}): ProjectItem[] {\n const result: ProjectItem[] = []\n for (const item of project.items ?? []) {\n const _id = item?._id ?? item?.doc?._id\n if (!_id) continue\n result.push({_id, title: item?.title ?? item?.doc?.title ?? undefined})\n }\n return result\n}\n\n/**\n * Thin progress step run by the `smartcat-progress` Function: fetches the\n * Smartcat project and mirrors its per-stage progress onto the project's\n * `progress` array. Read-only with respect to Smartcat — it never downloads or\n * creates variants, so it is cheap to run on every dashboard page load.\n */\nexport async function runProgressSync(\n options: RunProgressSyncOptions,\n): Promise<RunProgressSyncResult> {\n const {sanity, smartcat, projectId, now = () => new Date().toISOString()} = options\n\n const project = await sanity.fetch<ProgressProjectData | null>(PROGRESS_QUERY, {id: projectId})\n if (!project) throw new Error(`Translation project ${projectId} not found`)\n if (!project.smartcatProjectId) {\n throw new Error('Project has no smartcatProjectId — export it first')\n }\n\n const timestamp = now()\n\n // Trace HTTP failures into a functionLog so a timeout/error surfaces in the UI.\n // Successful calls are left unlogged: this Function runs on every page load, and\n // functionLog is shared with export/import — writing it on every success would\n // wipe a useful export/import log.\n const log: LogLine[] = []\n smartcat.setRequestLogger?.(({method, path, status, body}) => {\n if (status >= 200 && status < 300) return\n log.push({\n level: 'error',\n message: status ? `Error ${status} while performing ${method} ${path}` : `${method} ${path} did not complete`,\n })\n if (body) log.push({level: 'error', indent: true, message: body})\n })\n\n try {\n const scProject = await smartcat.getProject(project.smartcatProjectId)\n const progress = buildProgress(\n itemsFromProject(project),\n scProject,\n project.progress,\n timestamp,\n project.smartcatLanguages,\n )\n const summary = summarizeCompletion(progress)\n\n const patch: Record<string, unknown> = {progress, progressSyncedAt: timestamp, lastError: null}\n // Gentle one-way nudge: once Smartcat reports any work, reflect it in the badge.\n // Completion remains owned by the import flow.\n if (project.status === 'sent' && summary.anyProgress) {\n patch.status = 'translating'\n }\n\n await sanity.patch(projectId).set(patch).commit()\n\n return {summary}\n } catch (err) {\n // Record the failure and return instead of throwing: a throw would let the\n // platform retry, and a timed-out fetch has nothing transient to gain. Leave\n // the existing `progress` untouched (no zeroing-out) and only stamp the error\n // plus a fresh `progressSyncedAt`, which releases the UI refresh spinner and\n // makes the log land where the dashboard reads it.\n const message = err instanceof Error ? err.message : String(err)\n if (!log.some((l) => l.level === 'error')) log.push({level: 'error', message})\n await sanity\n .patch(projectId)\n .set({lastError: message, functionLog: JSON.stringify(log), progressSyncedAt: timestamp})\n .commit()\n .catch(() => {})\n return {summary: summarizeCompletion(project.progress ?? []), error: message}\n }\n}\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OAAA,EACA,MAAM,MAAM;AAAA,IAAC,CAAC,GACV,EAAC,SAAS,oBAAoB,QAAQ,YAAY,CAAA,CAAE,GAAG,OAAO,QAAA;AAAA,EACvE;AACF;"}
@@ -0,0 +1,340 @@
1
+ import { toHTML, escapeHTML } from "@portabletext/to-html";
2
+ import { htmlToBlocks } from "@sanity/block-tools";
3
+ function isExcludedByDocumentI18n(field) {
4
+ return field.type?.options?.documentInternationalization?.exclude === !0;
5
+ }
6
+ function isSystemType(typeName) {
7
+ return typeof typeName == "string" && typeName.startsWith("sanity.");
8
+ }
9
+ function isInternationalizedArrayType(type) {
10
+ return type?.jsonType === "array" && typeof type.name == "string" && type.name.startsWith("internationalizedArray");
11
+ }
12
+ function isInternationalizedArrayMemberType(typeName) {
13
+ return typeof typeName == "string" && /^internationalizedArray.+Value$/.test(typeName);
14
+ }
15
+ function innerValueType(arrayType) {
16
+ return arrayType?.of?.[0]?.fields?.find((f) => f.name === "value")?.type;
17
+ }
18
+ function localizationMode(compiledType) {
19
+ const fields = compiledType?.fields;
20
+ return Array.isArray(fields) && fields.some((f) => isInternationalizedArrayType(f.type)) ? "field" : "document";
21
+ }
22
+ function getTranslatableFields(compiledType, options = {}) {
23
+ const rootType = compiledType;
24
+ if (isSystemType(rootType?.name)) return [];
25
+ if (!Array.isArray(rootType?.fields)) return [];
26
+ const result = [];
27
+ return walkFields(rootType, "", localizationMode(rootType), new Set(options.exclude ?? []), result), result;
28
+ }
29
+ function walkFields(compiledType, prefix, mode, exclude, out) {
30
+ for (const field of compiledType?.fields ?? []) {
31
+ if (!field?.name || field.name.startsWith("_") || prefix === "" && exclude.has(field.name)) continue;
32
+ const forceInclude = field.type?.options?.smartcatTranslation?.include === !0;
33
+ if (isExcludedByDocumentI18n(field) && !forceInclude) continue;
34
+ const path = prefix ? `${prefix}.${field.name}` : field.name, title = field.type?.title || titleCase(field.name);
35
+ if (mode === "field")
36
+ if (isInternationalizedArrayType(field.type)) {
37
+ const inner = innerValueType(field.type), shape = classifyValueShape(inner) ?? (forceInclude ? classifyValueShapeByJsonType(inner) : null);
38
+ shape ? out.push({ path, localization: "field", kind: shape.container === "scalar" ? shape.kind : "plain", title, value: shape }) : forceInclude && warnUntranslatableInclude(field.name, inner);
39
+ } else isPlainObject(field.type) && walkFields(field.type, path, mode, exclude, out);
40
+ else {
41
+ const kind = classifyField(field.type) ?? (forceInclude ? classifyByJsonType(field.type) : null);
42
+ kind ? out.push({ path, localization: "document", kind, title, value: { container: "scalar", kind } }) : forceInclude && warnUntranslatableInclude(field.name, field.type);
43
+ }
44
+ }
45
+ }
46
+ function enumerateLeaves(field, sourceValue) {
47
+ const base = field.path, shape = field.value ?? { container: "scalar", kind: field.kind };
48
+ if (shape.container === "scalar")
49
+ return [{ fullKey: base, valuePath: "", kind: shape.kind, title: field.title }];
50
+ if (shape.container === "arrayOfScalar")
51
+ return (Array.isArray(sourceValue) ? sourceValue : []).map((_, i) => ({ fullKey: `${base}[${i}]`, valuePath: `[${i}]`, kind: shape.kind, title: field.title }));
52
+ if (shape.container === "object")
53
+ return shape.leaves.map((l) => ({ fullKey: `${base}.${l.subPath}`, valuePath: l.subPath, kind: l.kind, title: l.title ?? field.title }));
54
+ const arr = Array.isArray(sourceValue) ? sourceValue : [], out = [];
55
+ for (const item of arr) {
56
+ const key = item?._key;
57
+ if (typeof key == "string")
58
+ for (const l of shape.leaves) {
59
+ const valuePath = l.subPath ? `[${key}].${l.subPath}` : `[${key}]`;
60
+ out.push({ fullKey: `${base}${valuePath}`, valuePath, kind: l.kind, title: l.title ?? field.title });
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ function isPlainObject(type) {
66
+ return type?.jsonType !== "object" || !Array.isArray(type.fields) || type.fields.some((f) => f.name === "_ref") ? !1 : !["reference", "image", "file", "slug", "geopoint"].includes(type.name ?? "");
67
+ }
68
+ function classifyValueShape(inner) {
69
+ if (!inner) return null;
70
+ const scalar = classifyField(inner);
71
+ if (scalar) return { container: "scalar", kind: scalar };
72
+ if (inner.jsonType === "array" && Array.isArray(inner.of)) {
73
+ const member = inner.of[0];
74
+ if (member?.jsonType === "string" && (member.name === "string" || member.name === "text"))
75
+ return { container: "arrayOfScalar", kind: "plain" };
76
+ if (isPlainObject(member)) {
77
+ const leaves = collectLeaves(member, "");
78
+ if (leaves.length) return { container: "arrayOfObject", leaves };
79
+ }
80
+ return null;
81
+ }
82
+ if (isPlainObject(inner)) {
83
+ const leaves = collectLeaves(inner, "");
84
+ if (leaves.length) return { container: "object", leaves };
85
+ }
86
+ return null;
87
+ }
88
+ function classifyValueShapeByJsonType(inner) {
89
+ const kind = classifyByJsonType(inner);
90
+ return kind ? { container: "scalar", kind } : null;
91
+ }
92
+ function collectLeaves(objType, prefix) {
93
+ const leaves = [];
94
+ for (const f of objType?.fields ?? []) {
95
+ if (!f?.name || f.name.startsWith("_") || isExcludedByDocumentI18n(f) && f.type?.options?.smartcatTranslation?.include !== !0) continue;
96
+ const subPath = prefix ? `${prefix}.${f.name}` : f.name, kind = classifyField(f.type);
97
+ kind ? leaves.push({ subPath, kind, title: f.type?.title || titleCase(f.name) }) : isPlainObject(f.type) && leaves.push(...collectLeaves(f.type, subPath));
98
+ }
99
+ return leaves;
100
+ }
101
+ function isPortableTextArray(type) {
102
+ return type.jsonType === "array" && Array.isArray(type.of) && type.of.some((member) => member?.name === "block" || member?.jsonType === "block");
103
+ }
104
+ function classifyField(type) {
105
+ return type ? type.jsonType === "string" && (type.name === "string" || type.name === "text") ? "plain" : isPortableTextArray(type) ? "portableText" : null : null;
106
+ }
107
+ function classifyByJsonType(type) {
108
+ return type ? type.jsonType === "string" ? "plain" : isPortableTextArray(type) ? "portableText" : null : null;
109
+ }
110
+ function warnUntranslatableInclude(fieldName, type) {
111
+ console.warn(
112
+ `[smartcat-translation] Field "${fieldName}" is marked smartcatTranslation.include but its type (name: ${JSON.stringify(type?.name)}, jsonType: ${JSON.stringify(type?.jsonType)}) has no translatable representation; skipping.`
113
+ );
114
+ }
115
+ function titleCase(name) {
116
+ return name.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
117
+ }
118
+ function inferTranslatableFields(doc, options = {}) {
119
+ if (isSystemType(doc._type)) return [];
120
+ const exclude = new Set(options.exclude ?? []), isI18nArray = (value) => Array.isArray(value) && value.some((m) => m && typeof m == "object" && isInternationalizedArrayMemberType(m._type)), entries = Object.entries(doc).filter(([key]) => !key.startsWith("_") && !exclude.has(key)), fieldMode = entries.some(([, value]) => isI18nArray(value)), result = [];
121
+ for (const [key, value] of entries)
122
+ if (fieldMode) {
123
+ if (!isI18nArray(value)) continue;
124
+ const sample = value.find((m) => m && typeof m == "object")?.value, kind = sampleKind(sample);
125
+ kind && result.push({ path: key, kind, localization: "field", title: titleCase(key) });
126
+ } else typeof value == "string" ? value.length > 0 && result.push({ path: key, kind: "plain", localization: "document", title: titleCase(key) }) : Array.isArray(value) && value.some(isPortableTextBlock) && result.push({ path: key, kind: "portableText", localization: "document", title: titleCase(key) });
127
+ return result;
128
+ }
129
+ function sampleKind(value) {
130
+ return typeof value == "string" ? "plain" : Array.isArray(value) && value.some(isPortableTextBlock) ? "portableText" : null;
131
+ }
132
+ function isPortableTextBlock(value) {
133
+ return !!(value && typeof value == "object" && value._type === "block");
134
+ }
135
+ function orderFieldsBy(fields, orderedPaths) {
136
+ if (!orderedPaths || orderedPaths.length === 0) return fields;
137
+ const rank = new Map(orderedPaths.map((path, i) => [path, i])), at = (path) => rank.has(path) ? rank.get(path) : Number.MAX_SAFE_INTEGER;
138
+ return fields.map((field, i) => ({ field, i })).sort((a, b) => at(a.field.path) - at(b.field.path) || a.i - b.i).map((x) => x.field);
139
+ }
140
+ function parsePath(path) {
141
+ const segs = [], re = /\.?([^.[\]]+)|\[([^\]]+)\]/g;
142
+ let m;
143
+ for (; (m = re.exec(path)) !== null; )
144
+ m[1] !== void 0 ? segs.push({ field: m[1] }) : /^\d+$/.test(m[2]) ? segs.push({ index: Number(m[2]) }) : segs.push({ key: m[2] });
145
+ return segs;
146
+ }
147
+ function child(container, seg) {
148
+ if (!(container == null || typeof container != "object"))
149
+ return "field" in seg ? container[seg.field] : "index" in seg ? Array.isArray(container) ? container[seg.index] : void 0 : Array.isArray(container) ? container.find((m) => m && typeof m == "object" && m._key === seg.key) : void 0;
150
+ }
151
+ function getAtPath(root, path) {
152
+ let cur = root;
153
+ for (const seg of parsePath(path))
154
+ if (cur = child(cur, seg), cur === void 0) return;
155
+ return cur;
156
+ }
157
+ function setAtPath(root, path, value) {
158
+ const segs = parsePath(path);
159
+ if (segs.length === 0) return value;
160
+ const clone = structuredClone(root);
161
+ let cur = clone;
162
+ for (let i = 0; i < segs.length - 1; i++)
163
+ if (cur = child(cur, segs[i]), cur == null || typeof cur != "object") return clone;
164
+ const last = segs[segs.length - 1];
165
+ if ("field" in last) cur[last.field] = value;
166
+ else if ("index" in last && Array.isArray(cur)) cur[last.index] = value;
167
+ else if ("key" in last && Array.isArray(cur)) {
168
+ const idx = cur.findIndex((m) => m && typeof m == "object" && m._key === last.key);
169
+ idx >= 0 && (cur[idx] = value);
170
+ }
171
+ return clone;
172
+ }
173
+ const SERIALIZABLE_CUSTOM_TYPES = /* @__PURE__ */ new Set(["table"]);
174
+ function tableToHtml(value) {
175
+ return `<table><tbody>${(Array.isArray(value?.rows) ? value.rows : []).map((row) => `<tr>${(Array.isArray(row?.cells) ? row.cells : []).map((cell) => `<td>${escapeHTML(typeof cell == "string" ? cell : "")}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
176
+ }
177
+ const tableRule = {
178
+ deserialize(el, _next, createBlock) {
179
+ if (el.tagName?.toLowerCase() !== "table") return;
180
+ const rows = Array.from(el.querySelectorAll("tr")).map((tr, i) => ({
181
+ _type: "tableRow",
182
+ _key: `row${i}`,
183
+ cells: Array.from(tr.querySelectorAll("td, th")).map((cell) => cell.textContent ?? "")
184
+ }));
185
+ return createBlock({ _type: "table", rows });
186
+ }
187
+ };
188
+ function portableTextToHtml(blocks) {
189
+ return !blocks || blocks.length === 0 ? "" : toHTML(blocks, {
190
+ // Fallback only. Serialization skips any field containing an unserializable
191
+ // block up front (see findUnserializableBlockTypes), so to-html should never
192
+ // meet an unknown type here. If one slips through, render it as empty rather
193
+ // than let @portabletext/to-html emit its default placeholder — a hidden
194
+ // `<div style="display:none">Unknown block type "…"</div>` whose English text
195
+ // would otherwise be sent to Smartcat and translated into every locale.
196
+ // (`onMissingComponent: false` only silences the warning; it does NOT stop the
197
+ // placeholder — the `unknownType` override is what suppresses it.)
198
+ onMissingComponent: !1,
199
+ components: {
200
+ unknownType: () => "",
201
+ // Serializable custom block types get real markup so their text is
202
+ // translatable and can be parsed back (see SERIALIZABLE_CUSTOM_TYPES).
203
+ types: { table: ({ value }) => tableToHtml(value) }
204
+ }
205
+ });
206
+ }
207
+ function findUnserializableBlockTypes(blocks) {
208
+ if (!Array.isArray(blocks)) return [];
209
+ const types = /* @__PURE__ */ new Set();
210
+ for (const block of blocks) {
211
+ if (!block || typeof block != "object") continue;
212
+ const type = block._type;
213
+ if (type !== "block") {
214
+ typeof type == "string" && !SERIALIZABLE_CUSTOM_TYPES.has(type) && types.add(type);
215
+ continue;
216
+ }
217
+ const children = block.children;
218
+ if (Array.isArray(children))
219
+ for (const child2 of children) {
220
+ const childType = child2?._type;
221
+ typeof childType == "string" && childType !== "span" && types.add(childType);
222
+ }
223
+ }
224
+ return [...types].sort();
225
+ }
226
+ function portableTextToPlainText(blocks) {
227
+ if (!Array.isArray(blocks)) return "";
228
+ let text = "";
229
+ const visit = (node) => {
230
+ if (Array.isArray(node))
231
+ node.forEach(visit);
232
+ else if (node && typeof node == "object") {
233
+ const value = node;
234
+ if (typeof value.text == "string" && (text += value.text), Array.isArray(value.children) && visit(value.children), Array.isArray(value.rows))
235
+ for (const row of value.rows) {
236
+ const cells = row?.cells;
237
+ if (Array.isArray(cells)) for (const cell of cells) typeof cell == "string" && (text += cell);
238
+ }
239
+ }
240
+ };
241
+ return visit(blocks), text;
242
+ }
243
+ function htmlToPortableText(html, blockContentType, parseHtml) {
244
+ return html.trim() ? htmlToBlocks(html, blockContentType, {
245
+ parseHtml,
246
+ rules: [tableRule]
247
+ }) : [];
248
+ }
249
+ function serializeToLocjson(doc, fields, options) {
250
+ const units = [];
251
+ for (const field of fields) {
252
+ const source = field.localization === "field" ? memberValue(getAtPath(doc, field.path), options.sourceLanguage, options.fieldLanguageKey) : getAtPath(doc, field.path);
253
+ for (const leaf of enumerateLeaves(field, source)) {
254
+ const value = leaf.valuePath ? getAtPath(source, leaf.valuePath) : source, comments = leaf.title ? [leaf.title] : void 0;
255
+ if (leaf.kind === "plain") {
256
+ if (typeof value != "string" || value.trim().length === 0) continue;
257
+ units.push({
258
+ key: leaf.fullKey,
259
+ properties: { comments, "x-smartcat-split": "full", "x-sanity": { fieldPath: leaf.fullKey } },
260
+ // Split into line segments but keep the trailing newline on each, so
261
+ // concatenating the segments (LocJSON's '' join) reconstructs the original.
262
+ source: value.split(new RegExp("(?<=\\n)")),
263
+ target: []
264
+ });
265
+ } else {
266
+ const blocks = value, unserializable = findUnserializableBlockTypes(blocks);
267
+ if (unserializable.length > 0) {
268
+ options.onSkippedField?.({ fieldPath: field.path, title: field.title, types: unserializable });
269
+ continue;
270
+ }
271
+ const html = portableTextToHtml(blocks);
272
+ if (!html || portableTextToPlainText(blocks).trim().length === 0) continue;
273
+ units.push({
274
+ key: leaf.fullKey,
275
+ properties: { comments, "x-smartcat-format": "html", "x-smartcat-split": "full", "x-sanity": { fieldPath: leaf.fullKey } },
276
+ source: [html],
277
+ target: []
278
+ });
279
+ }
280
+ }
281
+ }
282
+ return {
283
+ properties: {
284
+ version: 1,
285
+ "x-sanity": {
286
+ documentId: doc._id,
287
+ documentType: doc._type,
288
+ rev: doc._rev,
289
+ sourceLanguage: options.sourceLanguage
290
+ }
291
+ },
292
+ units
293
+ };
294
+ }
295
+ function memberValue(field, language, languageKey) {
296
+ return Array.isArray(field) ? field.find(
297
+ (m) => m && typeof m == "object" && m[languageKey] === language
298
+ )?.value : void 0;
299
+ }
300
+ function buildLocjsonFilename(documentType, documentId, title, options = {}) {
301
+ const idPrefix = stripDraft(documentId).slice(0, 8) || "unknown", safeTitle = sanitizeSegment(title || "Untitled"), safeType = sanitizeSegment(documentType) || "document", draftMarker = options.draft ? "-draft" : "";
302
+ return `${safeType}/${safeTitle}-${idPrefix}${draftMarker}.locjson`;
303
+ }
304
+ function stripDraft(id) {
305
+ return id.replace(/^drafts\./, "");
306
+ }
307
+ function sanitizeSegment(value) {
308
+ return value.replace(/[/\\?%*:|"<>]/g, " ").replace(/\s+/g, " ").trim();
309
+ }
310
+ function deserializeFromLocjson(locjson, options) {
311
+ const fileMeta = locjson.properties?.["x-sanity"], fields = {}, sources = {};
312
+ for (const unit of locjson.units ?? []) {
313
+ const fieldPath = unit.properties?.["x-sanity"]?.fieldPath ?? unit.key, value = ((unit.target?.length ? unit.target : unit.source) ?? []).join("");
314
+ sources[fieldPath] = (unit.source ?? []).join(""), unit.properties?.["x-smartcat-format"] === "html" ? fields[fieldPath] = htmlToPortableText(value, options.getBlockContentType(fieldPath), options.parseHtml) : fields[fieldPath] = value;
315
+ }
316
+ return {
317
+ documentId: fileMeta?.documentId,
318
+ documentType: fileMeta?.documentType,
319
+ sourceLanguage: fileMeta?.sourceLanguage,
320
+ fields,
321
+ sources
322
+ };
323
+ }
324
+ export {
325
+ buildLocjsonFilename,
326
+ deserializeFromLocjson,
327
+ enumerateLeaves,
328
+ getAtPath,
329
+ getTranslatableFields,
330
+ htmlToPortableText,
331
+ inferTranslatableFields,
332
+ innerValueType,
333
+ isInternationalizedArrayType,
334
+ localizationMode,
335
+ orderFieldsBy,
336
+ portableTextToHtml,
337
+ serializeToLocjson,
338
+ setAtPath
339
+ };
340
+ //# sourceMappingURL=index2.js.map