@braze/sanity-plugin-ai-translation 0.2.7 → 0.2.22

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.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { ArrayDefinition } from "sanity";
2
2
  import { FieldDefinitionBase } from "sanity";
3
3
  import { Plugin as Plugin_2 } from "sanity";
4
- import type { SanityDocument } from "sanity";
5
4
  import { WidenInitialValue } from "sanity";
6
5
  import { WidenValidation } from "sanity";
7
6
 
@@ -13,289 +12,13 @@ import { WidenValidation } from "sanity";
13
12
  */
14
13
  export declare const aiTranslationPlugin: Plugin_2<PluginConfig>;
15
14
 
16
- /**
17
- * Type-erased version of FieldTransform for use in collections.
18
- * Uses `any` to allow variance - this is necessary because function parameters
19
- * are contravariant, and using `unknown` would prevent assigning specific
20
- * transforms like `FieldTransform<VTTCaption[], TranslatableVTT>` to the array.
21
- *
22
- * This type is used internally by the plugin for storing transforms
23
- * in arrays and registries where the specific types aren't known.
24
- *
25
- * @public
26
- *
27
- * @example Usage in plugin config
28
- * ```typescript
29
- * const config: PluginConfig = {
30
- * // ... other config
31
- * fieldTransforms: [
32
- * vttTransform, // FieldTransform<VTTCaption[], TranslatableVTT>
33
- * richTextTransform, // FieldTransform<PortableTextBlock[], TranslatableRichText>
34
- * customTransform, // FieldTransform<CustomType, TranslatableCustom>
35
- * ] // All coerced to AnyFieldTransform[]
36
- * }
37
- * ```
38
- */
39
- export declare type AnyFieldTransform = FieldTransform<any, any>;
40
-
41
- /**
42
- * Common enum field names that are typically excluded from translation
43
- * @internal
44
- */
45
- export declare const COMMON_ENUM_FIELDS: readonly [
46
- "status",
47
- "state",
48
- "type",
49
- "category",
50
- "priority",
51
- "visibility",
52
- "role",
53
- "permission",
54
- "level",
55
- "mode",
56
- "format",
57
- "variant",
58
- "size",
59
- "theme",
60
- "kind",
61
- "phase",
62
- "stage",
63
- ];
64
-
65
- /**
66
- * Criteria for matching fields that should be transformed.
67
- * @public
68
- * @typeParam TOriginal - Type of the original field value
69
- */
70
- export declare interface FieldMatcher<TOriginal = unknown> {
71
- /**
72
- * Schema type name to match (e.g., 'video')
73
- */
74
- schemaType?: string;
75
- /**
76
- * Field name to match (e.g., 'captions')
77
- */
78
- fieldName?: string;
79
- /**
80
- * Full field path pattern to match (e.g., 'captions[].text' or RegExp)
81
- */
82
- fieldPath?: string | RegExp;
83
- /**
84
- * Optional function to match based on field value.
85
- * This is called after other matcher criteria pass (or if no other criteria specified).
86
- * Useful for detecting field types by examining their content (e.g., Portable Text detection).
87
- * @param value - The field value to examine
88
- * @param context - Transform context with field path, schema type, and document
89
- * @returns true if this field should be transformed, false otherwise
90
- */
91
- valueMatcher?: (value: TOriginal, context: TransformContext) => boolean;
92
- }
93
-
94
- /**
95
- * Transform definition for custom field handling.
96
- *
97
- * Transforms allow you to convert complex field values to simpler formats
98
- * for translation, then restore the original structure after translation.
99
- *
100
- * @public
101
- * @typeParam TOriginal - Type of the original field value
102
- * @typeParam TTranslatable - Type of the translatable format (what gets sent to translation)
103
- *
104
- * @example Creating a type-safe transform for video captions
105
- * ```typescript
106
- * interface VTTCaption {
107
- * startTime: number;
108
- * endTime: number;
109
- * text: string;
110
- * }
111
- *
112
- * interface TranslatableCaption {
113
- * _type: 'translatable.vtt';
114
- * vtt: string;
115
- * }
116
- *
117
- * const vttTransform: FieldTransform<VTTCaption[], TranslatableCaption> = {
118
- * matcher: {
119
- * schemaType: 'video',
120
- * fieldName: 'captions',
121
- * },
122
- * toTranslatable: (captions) => ({
123
- * _type: 'translatable.vtt',
124
- * vtt: captions.map(c => `${c.startTime} --> ${c.endTime}\n${c.text}`).join('\n\n')
125
- * }),
126
- * fromTranslatable: (translated, original) => {
127
- * // Parse VTT and restore original structure with translated text
128
- * const lines = translated.vtt.split('\n\n');
129
- * return original.map((caption, i) => ({
130
- * ...caption,
131
- * text: lines[i]?.split('\n')[1] || caption.text
132
- * }));
133
- * }
134
- * };
135
- * ```
136
- */
137
- export declare interface FieldTransform<
138
- TOriginal = unknown,
139
- TTranslatable = unknown,
140
- > {
141
- /**
142
- * Criteria for matching fields that should be transformed
143
- */
144
- matcher: FieldMatcher<TOriginal>;
145
- /**
146
- * Transform complex field value to translatable format.
147
- * This method is called before translation to simplify the field structure.
148
- *
149
- * @param value - Original field value (typed as TOriginal)
150
- * @param context - Transform context with field path, schema type, and document
151
- * @returns Transformed value for translation (typed as TTranslatable)
152
- *
153
- * @example
154
- * ```typescript
155
- * toTranslatable: (value: CustomField[], context) => {
156
- * return {
157
- * _type: 'translatable.custom',
158
- * text: value.map(item => item.content).join('\n'),
159
- * _metadata: value.map(item => ({ id: item.id }))
160
- * };
161
- * }
162
- * ```
163
- */
164
- toTranslatable: (
165
- value: TOriginal,
166
- context: TransformContext,
167
- ) => TTranslatable;
168
- /**
169
- * Transform translated value back to original format.
170
- * This method is called after translation to restore the original structure
171
- * while preserving the translated content.
172
- *
173
- * @param value - Translated value (typed as TTranslatable)
174
- * @param originalValue - Original value before translation (typed as TOriginal)
175
- * @param context - Transform context with field path, schema type, and document
176
- * @returns Restored value with translated content (must match TOriginal type)
177
- *
178
- * @example
179
- * ```typescript
180
- * fromTranslatable: (translated: TranslatableCustom, original: CustomField[], context) => {
181
- * const translatedLines = translated.text.split('\n');
182
- * return original.map((item, index) => ({
183
- * ...item, // Preserve original structure and metadata
184
- * content: translatedLines[index] || item.content // Apply translated text
185
- * }));
186
- * }
187
- * ```
188
- */
189
- fromTranslatable: (
190
- value: TTranslatable,
191
- originalValue: TOriginal,
192
- context: TransformContext,
193
- ) => TOriginal;
194
- }
195
-
196
- /**
197
- * Result of filtering excluded fields from a document
198
- * @internal
199
- */
200
- export declare interface FilteredDocument<T = any> {
201
- /** Document with excluded fields removed */
202
- filteredDocument: T;
203
- /** Excluded field values that were removed */
204
- excludedValues: Record<string, any>;
205
- }
206
-
207
- /**
208
- * Recursively filters out excluded fields from a document
209
- * @param document - The document to filter
210
- * @param excludeFields - Array of field patterns to exclude. Supports:
211
- * - Field names: 'status' (matches any field named 'status' anywhere)
212
- * - Exact paths: 'meta.category' (matches only 'category' under 'meta')
213
- * - Array paths: 'body[0].imageType' (matches 'imageType' in first array item)
214
- * - Wildcard arrays: 'body[*].imageType' (matches 'imageType' in any array item)
215
- * - Hierarchical: '**.status' (explicitly matches 'status' anywhere - same as just 'status')
216
- * @param currentPath - Current path in the document (used internally)
217
- * @returns Filtered document and excluded values
218
- * @internal
219
- */
220
- export declare function filterExcludedFields<T extends Record<string, any>>(
221
- document: T,
222
- excludeFields?: string[],
223
- currentPath?: string,
224
- ): FilteredDocument<T>;
225
-
226
- /**
227
- * Helper type to infer the original type from a FieldTransform.
228
- * Useful for type checking and creating wrapper functions.
229
- *
230
- * @public
231
- * @typeParam T - The FieldTransform type to extract from
232
- *
233
- * @example
234
- * ```typescript
235
- * const myTransform: FieldTransform<MyType, TranslatableType> = { ... };
236
- *
237
- * // Inferred type will be MyType
238
- * type OriginalType = InferOriginalType<typeof myTransform>;
239
- *
240
- * // Use in function signature
241
- * function processOriginal(value: InferOriginalType<typeof myTransform>) {
242
- * // value is typed as MyType
243
- * }
244
- * ```
245
- */
246
- export declare type InferOriginalType<T> =
247
- T extends FieldTransform<infer O, unknown> ? O : never;
248
-
249
- /**
250
- * Helper type to infer the translatable type from a FieldTransform.
251
- * Useful for type checking intermediate translation formats.
252
- *
253
- * @public
254
- * @typeParam T - The FieldTransform type to extract from
255
- *
256
- * @example
257
- * ```typescript
258
- * const myTransform: FieldTransform<MyType, TranslatableType> = { ... };
259
- *
260
- * // Inferred type will be TranslatableType
261
- * type TransType = InferTranslatableType<typeof myTransform>;
262
- *
263
- * // Use in function signature
264
- * function processTranslatable(value: InferTranslatableType<typeof myTransform>) {
265
- * // value is typed as TranslatableType
266
- * }
267
- * ```
268
- */
269
- export declare type InferTranslatableType<T> =
270
- T extends FieldTransform<unknown, infer R> ? R : never;
271
-
272
- /**
273
- * Event emitted when an OpenAI API call is made
274
- * @public
275
- */
276
- declare interface OpenAIApiCallEvent extends TelemetryEventBase {
277
- name: "openai.api_call";
278
- data: {
279
- model: string;
280
- tokensUsed: {
281
- prompt: number;
282
- completion: number;
283
- reasoning: number;
284
- total: number;
285
- cached: number;
286
- };
287
- cost: number;
288
- durationMs: number;
289
- };
290
- }
291
-
292
15
  /**
293
16
  *
294
17
  * Configuration for the Sanity AI Translation plugin.
295
18
  * @public
296
19
  *
297
20
  */
