@textunited/sanity-plugin 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,833 @@
1
+ // src/server/sanityStore.ts
2
+ var SanityConflictError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "SanityConflictError";
6
+ }
7
+ };
8
+ var HttpSanityStore = class {
9
+ base;
10
+ dataset;
11
+ token;
12
+ fetchImpl;
13
+ constructor(options) {
14
+ const apiVersion = options.apiVersion ?? "2025-02-19";
15
+ this.base = `https://${options.projectId}.api.sanity.io/v${apiVersion}/data`;
16
+ this.dataset = options.dataset;
17
+ this.token = options.token;
18
+ this.fetchImpl = options.fetch ?? fetch;
19
+ }
20
+ async query(query, params) {
21
+ const response = await this.fetchImpl(`${this.base}/query/${this.dataset}?perspective=raw`, {
22
+ method: "POST",
23
+ headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/json" },
24
+ body: JSON.stringify({ query, params })
25
+ });
26
+ if (!response.ok) {
27
+ throw new Error(`Sanity query failed with status ${response.status}: ${await response.text()}`);
28
+ }
29
+ return (await response.json()).result;
30
+ }
31
+ getDocument(id) {
32
+ return this.query("*[_id == $id][0]", { id });
33
+ }
34
+ findTranslationMetadata(baseDocumentId) {
35
+ return this.query(
36
+ '*[_type == "translation.metadata" && $id in translations[].value._ref][0]',
37
+ { id: baseDocumentId }
38
+ );
39
+ }
40
+ listPendingDocuments(limit) {
41
+ return this.query(
42
+ '*[_type == "textunited.translationState" && pending == true] | order(updatedAt asc) [0...$limit].documentId',
43
+ { limit }
44
+ );
45
+ }
46
+ async mutate(mutations) {
47
+ if (mutations.length === 0) return;
48
+ const response = await this.fetchImpl(
49
+ `${this.base}/mutate/${this.dataset}?visibility=sync`,
50
+ {
51
+ method: "POST",
52
+ headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/json" },
53
+ body: JSON.stringify({ mutations })
54
+ }
55
+ );
56
+ if (response.status === 409) {
57
+ throw new SanityConflictError(await response.text());
58
+ }
59
+ if (!response.ok) {
60
+ throw new Error(`Sanity mutation failed with status ${response.status}: ${await response.text()}`);
61
+ }
62
+ }
63
+ };
64
+ async function getPreferredDocument(store, baseDocumentId) {
65
+ const draft = await store.getDocument(`drafts.${baseDocumentId}`);
66
+ return draft ?? store.getDocument(baseDocumentId);
67
+ }
68
+
69
+ // src/core/hash.ts
70
+ var FNV_PRIME = 0x100000001b3n;
71
+ var MASK_64 = 0xffffffffffffffffn;
72
+ function fnv1a64(input, offsetBasis) {
73
+ let hash = offsetBasis;
74
+ for (const byte of new TextEncoder().encode(input)) {
75
+ hash ^= BigInt(byte);
76
+ hash = hash * FNV_PRIME & MASK_64;
77
+ }
78
+ return hash;
79
+ }
80
+ function stableHash(input) {
81
+ const first = fnv1a64(input, 0xcbf29ce484222325n);
82
+ const second = fnv1a64(input, 0x84222325cbf29ce4n);
83
+ return first.toString(16).padStart(16, "0") + second.toString(16).padStart(16, "0");
84
+ }
85
+
86
+ // src/core/ids.ts
87
+ function pathToString(path) {
88
+ let result = "";
89
+ for (const segment of path) {
90
+ if (typeof segment === "string") {
91
+ result += result ? `.${segment}` : segment;
92
+ } else if (typeof segment === "number") {
93
+ result += `[${segment}]`;
94
+ } else {
95
+ result += `[_key==${JSON.stringify(segment._key)}]`;
96
+ }
97
+ }
98
+ return result;
99
+ }
100
+ function getBaseDocumentId(documentId) {
101
+ if (documentId.startsWith("drafts.")) return documentId.slice("drafts.".length);
102
+ if (documentId.startsWith("versions.")) {
103
+ const rest = documentId.slice("versions.".length);
104
+ const dot = rest.indexOf(".");
105
+ return dot === -1 ? rest : rest.slice(dot + 1);
106
+ }
107
+ return documentId;
108
+ }
109
+ function createProjectCustomId(args) {
110
+ return `sanity-${args.sanityProjectId}-${args.dataset}-${getBaseDocumentId(args.documentId)}`;
111
+ }
112
+ var FIELDS_TASK_ID = "fields";
113
+ function createTaskId(field, item) {
114
+ if (item === void 0) return field;
115
+ if (typeof item === "object") return `${field}.${item._key}`;
116
+ return `${field}.${item}`;
117
+ }
118
+ function createSegmentCustomId(path, chunk = 0) {
119
+ const suffix = chunk > 0 ? `#${chunk}` : "";
120
+ return `seg-${stableHash(pathToString(path) + suffix)}`;
121
+ }
122
+
123
+ // src/core/projects.ts
124
+ function isProjectType(value) {
125
+ return value === "outsourced" || value === "inHouse";
126
+ }
127
+ function toRecord(value) {
128
+ const record = value;
129
+ if (!record || typeof record.customId !== "string") return null;
130
+ return {
131
+ customId: record.customId,
132
+ languages: Array.isArray(record.languages) ? record.languages.map(String) : [],
133
+ ...isProjectType(record.projectType) ? { projectType: record.projectType } : {},
134
+ ...typeof record.projectId === "number" ? { projectId: record.projectId } : {},
135
+ ...typeof record.createdAt === "string" ? { createdAt: record.createdAt } : {}
136
+ };
137
+ }
138
+ function readProjects(document) {
139
+ if (!document) return { projects: [], archived: [], stopped: [] };
140
+ if (typeof document.projectsJson === "string") {
141
+ try {
142
+ const parsed = JSON.parse(document.projectsJson);
143
+ return {
144
+ projects: (parsed.projects ?? []).map(toRecord).filter((p) => p !== null),
145
+ archived: (parsed.archived ?? []).map(toRecord).filter((p) => p !== null),
146
+ stopped: Array.isArray(parsed.stopped) ? parsed.stopped.map(String) : []
147
+ };
148
+ } catch {
149
+ }
150
+ }
151
+ if (typeof document.projectCustomId !== "string") return { projects: [], archived: [], stopped: [] };
152
+ const legacy = toRecord({
153
+ customId: document.projectCustomId,
154
+ languages: document.projectLanguages,
155
+ projectType: document.projectType,
156
+ projectId: document.projectId
157
+ });
158
+ return { projects: legacy ? [legacy] : [], archived: [], stopped: [] };
159
+ }
160
+ function activeProjects(projects, stopped) {
161
+ if (stopped.length === 0) return projects;
162
+ return projects.map((project) => ({ ...project, languages: project.languages.filter((language) => !stopped.includes(language)) })).filter((project) => project.languages.length > 0);
163
+ }
164
+ function projectForLanguage(projects, language) {
165
+ return projects.find((project) => project.languages.includes(language));
166
+ }
167
+ function projectLanguages(projects) {
168
+ return [...new Set(projects.flatMap((project) => project.languages))];
169
+ }
170
+
171
+ // src/core/document/paths.ts
172
+ function isPlainObject(value) {
173
+ return typeof value === "object" && value !== null && !Array.isArray(value);
174
+ }
175
+ function cloneValue(value) {
176
+ return structuredClone(value);
177
+ }
178
+ function cloneForTranslation(value) {
179
+ const copy = structuredClone(value);
180
+ const strip = (node) => {
181
+ if (Array.isArray(node)) {
182
+ node.forEach(strip);
183
+ } else if (isPlainObject(node)) {
184
+ for (const key of Object.keys(node)) {
185
+ if (/canonical/i.test(key)) delete node[key];
186
+ else strip(node[key]);
187
+ }
188
+ }
189
+ };
190
+ strip(copy);
191
+ return copy;
192
+ }
193
+ function arrayItemSegment(item, index) {
194
+ return isPlainObject(item) && typeof item._key === "string" ? { _key: item._key } : index;
195
+ }
196
+ function findArrayIndex(array, segment) {
197
+ if (typeof segment === "number") return segment < array.length ? segment : -1;
198
+ if (typeof segment === "object") {
199
+ return array.findIndex((item) => isPlainObject(item) && item._key === segment._key);
200
+ }
201
+ return -1;
202
+ }
203
+ function getAtPath(root, path) {
204
+ let current = root;
205
+ for (const segment of path) {
206
+ if (Array.isArray(current)) {
207
+ const index = findArrayIndex(current, segment);
208
+ if (index === -1) return void 0;
209
+ current = current[index];
210
+ } else if (isPlainObject(current) && typeof segment === "string") {
211
+ current = current[segment];
212
+ } else {
213
+ return void 0;
214
+ }
215
+ }
216
+ return current;
217
+ }
218
+ function setAtPath(target, source, path, value) {
219
+ if (path.length === 0) throw new Error("Cannot set a value at an empty path");
220
+ let current = target;
221
+ let currentSource = source;
222
+ for (let depth = 0; depth < path.length; depth += 1) {
223
+ const segment = path[depth];
224
+ const isLast = depth === path.length - 1;
225
+ const nextSource = getAtPath(currentSource, [segment]);
226
+ if (Array.isArray(current)) {
227
+ let index = findArrayIndex(current, segment);
228
+ if (index === -1) {
229
+ if (isLast) {
230
+ current.push(value);
231
+ return;
232
+ }
233
+ const sourceArray = Array.isArray(currentSource) ? currentSource : [];
234
+ const sourceIndex = findArrayIndex(sourceArray, segment);
235
+ const placeholder = cloneValue(nextSource ?? (typeof segment === "object" ? { _key: segment._key } : {}));
236
+ index = insertionIndex(current, sourceArray, sourceIndex);
237
+ current.splice(index, 0, placeholder);
238
+ }
239
+ if (isLast) {
240
+ current[index] = value;
241
+ return;
242
+ }
243
+ current = current[index];
244
+ } else if (isPlainObject(current) && typeof segment === "string") {
245
+ if (isLast) {
246
+ current[segment] = value;
247
+ return;
248
+ }
249
+ if (current[segment] === void 0 || current[segment] === null) {
250
+ current[segment] = nextSource !== void 0 && nextSource !== null ? cloneForTranslation(nextSource) : emptyContainer(nextSource, path[depth + 1]);
251
+ }
252
+ current = current[segment];
253
+ } else {
254
+ throw new Error("Path does not match the document structure");
255
+ }
256
+ currentSource = nextSource;
257
+ }
258
+ }
259
+ function emptyContainer(source, next) {
260
+ if (Array.isArray(source) || typeof next !== "string") return [];
261
+ return isPlainObject(source) && typeof source._type === "string" ? { _type: source._type } : {};
262
+ }
263
+ function insertionIndex(target, source, sourceIndex) {
264
+ for (let i = sourceIndex - 1; i >= 0; i -= 1) {
265
+ const previous = source[i];
266
+ if (isPlainObject(previous) && typeof previous._key === "string") {
267
+ const found = findArrayIndex(target, { _key: previous._key });
268
+ if (found !== -1) return found + 1;
269
+ }
270
+ }
271
+ return sourceIndex >= 0 ? 0 : target.length;
272
+ }
273
+
274
+ // src/core/document/intl.ts
275
+ function isIntlArray(value) {
276
+ return Array.isArray(value) && value.length > 0 && value.every(
277
+ (item) => isPlainObject(item) && typeof item._key === "string" && (typeof item._type === "string" ? item._type.startsWith("internationalizedArray") : "value" in item)
278
+ );
279
+ }
280
+ function getIntlItem(array, language) {
281
+ if (!Array.isArray(array)) return void 0;
282
+ return array.find(
283
+ (item) => isPlainObject(item) && item._key === language
284
+ );
285
+ }
286
+
287
+ // src/core/document/portableText.ts
288
+ var MAX_SEGMENT_LENGTH = 2e3;
289
+ var ENTITIES = { amp: "&", apos: "'", gt: ">", lt: "<", nbsp: " ", quot: '"' };
290
+ function isPortableTextBlock(value) {
291
+ return isPlainObject(value) && value._type === "block";
292
+ }
293
+ function isPortableTextArray(value) {
294
+ return Array.isArray(value) && value.some(isPortableTextBlock);
295
+ }
296
+ function isSpan(value) {
297
+ return isPlainObject(value) && value._type === "span" && typeof value.text === "string";
298
+ }
299
+ function escapeHtml(value) {
300
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
301
+ }
302
+ function decodeHtmlEntities(text) {
303
+ return text.replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi, (entity, token) => {
304
+ if (token[0] === "#") {
305
+ const codePoint = token[1] === "x" || token[1] === "X" ? Number.parseInt(token.slice(2), 16) : Number.parseInt(token.slice(1), 10);
306
+ return Number.isFinite(codePoint) ? String.fromCodePoint(codePoint) : entity;
307
+ }
308
+ return ENTITIES[token.toLowerCase()] ?? entity;
309
+ });
310
+ }
311
+ function spanId(span, index) {
312
+ return typeof span._key === "string" ? span._key : `child-${index}`;
313
+ }
314
+ function isPlainBlock(block, spans) {
315
+ return spans.length === 1 && (!Array.isArray(block.markDefs) || block.markDefs.length === 0) && (!Array.isArray(spans[0]?.marks) || spans[0].marks.length === 0) && (block.children?.length ?? 0) === 1;
316
+ }
317
+ function splitText(text, maxLength) {
318
+ const parts = [];
319
+ let remaining = text;
320
+ while (remaining.length > maxLength) {
321
+ const slice = remaining.slice(0, maxLength);
322
+ const boundary = Math.max(
323
+ slice.lastIndexOf(". "),
324
+ slice.lastIndexOf("! "),
325
+ slice.lastIndexOf("? "),
326
+ slice.lastIndexOf("; "),
327
+ slice.lastIndexOf(", "),
328
+ slice.lastIndexOf(" ")
329
+ );
330
+ const splitAt = boundary > maxLength * 0.5 ? boundary + 1 : maxLength;
331
+ parts.push(remaining.slice(0, splitAt));
332
+ remaining = remaining.slice(splitAt);
333
+ }
334
+ if (remaining) parts.push(remaining);
335
+ return parts;
336
+ }
337
+ function joinTextChunks(chunks) {
338
+ return chunks.reduce((joined, chunk) => {
339
+ if (!joined) return chunk;
340
+ return /\s$/.test(joined) || /^\s/.test(chunk) ? joined + chunk : `${joined} ${chunk}`;
341
+ }, "");
342
+ }
343
+ function blockToSegmentContents(block) {
344
+ const spans = (block.children ?? []).filter(isSpan);
345
+ if (!spans.some((span) => span.text.trim() !== "")) return [];
346
+ if (isPlainBlock(block, spans)) {
347
+ return splitText(spans[0].text, MAX_SEGMENT_LENGTH);
348
+ }
349
+ const chunks = [];
350
+ let current = "";
351
+ spans.forEach((span, index) => {
352
+ if (span.text === "") return;
353
+ const id = escapeHtml(spanId(span, index));
354
+ const wrapperLength = `<span data-tu-id="${id}"></span>`.length;
355
+ for (const part of splitText(span.text, Math.max(100, MAX_SEGMENT_LENGTH - wrapperLength))) {
356
+ const wrapped = `<span data-tu-id="${id}">${escapeHtml(part)}</span>`;
357
+ if (current && current.length + wrapped.length > MAX_SEGMENT_LENGTH) {
358
+ chunks.push(current);
359
+ current = "";
360
+ }
361
+ current += wrapped;
362
+ }
363
+ });
364
+ if (current) chunks.push(current);
365
+ return chunks;
366
+ }
367
+ function blockText(block) {
368
+ if (!isPortableTextBlock(block)) return "";
369
+ return (block.children ?? []).filter(isSpan).map((span) => span.text).join("");
370
+ }
371
+ function applyBlockTranslation(sourceBlock, translatedChunks) {
372
+ const block = cloneValue(sourceBlock);
373
+ const children = block.children ?? [];
374
+ const spans = children.filter(isSpan);
375
+ if (isPlainBlock(sourceBlock, (sourceBlock.children ?? []).filter(isSpan))) {
376
+ const span = spans[0];
377
+ span.text = decodeHtmlEntities(joinTextChunks(translatedChunks).replace(/<[^>]*>/g, ""));
378
+ return block;
379
+ }
380
+ const translatedById = /* @__PURE__ */ new Map();
381
+ const pattern = /<span\b([^>]*)>([\s\S]*?)<\/span>/gi;
382
+ const html = translatedChunks.join("");
383
+ let match;
384
+ while (match = pattern.exec(html)) {
385
+ const idMatch = (match[1] ?? "").match(/\bdata-tu-id\s*=\s*["']([^"']+)["']/i);
386
+ if (!idMatch?.[1]) continue;
387
+ const id = decodeHtmlEntities(idMatch[1]);
388
+ const text = decodeHtmlEntities((match[2] ?? "").replace(/<[^>]*>/g, ""));
389
+ translatedById.set(id, (translatedById.get(id) ?? "") + text);
390
+ }
391
+ spans.forEach((span, index) => {
392
+ const translated = translatedById.get(spanId(span, index));
393
+ if (translated !== void 0) span.text = translated;
394
+ });
395
+ return block;
396
+ }
397
+
398
+ // src/core/document/target.ts
399
+ function readTargetValue(unit, language, targets) {
400
+ if (targets.model === "fieldLevel") {
401
+ const item = getIntlItem(getAtPath(targets.document, unit.fieldPath), language);
402
+ return getAtPath(item?.value, unit.innerPath);
403
+ }
404
+ return getAtPath(targets.documents[language], [...unit.fieldPath, ...unit.innerPath]);
405
+ }
406
+ function isMissingValue(unit, value) {
407
+ if (unit.kind === "text") {
408
+ return typeof value !== "string" || value.trim() === "" || value.trim() === String(unit.source).trim();
409
+ }
410
+ return blockText(value).trim() === "" || blockText(value) === blockText(unit.source);
411
+ }
412
+ function needsTranslation(unit, value, appliedHash) {
413
+ if (!isMissingValue(unit, value)) return false;
414
+ const empty = unit.kind === "text" ? typeof value !== "string" || value.trim() === "" : blockText(value).trim() === "";
415
+ return empty || appliedHash !== valueHash(value);
416
+ }
417
+ function valueHash(value) {
418
+ return stableHash(JSON.stringify(value ?? null));
419
+ }
420
+
421
+ // src/core/plan.ts
422
+ function sentRecord(record, projectCustomId) {
423
+ return record?.projects?.[projectCustomId];
424
+ }
425
+ function migrateLegacyState(state, legacyProjectCustomId) {
426
+ if (!legacyProjectCustomId) return state;
427
+ let changed = false;
428
+ const units = {};
429
+ for (const [id, record] of Object.entries(state.units)) {
430
+ if (record.sentAt && !record.projects) {
431
+ const { taskId, ...rest } = record;
432
+ units[id] = {
433
+ ...rest,
434
+ projects: {
435
+ [legacyProjectCustomId]: { sourceHash: record.sourceHash, sentAt: record.sentAt, ...taskId ? { taskId } : {} }
436
+ }
437
+ };
438
+ changed = true;
439
+ } else {
440
+ units[id] = record;
441
+ }
442
+ }
443
+ return changed ? { units } : state;
444
+ }
445
+ function emptyState() {
446
+ return { units: {} };
447
+ }
448
+ function selectionReason(unit, languages, targets, state, mode, projectCustomId) {
449
+ if (mode === "all") return "all";
450
+ const record = state.units[unit.id];
451
+ if (languages.some(
452
+ (language) => needsTranslation(unit, readTargetValue(unit, language, targets), record?.languages[language]?.appliedHash)
453
+ )) {
454
+ return "missing";
455
+ }
456
+ const sentHash = (projectCustomId ? sentRecord(record, projectCustomId)?.sourceHash : void 0) ?? record?.sourceHash;
457
+ if (mode === "changed" && sentHash !== void 0 && sentHash !== unit.sourceHash) return "sourceChanged";
458
+ return null;
459
+ }
460
+ function planTranslation(args) {
461
+ const selected = [];
462
+ for (const unit of args.units) {
463
+ const reason = selectionReason(unit, args.languages, args.targets, args.state, args.mode, args.projectCustomId);
464
+ if (reason) selected.push({ unit, reason });
465
+ }
466
+ const taskIds = new Set(selected.map(({ unit }) => unit.taskId));
467
+ const tasks = [...taskIds].map((taskId) => ({
468
+ taskId,
469
+ segments: args.units.filter((unit) => unit.taskId === taskId).flatMap((unit) => unit.segments.map((segment) => ({ ...segment, taskId })))
470
+ }));
471
+ return { selected, tasks };
472
+ }
473
+ function recordBaseline(state, units) {
474
+ const next = { units: { ...state.units } };
475
+ for (const unit of units) {
476
+ next.units[unit.id] ??= { sourceHash: unit.sourceHash, languages: {} };
477
+ }
478
+ return next;
479
+ }
480
+ function recordSentUnits(state, units, sentAt = (/* @__PURE__ */ new Date()).toISOString(), taskId, projectCustomId) {
481
+ const next = { units: { ...state.units } };
482
+ for (const unit of units) {
483
+ const previous = next.units[unit.id];
484
+ if (projectCustomId) {
485
+ next.units[unit.id] = {
486
+ sourceHash: unit.sourceHash,
487
+ sentAt,
488
+ projects: {
489
+ ...previous?.projects,
490
+ [projectCustomId]: { sourceHash: unit.sourceHash, sentAt, ...taskId ? { taskId } : {} }
491
+ },
492
+ languages: previous?.languages ?? {}
493
+ };
494
+ } else {
495
+ next.units[unit.id] = {
496
+ sourceHash: unit.sourceHash,
497
+ sentAt,
498
+ ...taskId ? { taskId } : {},
499
+ languages: previous?.languages ?? {}
500
+ };
501
+ }
502
+ }
503
+ return next;
504
+ }
505
+ function mergeState(base, changes, unitIds) {
506
+ const next = { units: { ...base.units } };
507
+ for (const id of unitIds) {
508
+ const record = changes.units[id];
509
+ if (record) next.units[id] = record;
510
+ }
511
+ return next;
512
+ }
513
+ function hasPendingTranslations(state, projects, isFinal) {
514
+ return Object.values(state.units).some(
515
+ (record) => projects.some(
516
+ (project) => sentRecord(record, project.customId) !== void 0 && project.languages.some((language) => !isFinal(record.languages[language]?.status))
517
+ )
518
+ );
519
+ }
520
+
521
+ // src/core/config.ts
522
+ var BUILT_IN_SKIP_FIELDS = /* @__PURE__ */ new Set([
523
+ "language",
524
+ "slug",
525
+ "current",
526
+ "href",
527
+ "url",
528
+ "link",
529
+ "asset",
530
+ "crop",
531
+ "hotspot",
532
+ "markDefs",
533
+ "style",
534
+ "listItem",
535
+ "level"
536
+ ]);
537
+ function getDocumentTypeConfig(config, documentType) {
538
+ return config.documentTypes.find((entry) => entry.type === documentType);
539
+ }
540
+
541
+ // src/core/document/extract.ts
542
+ var NON_TEXT_PATTERNS = [
543
+ /^https?:\/\//i,
544
+ /^mailto:/i,
545
+ /^tel:/i,
546
+ /^#[0-9a-f]{3,8}$/i,
547
+ // colors
548
+ /^[\d\s.,:%+-]+$/,
549
+ // numbers, dates, percentages
550
+ /^\d{4}-\d{2}-\d{2}/
551
+ // ISO dates
552
+ ];
553
+ function isTranslatableString(value) {
554
+ const trimmed = value.trim();
555
+ return trimmed !== "" && !NON_TEXT_PATTERNS.some((pattern) => pattern.test(trimmed));
556
+ }
557
+ function shouldSkipField(name, context) {
558
+ return name.startsWith("_") || context.skipFields.has(name);
559
+ }
560
+ function addTextUnit(context, taskId, fieldPath, text) {
561
+ const id = pathToString(fieldPath);
562
+ const parts = splitText(text, MAX_SEGMENT_LENGTH);
563
+ context.units.push({
564
+ id,
565
+ taskId,
566
+ fieldPath,
567
+ innerPath: [],
568
+ kind: "text",
569
+ source: text,
570
+ segments: parts.map((content, chunk) => ({
571
+ customId: createSegmentCustomId(fieldPath, chunk),
572
+ content
573
+ })),
574
+ sourceHash: stableHash(text)
575
+ });
576
+ }
577
+ function addBlockUnits(context, taskId, fieldPath, blocks, walkObjects) {
578
+ blocks.forEach((block, index) => {
579
+ const segment = arrayItemSegment(block, index);
580
+ if (isPortableTextBlock(block)) {
581
+ const contents = blockToSegmentContents(block);
582
+ if (contents.length === 0) return;
583
+ const innerPath = [segment];
584
+ const fullPath = [...fieldPath, ...innerPath];
585
+ context.units.push({
586
+ id: pathToString(fullPath),
587
+ taskId,
588
+ fieldPath,
589
+ innerPath,
590
+ kind: "block",
591
+ source: block,
592
+ segments: contents.map((content, chunk) => ({
593
+ customId: createSegmentCustomId(fullPath, chunk),
594
+ content
595
+ })),
596
+ sourceHash: stableHash(JSON.stringify(contents))
597
+ });
598
+ return;
599
+ }
600
+ if (!walkObjects || !isPlainObject(block)) return;
601
+ if (typeof block._type === "string" && context.skipBlockTypes.has(block._type)) return;
602
+ walk(block, [...fieldPath, segment], taskId, context);
603
+ });
604
+ }
605
+ function walk(value, path, taskId, context) {
606
+ if (context.model === "fieldLevel" && isIntlArray(value)) {
607
+ const sourceValue = getIntlItem(value, context.sourceLanguage)?.value;
608
+ if (typeof sourceValue === "string") {
609
+ if (sourceValue.trim() !== "") addTextUnit(context, taskId, path, sourceValue);
610
+ } else if (isPortableTextArray(sourceValue)) {
611
+ addBlockUnits(context, taskId, path, sourceValue, false);
612
+ }
613
+ return;
614
+ }
615
+ if (typeof value === "string") {
616
+ if (context.model === "documentLevel" && isTranslatableString(value)) {
617
+ addTextUnit(context, taskId, path, value);
618
+ }
619
+ return;
620
+ }
621
+ if (Array.isArray(value)) {
622
+ if (context.model === "documentLevel" && isPortableTextArray(value)) {
623
+ addBlockUnits(context, taskId, path, value, true);
624
+ return;
625
+ }
626
+ value.forEach((item, index) => {
627
+ if (isPlainObject(item) && typeof item._type === "string" && context.skipBlockTypes.has(item._type)) {
628
+ return;
629
+ }
630
+ walk(item, [...path, arrayItemSegment(item, index)], taskId, context);
631
+ });
632
+ return;
633
+ }
634
+ if (isPlainObject(value)) {
635
+ if (typeof value._ref === "string") return;
636
+ for (const [name, child] of Object.entries(value)) {
637
+ if (shouldSkipField(name, context)) continue;
638
+ walk(child, [...path, name], taskId, context);
639
+ }
640
+ }
641
+ }
642
+ function isPageBuilderArray(value, context) {
643
+ if (!Array.isArray(value) || value.length === 0) return false;
644
+ if (isPortableTextArray(value)) return false;
645
+ if (context.model === "fieldLevel" && isIntlArray(value)) return false;
646
+ return value.every((item) => isPlainObject(item) && typeof item._key === "string");
647
+ }
648
+ function extractTranslationUnits(document, typeConfig, config) {
649
+ const context = {
650
+ model: typeConfig.model,
651
+ sourceLanguage: config.sourceLanguage.id,
652
+ skipFields: /* @__PURE__ */ new Set([...BUILT_IN_SKIP_FIELDS, ...typeConfig.skipFields ?? []]),
653
+ skipBlockTypes: new Set(config.skipBlockTypes ?? []),
654
+ units: []
655
+ };
656
+ const allowed = typeConfig.fields ? new Set(typeConfig.fields) : void 0;
657
+ for (const [field, value] of Object.entries(document)) {
658
+ if (shouldSkipField(field, context)) continue;
659
+ if (allowed && !allowed.has(field)) continue;
660
+ if (isPageBuilderArray(value, context)) {
661
+ value.forEach((item, index) => {
662
+ const segment = arrayItemSegment(item, index);
663
+ walk(item, [field, segment], createTaskId(field, segment), context);
664
+ });
665
+ continue;
666
+ }
667
+ const isRichText = isPortableTextArray(value) || context.model === "fieldLevel" && isIntlArray(value) && isPortableTextArray(getIntlItem(value, context.sourceLanguage)?.value);
668
+ walk(value, [field], isRichText ? createTaskId(field) : FIELDS_TASK_ID, context);
669
+ }
670
+ return context.units;
671
+ }
672
+
673
+ // src/core/document/slug.ts
674
+ function slugify(title) {
675
+ return title.normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/ß/g, "ss").replace(/[łŁ]/g, "l").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 96).replace(/-+$/, "");
676
+ }
677
+
678
+ // src/server/documents.ts
679
+ var STATE_TYPE = "textunited.translationState";
680
+ function stateDocumentId(baseDocumentId) {
681
+ return `textunited.state.${baseDocumentId}`;
682
+ }
683
+ var SYSTEM_FIELDS = ["_id", "_rev", "_createdAt", "_updatedAt"];
684
+ function withoutSystemFields(document) {
685
+ const copy = cloneValue(document);
686
+ for (const field of SYSTEM_FIELDS) delete copy[field];
687
+ return copy;
688
+ }
689
+ async function loadState(store, baseDocumentId) {
690
+ const document = await store.getDocument(stateDocumentId(baseDocumentId));
691
+ if (!document) return { state: emptyState(), projects: [], archived: [], stopped: [] };
692
+ const revision = typeof document._rev === "string" ? document._rev : void 0;
693
+ let state = emptyState();
694
+ try {
695
+ if (typeof document.stateJson === "string") state = JSON.parse(document.stateJson);
696
+ } catch {
697
+ }
698
+ const { projects, archived, stopped } = readProjects(document);
699
+ if (typeof document.projectsJson !== "string") state = migrateLegacyState(state, projects[0]?.customId);
700
+ return { state, revision, projects, archived, stopped };
701
+ }
702
+ function saveStateMutation(baseDocumentId, stored, pending) {
703
+ const first = stored.projects[0];
704
+ const fields = {
705
+ documentId: baseDocumentId,
706
+ projectsJson: JSON.stringify({ projects: stored.projects, archived: stored.archived, stopped: stored.stopped }),
707
+ projectCustomId: first?.customId,
708
+ projectLanguages: projectLanguages(activeProjects(stored.projects, stored.stopped)),
709
+ projectType: first?.projectType,
710
+ projectId: first?.projectId,
711
+ stateJson: JSON.stringify(stored.state),
712
+ pending,
713
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
714
+ };
715
+ const id = stateDocumentId(baseDocumentId);
716
+ if (stored.revision) return { patch: { id, ifRevisionID: stored.revision, set: fields } };
717
+ return { create: { _id: id, _type: STATE_TYPE, ...fields } };
718
+ }
719
+ async function translationDocumentIds(store, baseDocumentId) {
720
+ const metadata = await store.findTranslationMetadata(baseDocumentId);
721
+ const ids = {};
722
+ const translations = Array.isArray(metadata?.translations) ? metadata.translations : [];
723
+ for (const entry of translations) {
724
+ if (!isPlainObject(entry) || typeof entry._key !== "string") continue;
725
+ const value = entry.value;
726
+ if (isPlainObject(value) && typeof value._ref === "string") ids[entry._key] = value._ref;
727
+ }
728
+ return { metadata, ids };
729
+ }
730
+ async function loadTargets(args) {
731
+ if (args.typeConfig.model === "fieldLevel") {
732
+ return { targets: { model: "fieldLevel", document: cloneValue(args.source) }, metadata: null };
733
+ }
734
+ const baseId = getBaseDocumentId(String(args.source._id));
735
+ const { metadata, ids } = await translationDocumentIds(args.store, baseId);
736
+ const documents = {};
737
+ for (const language of args.languages) {
738
+ const id = ids[language];
739
+ documents[language] = id ? await getPreferredDocument(args.store, id) ?? void 0 : void 0;
740
+ }
741
+ return { targets: { model: "documentLevel", documents }, metadata };
742
+ }
743
+ function createMissingTranslationDocuments(args) {
744
+ if (args.targets.model !== "documentLevel") return [];
745
+ const created = [];
746
+ const languageField = args.typeConfig.languageField ?? "language";
747
+ for (const language of args.languages) {
748
+ if (args.targets.documents[language]) continue;
749
+ const copy = cloneForTranslation(withoutSystemFields(args.source));
750
+ delete copy.slug;
751
+ copy._id = `drafts.${args.newId()}`;
752
+ copy[languageField] = language;
753
+ args.targets.documents[language] = copy;
754
+ created.push(language);
755
+ }
756
+ return created;
757
+ }
758
+ function translationReference(language, documentId, type) {
759
+ return {
760
+ _key: language,
761
+ _type: "internationalizedArrayReferenceValue",
762
+ value: {
763
+ _type: "reference",
764
+ _ref: getBaseDocumentId(documentId),
765
+ _weak: true,
766
+ _strengthenOnPublish: { type }
767
+ }
768
+ };
769
+ }
770
+ function writeTargetsMutations(args) {
771
+ const mutations = [];
772
+ const saveDraft = (document, fields, isNew) => {
773
+ const id = String(document._id);
774
+ const draftId = id.startsWith("drafts.") ? id : `drafts.${id}`;
775
+ if (isNew || !id.startsWith("drafts.")) {
776
+ mutations.push({ createOrReplace: { ...withoutSystemFields(document), _id: draftId } });
777
+ return;
778
+ }
779
+ const set = {};
780
+ for (const field of fields) set[field] = document[field];
781
+ mutations.push({ patch: { id: draftId, set } });
782
+ };
783
+ if (args.targets.model === "fieldLevel") {
784
+ const fields = args.changedFields.get("");
785
+ if (fields?.size) saveDraft(args.targets.document, fields, false);
786
+ return mutations;
787
+ }
788
+ for (const [language, changed] of args.changedFields) {
789
+ let fields = changed;
790
+ const document = args.targets.documents[language];
791
+ if (!document) continue;
792
+ const isNew = args.createdLanguages.includes(language);
793
+ const slug = document.slug;
794
+ if (isNew || !slug || typeof slug.current !== "string" || slug.current === "") {
795
+ const titleField = (args.typeConfig.fields ?? ["title"]).find((field) => typeof document[field] === "string");
796
+ const title = titleField ? String(document[titleField]) : "";
797
+ if (title) {
798
+ document.slug = { _type: "slug", current: slugify(title) };
799
+ fields = /* @__PURE__ */ new Set([...fields, "slug"]);
800
+ }
801
+ }
802
+ saveDraft(document, fields, isNew);
803
+ }
804
+ const createdIds = args.createdLanguages.filter((language) => args.changedFields.has(language)).map((language) => [language, String(args.targets.model === "documentLevel" ? args.targets.documents[language]?._id : "")]);
805
+ if (createdIds.length === 0) return mutations;
806
+ const type = String(args.source._type);
807
+ const sourceRef = translationReference(args.sourceLanguage, String(args.source._id), type);
808
+ const newRefs = createdIds.map(([language, id]) => translationReference(language, id, type));
809
+ const existing = args.loaded.metadata;
810
+ if (!existing) {
811
+ mutations.push({
812
+ create: {
813
+ _id: `translation.metadata.${args.newId()}`,
814
+ _type: "translation.metadata",
815
+ schemaTypes: [type],
816
+ translations: [sourceRef, ...newRefs]
817
+ }
818
+ });
819
+ } else {
820
+ const replaced = new Set(newRefs.map((ref) => ref._key));
821
+ const kept = (Array.isArray(existing.translations) ? existing.translations : []).filter(
822
+ (entry) => !(isPlainObject(entry) && replaced.has(String(entry._key)))
823
+ );
824
+ const keys = new Set(kept.map((entry) => isPlainObject(entry) ? entry._key : void 0));
825
+ const additions = [sourceRef, ...newRefs].filter((ref) => !keys.has(ref._key));
826
+ mutations.push({ patch: { id: String(existing._id), set: { translations: [...kept, ...additions] } } });
827
+ }
828
+ return mutations;
829
+ }
830
+
831
+ export { HttpSanityStore, SanityConflictError, activeProjects, applyBlockTranslation, cloneForTranslation, cloneValue, createMissingTranslationDocuments, createProjectCustomId, decodeHtmlEntities, emptyState, extractTranslationUnits, getAtPath, getBaseDocumentId, getDocumentTypeConfig, getIntlItem, getPreferredDocument, hasPendingTranslations, isMissingValue, isPlainObject, joinTextChunks, loadState, loadTargets, mergeState, migrateLegacyState, planTranslation, projectForLanguage, projectLanguages, readProjects, readTargetValue, recordBaseline, recordSentUnits, saveStateMutation, sentRecord, setAtPath, valueHash, writeTargetsMutations };
832
+ //# sourceMappingURL=chunk-TA5JUFXP.js.map
833
+ //# sourceMappingURL=chunk-TA5JUFXP.js.map