@startsimpli/integrations 0.2.218 → 0.2.219

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.218",
3
+ "version": "0.2.219",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.208",
54
53
  "@startsimpli/utils": "^0.4.21",
55
- "@startsimpli/auth": "^0.4.62"
54
+ "@startsimpli/auth": "^0.4.62",
55
+ "@startsimpli/ui": "^0.4.208"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -2,9 +2,8 @@
2
2
  * THE CLIENT CORPUS FOR TRANSLATION — glossary and translation memory
3
3
  * (bd startsim-ppfl RED / bd startsim-364c GREEN).
4
4
  *
5
- * CONTRACT AND STUBS ONLY. Every function throws `NotImplementedError`, so the
6
- * tests in `../__tests__/translation-corpus.test.ts` fail on missing BEHAVIOUR
7
- * rather than on a missing module.
5
+ * Pure functions over the generic `TenantEntity` envelope. The behaviour is
6
+ * pinned by `../__tests__/translation-corpus.test.ts`.
8
7
  *
9
8
  * ── WHY THIS LIVES IN THE CORPUS PACKAGE ───────────────────────────────────
10
9
  * `startsim-3o4e` decides the whole mechanism is glossary + translation-memory
@@ -34,6 +33,8 @@
34
33
  * DOCUMENT. So every read here is scope-partitioned and every drop is counted.
35
34
  */
36
35
 
36
+ import { enforceScope, isInScope } from './retrieval';
37
+ import { jaccard, tokenize, words } from './text';
37
38
  import type { CorpusPage, CorpusScope, SourceDocument } from './types';
38
39
 
39
40
  /**
@@ -108,13 +109,6 @@ export interface TenantEntityWrite {
108
109
  data: Record<string, unknown>;
109
110
  }
110
111
 
111
- export class NotImplementedError extends Error {
112
- constructor(what: string) {
113
- super(`${what} is not implemented (bd startsim-ppfl is RED; bd startsim-364c implements it)`);
114
- this.name = 'NotImplementedError';
115
- }
116
- }
117
-
118
112
  // ---------------------------------------------------------------------------
119
113
  // ingestion
120
114
  // ---------------------------------------------------------------------------
@@ -132,10 +126,25 @@ export interface IngestOptions {
132
126
  * mapper in this package.
133
127
  */
134
128
  export function ingestForTranslation(
135
- _document: SourceDocument,
136
- _options: IngestOptions,
129
+ document: SourceDocument,
130
+ options: IngestOptions,
137
131
  ): TenantEntityWrite[] {
138
- throw new NotImplementedError('ingestForTranslation');
132
+ const typeKeys = options.typeKeys ?? TRANSLATION_TYPE_KEYS;
133
+ return [
134
+ {
135
+ entity_type: typeKeys.sourceDocument,
136
+ external_id: `translation:document:${document.id}`,
137
+ name: document.title || document.id,
138
+ data: {
139
+ body: document.body,
140
+ summary: document.summary ?? '',
141
+ source: document.source,
142
+ source_ref: document.sourceRef,
143
+ occurred_at: document.occurredAt,
144
+ org_id: options.scope.orgId,
145
+ },
146
+ },
147
+ ];
139
148
  }
140
149
 
141
150
  // ---------------------------------------------------------------------------