298
- export declare interface PluginConfig {
21
+ declare interface PluginConfig {
299
22
  supportedLanguages: Array<{
300
23
  id: string;
301
24
  title: string;
@@ -307,346 +30,14 @@ export declare interface PluginConfig {
307
30
  maxReferenceDepth?: number;
308
31
  openai?: {
309
32
  apiKey: string;
310
- model?:
311
- | "gpt-5.1"
312
- | "gpt-5"
313
- | "gpt-5-mini"
314
- | "gpt-5-nano"
315
- | "gpt-5-pro"
316
- | "gpt-4o"
317
- | "gpt-4-turbo"
318
- | "gpt-4";
319
- reasoningEffort?: "low" | "medium" | "high";
33
+ model?: "gpt-5" | "gpt-4o" | "gpt-4-turbo" | "gpt-4";
34
+ reasoningEffort?: "minimal" | "low" | "medium" | "high";
35
+ verbosity?: "low" | "medium" | "high";
320
36
  enabled?: boolean;
321
37
  defaultMode?: TranslationMode;
322
38
  };
323
- fieldTransforms?: AnyFieldTransform[];
324
- /**
325
- * Fields to exclude from translation. These fields will be preserved as-is in the translated document.
326
- * Supports field names (e.g., 'status') and nested field paths (e.g., 'meta.category').
327
- * Useful for enum fields, IDs, technical values, and other non-translatable content.
328
- *
329
- * @example
330
- * ```typescript
331
- * excludeFields: ['status', 'category', 'type', 'meta.priority', 'config.mode']
332
- * ```
333
- */
334
- excludeFields?: string[];
335
- /**
336
- * Optional telemetry configuration for monitoring translation operations.
337
- * Provides callbacks for lightweight events and detailed error bundles.
338
- *
339
- * @example
340
- * ```typescript
341
- * telemetry: {
342
- * onEvent: (event) => datadogRum.addAction(event.name, event.data),
343
- * onError: (bundle) => datadogLogs.logger.error('Translation failed', bundle)
344
- * }
345
- * ```
346
- */
347
- telemetry?: TelemetryConfig;
348
39
  }
349
40
 
350
- /**
351
- * Predefined exclusion lists for common use cases
352
- * @internal
353
- */
354
- export declare const PREDEFINED_EXCLUSIONS: {
355
- /** Common enum and status fields */
356
- readonly enums: readonly [
357
- "status",
358
- "state",
359
- "type",
360
- "category",
361
- "priority",
362
- "visibility",
363
- "role",
364
- "permission",
365
- "level",
366
- "mode",
367
- "format",
368
- "variant",
369
- "size",
370
- "theme",
371
- "kind",
372
- "phase",
373
- "stage",
374
- ];
375
- /** All metadata and system fields (starting with _) */
376
- readonly metadata: readonly [
377
- "_id",
378
- "_type",
379
- "_rev",
380
- "_createdAt",
381
- "_updatedAt",
382
- ];
383
- /** Common technical and configuration fields */
384
- readonly technical: readonly [
385
- "slug",
386
- "handle",
387
- "key",
388
- "code",
389
- "id",
390
- "uuid",
391
- "token",
392
- "hash",
393
- "checksum",
394
- "version",
395
- "config",
396
- "settings",
397
- ];
398
- /** SEO and URL-related fields that often shouldn't be translated */
399
- readonly seo: readonly [
400
- "slug",
401
- "handle",
402
- "permalink",
403
- "canonical",
404
- "redirect",
405
- "robots",
406
- "sitemap",
407
- ];
408
- };
409
-
410
- declare type ReleaseSelectionMode = "new" | "existing";
411
-
412
- /**
413
- * Restores previously excluded fields to a translated document
414
- * @param translatedDocument - The translated document
415
- * @param excludedValues - The excluded field values to restore
416
- * @returns Document with excluded fields restored
417
- * @internal
418
- */
419
- export declare function restoreExcludedFields<T extends Record<string, any>>(
420
- translatedDocument: T,
421
- excludedValues: Record<string, any>,
422
- ): T;
423
-
424
- /**
425
- * Transform for handling Portable Text (rich text) content using XML-like serialization.
426
- * This leverages the existing serialization utilities to convert complex rich text
427
- * to a format that's easier for translation models to process.
428
- *
429
- * Uses value-based detection to identify Portable Text arrays (checking for _type === 'block').
430
- * The fieldPath pattern is used as a performance optimization to avoid checking every field,
431
- * but the valueMatcher is the definitive check.
432
- *
433
- * @public
434
- */
435
- export declare const richTextTransform: FieldTransform<
436
- unknown[],
437
- TranslatableRichText
438
- >;
439
-
440
- /**
441
- * Configuration for telemetry/monitoring integration.
442
- * Both callbacks are optional - configure based on your monitoring needs.
443
- * @public
444
- *
445
- * @example Basic Datadog RUM integration
446
- * ```typescript
447
- * telemetry: {
448
- * onEvent: (event) => datadogRum.addAction(event.name, event.data),
449
- * onError: (bundle) => datadogRum.addError(new Error(bundle.error.message), {
450
- * documentId: bundle.documentId,
451
- * errorType: bundle.error.type,
452
- * })
453
- * }
454
- * ```
455
- */
456
- declare interface TelemetryConfig {
457
- /**
458
- * Lightweight event callback - called for all translation events.
459
- * Keep payloads small (IDs, counts, durations, costs).
460
- * @param event - The telemetry event with name and data
461
- */
462
- onEvent?: (event: TelemetryEvent) => void;
463
- /**
464
- * Error callback with full debug bundle - only called on failures.
465
- * Consumer decides how to handle (send to Datadog, store locally, truncate, etc.)
466
- * @param bundle - Full debug context for troubleshooting
467
- */
468
- onError?: (bundle: TranslationErrorBundle) => void;
469
- }
470
-
471
- /**
472
- * Union of all telemetry event types
473
- * @public
474
- */
475
- declare type TelemetryEvent =
476
- | TranslationBatchStartedEvent
477
- | TranslationBatchCompletedEvent
478
- | TranslationJobCompletedEvent
479
- | OpenAIApiCallEvent;
480
-
481
- /**
482
- * Base interface for all telemetry events
483
- * @public
484
- */
485
- declare interface TelemetryEventBase {
486
- name: string;
487
- timestamp: string;
488
- }
489
-
490
- /**
491
- * Context passed to transform functions.
492
- * @public
493
- */
494
- export declare interface TransformContext {
495
- /**
496
- * Current field path
497
- */
498
- fieldPath: string;
499
- /**
500
- * Document schema type
501
- */
502
- schemaType: string;
503
- /**
504
- * Full document being processed
505
- */
506
- document: TranslatableDocument;
507
- }
508
-
509
- declare interface TranslatableDocument extends SanityDocument {
510
- language: string;
511
- }
512
-
513
- /**
514
- * Special type to track transformed rich text content.
515
- * This separates the serialized XML content from regular strings
516
- * so the main serialization can handle it correctly.
517
- */
518
- declare interface TranslatableRichText {
519
- _type: "translatable.richtext";
520
- translationText: string;
521
- _originalValue: unknown[];
522
- }
523
-
524
- /**
525
- * Special type to track transformed VTT captions.
526
- * This combines metadata separation for token efficiency with XML format for translation.
527
- */
528
- declare interface TranslatableVTTCaptions {
529
- _type: "translatable.vtt.captions";
530
- translationText: string;
531
- _originalMetadata: VTTCaptionMetadata[];
532
- }
533
-
534
- /**
535
- * Special type to track transformed Wistia captions.
536
- * This combines metadata separation for token efficiency with compact text format for translation.
537
- */
538
- declare interface TranslatableWistiaCaptions {
539
- _type: "translatable.wistia.captions";
540
- translationText: string;
541
- _originalMetadata: WistiaCaptionsMetadata;
542
- _srtCues: Array<{
543
- index: number;
544
- startTime: string;
545
- endTime: string;
546
- }>;
547
- }
548
-
549
- /**
550
- * Event emitted when a translation batch completes
551
- * @public
552
- */
553
- declare interface TranslationBatchCompletedEvent extends TelemetryEventBase {
554
- name: "translation.batch_completed";
555
- data: {
556
- documentId: string;
557
- documentType: string;
558
- sourceLanguage: string;
559
- targetLanguages: string[];
560
- translationMode: TranslationMode;
561
- succeeded: number;
562
- failed: number;
563
- skipped: number;
564
- durationMs: number;
565
- };
566
- }
567
-
568
- /**
569
- * Event emitted when a translation batch starts
570
- * @public
571
- */
572
- declare interface TranslationBatchStartedEvent extends TelemetryEventBase {
573
- name: "translation.batch_started";
574
- data: {
575
- documentId: string;
576
- documentType: string;
577
- sourceLanguage: string;
578
- targetLanguages: string[];
579
- translationMode: TranslationMode;
580
- referenceCount: number;
581
- releaseMode: ReleaseSelectionMode;
582
- };
583
- }
584
-
585
- /**
586
- * Debug bundle containing full context for troubleshooting translation failures.
587
- * This is only emitted when a translation fails.
588
- * @public
589
- */
590
- declare interface TranslationErrorBundle {
591
- /** Document ID being translated */
592
- documentId: string;
593
- /** Document schema type */
594
- documentType: string;
595
- /** Target language for translation */
596
- targetLanguage: string;
597
- /** Source language of the document */
598
- sourceLanguage: string;
599
- /** Translation mode used */
600
- translationMode: TranslationMode;
601
- /** Error details */
602
- error: {
603
- /** Error message */
604
- message: string;
605
- /** Error stack trace if available */
606
- stack?: string;
607
- /** Categorized error type for filtering/alerting */
608
- type: TranslationErrorType;
609
- };
610
- /**
611
- * Debug data for troubleshooting.
612
- * Can be large - consumer decides how to handle (truncate, store locally, etc.)
613
- */
614
- debug: {
615
- /** Full source document */
616
- originalDocument: SanityDocument;
617
- /** XML-serialized document sent to OpenAI (if OpenAI mode) */
618
- serializedDocument?: string;
619
- /** Raw API response from OpenAI (if OpenAI mode) */
620
- openaiResponse?: string;
621
- /** Translation prompts used */
622
- translationPrompts?: {
623
- globalPrompt?: string;
624
- localePrompt?: string;
625
- protectedPhrases?: string[];
626
- glossaryTerms?: any[];
627
- };
628
- /** Validation errors if structure validation failed */
629
- validationErrors?: any[];
630
- };
631
- /** ISO timestamp when error occurred */
632
- timestamp: string;
633
- /** Duration of the translation attempt in milliseconds */
634
- durationMs: number;
635
- }
636
-
637
- /**
638
- * Error types for categorizing translation failures
639
- * @public
640
- */
641
- declare type TranslationErrorType =
642
- | "serialization"
643
- | "deserialization"
644
- | "openai_api"
645
- | "validation"
646
- | "sanity_agent"
647
- | "network"
648
- | "unknown";
649
-
650
41
  /**
651
42
  * Schema for translation history
652
43
  *
@@ -660,96 +51,9 @@ export declare const translationHistorySchema: {
660
51
  WidenValidation &
661
52
  WidenInitialValue;
662
53
 
663
- /**
664
- * Event emitted when an individual translation job completes successfully
665
- * @public
666
- */
667
- declare interface TranslationJobCompletedEvent extends TelemetryEventBase {
668
- name: "translation.job_completed";
669
- data: {
670
- documentId: string;
671
- documentType: string;
672
- sourceLanguage: string;
673
- targetLanguage: string;
674
- translationMode: TranslationMode;
675
- durationMs: number;
676
- tokensUsed?: number;
677
- estimatedCost?: number;
678
- };
679
- }
680
-
681
- declare type TranslationMode = "sanity-only" | "openai-only";
682
-
683
- /**
684
- * Represents a VTT caption cue with timing and text content.
685
- */
686
- declare interface VTTCaption {
687
- _key?: string;
688
- _type?: string;
689
- text?: string;
690
- startTime?: number;
691
- endTime?: number;
692
- [key: string]: string | number | undefined;
693
- }
694
-
695
- /**
696
- * VTT caption metadata without text content, used for preservation during translation.
697
- */
698
- declare interface VTTCaptionMetadata {
699
- _key?: string;
700
- _type?: string;
701
- startTime?: number;
702
- endTime?: number;
703
- _originalIndex: number;
704
- [key: string]: string | number | undefined;
705
- }
706
-
707
- /**
708
- * Transform for handling VTT captions in video documents using a hybrid approach.
709
- * This stores metadata separately for token efficiency while formatting
710
- * text content as XML for better translation results.
711
- *
712
- * @public
713
- */
714
- export declare const vttCaptionTransform: FieldTransform<
715
- VTTCaption[],
716
- TranslatableVTTCaptions
717
- >;
718
-
719
- /**
720
- * Represents a Wistia captions object with SRT content and metadata.
721
- */
722
- declare interface WistiaCaptions {
723
- captionContent?: string;
724
- captionFileName?: string;
725
- isoLanguage?: string;
726
- captionUploadStatus?: string;
727
- captionUploadMessage?: string;
728
- [key: string]: string | undefined;
729
- }
730
-
731
- /**
732
- * Wistia captions metadata without captionContent, used for preservation during translation.
733
- */
734
- declare interface WistiaCaptionsMetadata {
735
- captionFileName?: string;
736
- isoLanguage?: string;
737
- captionUploadStatus?: string;
738
- captionUploadMessage?: string;
739
- _originalIndex: number;
740
- [key: string]: string | number | undefined;
741
- }
742
-
743
- /**
744
- * Transform for handling Wistia captions in documents using SRT format.
745
- * This stores metadata separately for token efficiency while formatting
746
- * text content in a compact indexed format for better translation results.
747
- *
748
- * @public
749
- */
750
- export declare const wistiaCaptionTransform: FieldTransform<
751
- WistiaCaptions,
752
- TranslatableWistiaCaptions
753
- >;
54
+ declare type TranslationMode =
55
+ | "sanity-only"
56
+ | "openai-only"
57
+ | "sanity-with-review";
754
58
 
755
59
  export {};