@@ -160,18 +169,74 @@ export interface ExtractTermsOptions {
160
169
  * module that produces an `approved` term without a human verdict.
161
170
  */
162
171
  export function extractTermCandidates(
163
- _documents: readonly SourceDocument[],
164
- _options: ExtractTermsOptions,
172
+ documents: readonly SourceDocument[],
173
+ options: ExtractTermsOptions,
165
174
  ): GlossaryTermRecord[] {
166
- throw new NotImplementedError('extractTermCandidates');
175
+ const minOccurrences = options.minOccurrences ?? 2;
176
+ const maxCandidates = options.maxCandidates ?? 50;
177
+ const ruledOn = new Set(
178
+ (options.known ?? [])
179
+ .filter((t) => t.sourceLocale === options.sourceLocale && t.targetLocale === options.targetLocale)
180
+ .map((t) => t.sourceTerm.toLowerCase()),
181
+ );
182
+
183
+ const counts = new Map<string, { occurrences: number; documentIds: Set<string> }>();
184
+ for (const document of documents) {
185
+ if (!isInScope(document, options.scope)) continue; // the same guard as every other read
186
+ for (const chunk of phraseChunks(document.body)) {
187
+ for (let size = 2; size <= 3; size += 1) {
188
+ for (let at = 0; at + size <= chunk.length; at += 1) {
189
+ const phrase = chunk.slice(at, at + size).join(' ');
190
+ const entry = counts.get(phrase) ?? { occurrences: 0, documentIds: new Set<string>() };
191
+ entry.occurrences += 1;
192
+ entry.documentIds.add(document.id);
193
+ counts.set(phrase, entry);
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ const frequent = [...counts.entries()].filter(
200
+ ([phrase, entry]) => entry.occurrences >= minOccurrences && !ruledOn.has(phrase),
201
+ );
202
+ // "settlement agreement" inside "settlement agreement signed" at the same count is one term, not two.
203
+ const kept = frequent.filter(
204
+ ([phrase, entry]) =>
205
+ !frequent.some(
206
+ ([other, o]) => other !== phrase && o.occurrences === entry.occurrences && ` ${other} `.includes(` ${phrase} `) && other.length > phrase.length,
207
+ ),
208
+ );
209
+
210
+ return kept
211
+ .sort((a, b) => b[1].occurrences - a[1].occurrences || a[0].localeCompare(b[0]))
212
+ .slice(0, maxCandidates)
213
+ .map(([phrase, entry]) => ({
214
+ id: `term:${options.sourceLocale}:${options.targetLocale}:${phrase.replace(/\s+/g, '-')}`,
215
+ sourceLocale: options.sourceLocale,
216
+ targetLocale: options.targetLocale,
217
+ sourceTerm: phrase,
218
+ targetTerm: '',
219
+ status: 'candidate' as const,
220
+ occurrences: entry.occurrences,
221
+ documentIds: [...entry.documentIds],
222
+ scope: options.scope,
223
+ }));
167
224
  }
168
225
 
169
226
  /** Record a human's verdict. The ONLY route from `candidate` to `approved`. */
170
227
  export function applyTermVerdict(
171
- _term: GlossaryTermRecord,
172
- _verdict: { status: 'approved' | 'rejected'; targetTerm?: string; doNotTranslate?: boolean },
228
+ term: GlossaryTermRecord,
229
+ verdict: { status: 'approved' | 'rejected'; targetTerm?: string; doNotTranslate?: boolean },
173
230
  ): GlossaryTermRecord {
174
- throw new NotImplementedError('applyTermVerdict');
231
+ if (verdict.status === 'rejected') {
232
+ return { ...term, status: 'rejected' };
233
+ }
234
+ const doNotTranslate = verdict.doNotTranslate ?? term.doNotTranslate ?? false;
235
+ const targetTerm = doNotTranslate ? term.sourceTerm : (verdict.targetTerm ?? '').trim();
236
+ if (!targetTerm) {
237
+ throw new Error(`Approving "${term.sourceTerm}" needs a target term, or doNotTranslate`);
238
+ }
239
+ return { ...term, status: 'approved', targetTerm, doNotTranslate };
175
240
  }
176
241
 
177
242
  // ---------------------------------------------------------------------------
@@ -185,10 +250,17 @@ export function applyTermVerdict(
185
250
  * page, not the glossary) and status (so a candidate never reaches a model).
186
251
  */
187
252
  export function glossaryForSegment(
188
- _segmentText: string,
189
- _terms: readonly GlossaryTermRecord[],
253
+ segmentText: string,
254
+ terms: readonly GlossaryTermRecord[],
190
255
  ): GlossaryTermRecord[] {
191
- throw new NotImplementedError('glossaryForSegment');
256
+ const haystack = normalizeForMemory(segmentText);
257
+ return terms.filter((t) => {
258
+ if (t.status !== 'approved') return false;
259
+ const needle = normalizeForMemory(t.sourceTerm);
260
+ if (!needle) return false;
261
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(needle)}(?![\\p{L}\\p{N}])`, 'u');
262
+ return pattern.test(haystack);
263
+ });
192
264
  }
193
265
 
194
266
  // ---------------------------------------------------------------------------
@@ -200,8 +272,13 @@ export function glossaryForSegment(
200
272
  * bidi isolates stripped. A MATERIAL change — a different word, a different
201
273
  * number — must survive normalisation and defeat the match.
202
274
  */
203
- export function normalizeForMemory(_text: string): string {
204
- throw new NotImplementedError('normalizeForMemory');
275
+ export function normalizeForMemory(text: string): string {
276
+ return (text ?? '')
277
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')
278
+ .normalize('NFKC')
279
+ .replace(/\s+/g, ' ')
280
+ .trim()
281
+ .toLowerCase();
205
282
  }
206
283
 
207
284
  export interface MemoryLookupOptions {
@@ -212,11 +289,14 @@ export interface MemoryLookupOptions {
212
289
 
213
290
  /** An exact hit, or null. Costs nothing and makes no provider call. */
214
291
  export function exactMemoryHit(
215
- _segmentText: string,
216
- _units: readonly MemoryUnitRecord[],
217
- _options: MemoryLookupOptions,
292
+ segmentText: string,
293
+ units: readonly MemoryUnitRecord[],
294
+ options: MemoryLookupOptions,
218
295
  ): MemoryUnitRecord | null {
219
- throw new NotImplementedError('exactMemoryHit');
296
+ const wanted = normalizeForMemory(segmentText);
297
+ return (
298
+ servable(units, options).find((u) => u.sourceHash === wanted || normalizeForMemory(u.sourceText) === wanted) ?? null
299
+ );
220
300
  }
221
301
 
222
302
  export interface FuzzyMatch {
@@ -232,11 +312,17 @@ export interface FuzzyOptions extends MemoryLookupOptions {
232
312
 
233
313
  /** Neighbours, best first, capped. Offered to the model as EXAMPLES, never as answers. */
234
314
  export function fuzzyMemoryMatches(
235
- _segmentText: string,
236
- _units: readonly MemoryUnitRecord[],
237
- _options: FuzzyOptions,
315
+ segmentText: string,
316
+ units: readonly MemoryUnitRecord[],
317
+ options: FuzzyOptions,
238
318
  ): FuzzyMatch[] {
239
- throw new NotImplementedError('fuzzyMemoryMatches');
319
+ const query = tokenize(segmentText);
320
+ const minScore = options.minScore ?? 0.3;
321
+ return servable(units, options)
322
+ .map((unit) => ({ unit, score: jaccard(query, tokenize(unit.sourceText)) }))
323
+ .filter((m) => m.score >= minScore)
324
+ .sort((a, b) => b.score - a.score || a.unit.id.localeCompare(b.unit.id))
325
+ .slice(0, options.limit ?? 3);
240
326
  }
241
327
 
242
328
  /**
@@ -246,15 +332,27 @@ export function fuzzyMemoryMatches(
246
332
  * which is exactly the upkeep trap that makes people abandon tools."
247
333
  */
248
334
  export function memoryUnitFromReviewerEdit(
249
- _edit: {
335
+ edit: {
250
336
  sourceText: string;
251
337
  editedTargetText: string;
252
338
  sourceLocale: string;
253
339
  targetLocale: string;
254
340
  },
255
- _scope: CorpusScope,
341
+ scope: CorpusScope,
256
342
  ): MemoryUnitRecord {
257
- throw new NotImplementedError('memoryUnitFromReviewerEdit');
343
+ if (!edit.editedTargetText.trim()) throw new Error('A reviewer edit with no text is not memory');
344
+ const sourceHash = normalizeForMemory(edit.sourceText);
345
+ return {
346
+ id: `memory:${edit.sourceLocale}:${edit.targetLocale}:${sourceHash}`,
347
+ sourceLocale: edit.sourceLocale,
348
+ targetLocale: edit.targetLocale,
349
+ sourceText: edit.sourceText,
350
+ targetText: edit.editedTargetText,
351
+ sourceHash,
352
+ origin: 'reviewer_edit',
353
+ approved: true,
354
+ scope,
355
+ };
258
356
  }
259
357
 
260
358
  // ---------------------------------------------------------------------------
@@ -275,17 +373,19 @@ export interface ScopedRead<T> {
275
373
  * it should not have, the OUTPUT must still not contain it.
276
374
  */
277
375
  export function scopedTerms(
278
- _terms: readonly GlossaryTermRecord[],
279
- _scope: CorpusScope,
376
+ terms: readonly GlossaryTermRecord[],
377
+ scope: CorpusScope,
280
378
  ): ScopedRead<GlossaryTermRecord> {
281
- throw new NotImplementedError('scopedTerms');
379
+ const { kept, dropped } = enforceScope([...terms], scope);
380
+ return { kept, droppedOutOfScope: dropped.length };
282
381
  }
283
382
 
284
383
  export function scopedMemory(
285
- _units: readonly MemoryUnitRecord[],
286
- _scope: CorpusScope,
384
+ units: readonly MemoryUnitRecord[],
385
+ scope: CorpusScope,
287
386
  ): ScopedRead<MemoryUnitRecord> {
288
- throw new NotImplementedError('scopedMemory');
387
+ const { kept, dropped } = enforceScope([...units], scope);
388
+ return { kept, droppedOutOfScope: dropped.length };
289
389
  }
290
390
 
291
391
  // ---------------------------------------------------------------------------
@@ -312,10 +412,60 @@ export interface TranslationCorpusApi {
312
412
  }): Promise<CorpusPage<MemoryUnitRecord>>;
313
413
  }
314
414
 
315
- export function readAllGlossaryTerms(
316
- _api: TranslationCorpusApi,
317
- _scope: CorpusScope,
318
- _options?: { maxPages?: number },
415
+ export async function readAllGlossaryTerms(
416
+ api: TranslationCorpusApi,
417
+ scope: CorpusScope,
418
+ options?: { maxPages?: number },
319
419
  ): Promise<ScopedRead<GlossaryTermRecord>> {
320
- throw new NotImplementedError('readAllGlossaryTerms');
420
+ const maxPages = options?.maxPages ?? 50;
421
+ const all: GlossaryTermRecord[] = [];
422
+ for (let page = 1; ; page += 1) {
423
+ if (page > maxPages) {
424
+ throw new Error(`Glossary has more than ${maxPages} pages; refusing to return a truncated read`);
425
+ }
426
+ const read = await api.listGlossaryTerms({ page });
427
+ all.push(...read.results);
428
+ if (!read.next) break;
429
+ }
430
+ return scopedTerms(all, scope);
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // helpers
435
+ // ---------------------------------------------------------------------------
436
+
437
+ function escapeRegExp(value: string): string {
438
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
439
+ }
440
+
441
+ /**
442
+ * Runs of adjacent content words, broken at punctuation and at stopwords, so a
443
+ * phrase never spans a clause boundary or a "the".
444
+ */
445
+ function phraseChunks(text: string): string[][] {
446
+ const chunks: string[][] = [];
447
+ for (const clause of (text ?? '').toLowerCase().split(/[.!?;:,()\n]+/)) {
448
+ let run: string[] = [];
449
+ for (const token of clause.match(/[a-z0-9][a-z0-9'&\-/]*/g) ?? []) {
450
+ const [content] = words(token);
451
+ if (content) run.push(content);
452
+ else if (run.length) {
453
+ chunks.push(run);
454
+ run = [];
455
+ }
456
+ }
457
+ if (run.length) chunks.push(run);
458
+ }
459
+ return chunks;
460
+ }
461
+
462
+ /** Approved, in scope, and the right language pair: the only units memory may serve. */
463
+ function servable(units: readonly MemoryUnitRecord[], options: MemoryLookupOptions): MemoryUnitRecord[] {
464
+ return units.filter(
465
+ (u) =>
466
+ u.approved &&
467
+ u.sourceLocale === options.sourceLocale &&
468
+ u.targetLocale === options.targetLocale &&
469
+ isInScope(u, options.scope),
470
+ );
321
471
  }