Repository navigation
Expand file tree
/
Copy pathactivity-summary-message.ts
More file actions
705 lines (671 loc) · 31.7 KB
/
Copy pathactivity-summary-message.ts
File metadata and controls
705 lines (671 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#26167] An activity summary in the READER's language.
*
* ## What was wrong
*
* The CRUD mirror (`audit-writers.ts`) composes `sys_activity.summary` once,
* at write time, in the workspace default locale (framework#3039), and the
* object and field labels inside it are translated at that same moment. Every
* reader was then served that one sentence: an English-default workspace
* showed `Created Contract "…"` to a zh-CN reader forever, a workspace that
* switched language kept every older row in the old one, and two colleagues
* with different languages read the same row in one of them.
*
* ## What a row stores now
*
* Beside the sentence, the mirror records the sentence as a CODE: which
* template it is and its parameters ({@link ActivitySummaryMessage}), in the
* row's `metadata` under {@link ACTIVITY_SUMMARY_MESSAGE_KEY}. The object is
* stored by NAME and each field by KEY, so their labels are resolved for each
* reader. A value inside a field-change summary is stored as the text the
* writer rendered (a referenced record's title is the record's own datum, the
* same in every language) plus, for a select value, the option it matched, so
* its option label is resolved for each reader too.
*
* `summary` itself is unchanged: the sentence the writer has always stored,
* for every reader of the column that is not served through the read below.
* The `metadata` slot follows the approvals precedent (the `admin_rescue`
* note's code rides on the request's snapshot), so no column, object schema or
* spec contract moves.
*
* ## Who renders it
*
* {@link installActivitySummaryLocale}: an engine middleware on `sys_activity`
* that, on a read whose `ExecutionContext.locale` is set, re-composes each
* row's `summary` from its stored code in that locale. The locale is the
* door's already-resolved one (the request's `Accept-Language`, else the
* `localization` settings), negotiated against the locales the `i18n` service
* holds by `resolveBundleLocale`, the one negotiation rule; the text is
* `II18nService.t()`. ⛔ Nothing here is a second way to do that: it is the
* sequence `plugin-approvals`'s `reader-locale-labels.ts` uses.
*
* [#35384] The object, field and option LABELS inside the sentence are
* metadata `/meta` serves, so they are not read through `t()`: the reader's
* object definition is put in its language by `translateObject`
* (`@objectstack/spec/system`) over every locale the service holds, with the
* metadata route's `ResolveOptions` (the reader's locale, the DECLARED
* fallback chain, and the authored language — the declared `sourceLocale`,
* else `defaultLocale`), and every label is read off that definition. So a
* reader in a deployment's declared `sourceLocale` reads the labels as
* authored, never the `defaultLocale` row `t()` falls back to; `t()` carries
* the `messages.*` templates. The object's packaged base rides along as
* `packagedBase`, as `/meta` hands it, so a renamed packaged object is named
* by its rename, never by the bundle's translation of its old label.
*
* The writer composes the stored sentence through the SAME function
* ({@link composeActivitySummary}), bound to the write locale, with the English
* catalog as its fallback, so the stored text and a reader's text can never be
* two spellings of one template.
*
* ## What stays as stored
*
* Nothing is re-composed when the read carries no locale, when no `i18n`
* service is registered, when the reader's locale has no template for the code,
* or when composing throws — the stored sentence stands. A row written before
* this change carries no code and is served as written (no migration, no
* backfill).
*
* [#37524] A fired milestone's row carries a code too (`activityMilestone`):
* the milestone's `field` + `value`, the address of its translated template
* (`objects.<object>._milestones.<field>.<value>.summary`,
* `resolveObjectMilestoneSummary`), and each interpolated token's value. A
* reader whose language translates the milestone reads the translated template
* interpolated with those values, a select value named by its option label in
* the reader's language; a reader whose language has no entry reads the
* authored sentence as stored. A tenant that reworded a packaged milestone's
* `summary` keeps its words (ADR-0029 D9.2a), as a reworded validation message
* does.
*/
import {
resolveBundleLocale,
resolveObjectMilestoneSummary,
scalarOverridesPackagedBase,
translateObject,
type ResolveOptions,
type TranslationBundle,
} from '@objectstack/spec/system';
import { enMessages } from './translations/messages.js';
import { ensureJudgedColumnsProjected, isRecord } from './served-fields.js';
/** The `metadata` key a row's summary code rides in. Read and stripped by {@link installActivitySummaryLocale}. */
export const ACTIVITY_SUMMARY_MESSAGE_KEY = 'summary_message';
/**
* One side of a field change: the writer's text, and the option it matched (a
* select value) — or, for a yes/no field that declares no option words, the
* boolean itself, worded per locale by `messages.activityValueTrue` /
* `messages.activityValueFalse`.
*/
export interface ActivitySummaryValue {
text: string;
option?: string;
boolean?: boolean;
}
/** The catalogue key a boolean value is worded by. */
function booleanMessageKey(value: boolean): 'activityValueTrue' | 'activityValueFalse' {
return value ? 'activityValueTrue' : 'activityValueFalse';
}
/** A boolean value in this plugin's ENGLISH catalogue: the writer's text, and every locale's floor. */
export function englishBooleanWord(value: boolean): string {
const word = (enMessages as Record<string, unknown>)[booleanMessageKey(value)];
return typeof word === 'string' ? word : String(value);
}
/** A field change inside a `fieldChanges` summary. */
export interface ActivitySummaryFieldChange {
field: string;
from: ActivitySummaryValue;
to: ActivitySummaryValue;
}
/**
* The code of a summary. `key` names a `messages.*` template of this plugin's
* catalog, except `fieldChanges`, the tracked-change diff (ADR-0052 §5b.1),
* which has no template of its own. `object` is the object's NAME.
*/
export type ActivitySummaryMessage =
| { key: 'activityCreated' | 'activityDeleted' | 'activityUpdated'; object: string; label: string }
| { key: 'activityUpdatedFields'; object: string; label: string; fields: string[]; more: number }
| { key: 'fieldChanges'; object: string; changes: ActivitySummaryFieldChange[] }
| {
key: 'activityMilestone';
object: string;
/** The watched field and the value the milestone fired on — its translation address. */
field: string;
value: string;
/** Each `{token}` the authored template interpolated, by token name. */
tokens: Record<string, ActivitySummaryValue>;
/**
* [#37635] Every `{token}` name the fired template held when the row was
* written, interpolated or not ({@link milestoneTokenNames}). It is what
* tells a token whose value was empty (listed, no entry in `tokens`)
* from one the template gained after the row was written (not listed),
* which this row has no value for: a translation naming such a token
* cannot be composed whole, so the row keeps its stored sentence. A row
* written before #37635 carries no list, so no token missing from
* `tokens` can be told empty, and it keeps its stored sentence whenever
* its translation names one.
*/
names?: string[];
};
/** One language a summary is composed in. */
export interface ActivitySummaryLocale {
/** A bundle key in this locale, interpolated; `undefined` on any miss. */
translate(key: string, params?: Record<string, unknown>): string | undefined;
/** The locale a list is joined in; `undefined` joins in English. */
locale: string | undefined;
/**
* The object's definition its labels are read off, `null` when there is
* none: the authored one for the writer, and [#35384] for a reader the one
* `translateObject` put in the reader's language.
*/
getObjectDef(objectName: string): any;
/**
* [#37524] The translated summary template of the milestone `field` +
* `value` declares on `objectName`, in this locale; `undefined` when the
* locale has none, or the milestone's served `summary` is a tenant's
* rewording of the packaged one. Absent on the writer's locale.
*/
milestoneSummary?(objectName: string, field: string, value: string): string | undefined;
}
/**
* [#7290] The `{token}` pattern of an `activityMilestones` summary template —
* the ONE definition: the writer plans its reads and renders the stored
* sentence with it, and a reader composes a translated template with it.
*
* A FRESH instance per call, deliberately: a module-level `/g` regex carries
* `lastIndex` between callers, and a fired milestone reads this more than
* once. One definition, no shared cursor.
*/
export function milestoneTokenRe(): RegExp {
return /\{(\w+)\}/g;
}
/** [#37635] The distinct `{token}` names of `template`, in the order they first appear. */
export function milestoneTokenNames(template: string): string[] {
return [...new Set(Array.from(template.matchAll(milestoneTokenRe()), (match) => match[1]))];
}
/** Interpolate one `{{param}}` template, the shared convention (`createMemoryI18n`, FileI18nAdapter). */
function interpolate(template: string, params: Record<string, unknown> = {}): string {
return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(params[name] ?? `{{${name}}}`));
}
/**
* `locale` with this plugin's ENGLISH catalog answering every `messages.*`
* key: what the stored sentence falls back to when the write locale has no
* template. Every other key is still asked of `locale`, and the labels are
* still read off `locale`'s definitions ([#35384] never a `t()` key).
*/
export function withEnglishMessages(locale: ActivitySummaryLocale): ActivitySummaryLocale {
return {
translate: (key, params) => {
if (!key.startsWith('messages.')) return locale.translate(key, params);
const template = (enMessages as Record<string, unknown>)[key.slice('messages.'.length)];
return typeof template === 'string' ? interpolate(template, params) : undefined;
},
locale: undefined,
getObjectDef: locale.getObjectDef,
};
}
/**
* An object's label: the definition's ({@link ActivitySummaryLocale.getObjectDef},
* in the reader's language for a reader), then the name.
*/
export function objectLabelIn(locale: ActivitySummaryLocale, objectName: string): string {
const def = locale.getObjectDef(objectName);
return typeof def?.label === 'string' && def.label.length > 0 ? def.label : objectName;
}
/**
* A field's label inside an activity summary: the definition's (in the
* reader's language for a reader), then the machine key. One answer for every
* branch that names a field.
*/
export function fieldLabelForSummary(key: string, field: any): string {
return typeof field?.label === 'string' && field.label.length > 0 ? field.label : key;
}
/** A select value's option label on the definition's field, `undefined` when the field declares none for it. */
function optionLabelOn(field: any, option: string): string | undefined {
const options: unknown = field?.options;
if (!Array.isArray(options)) return undefined;
for (const candidate of options) {
if (candidate && typeof candidate === 'object' && String((candidate as { value?: unknown }).value) === option) {
const label = (candidate as { label?: unknown }).label;
return typeof label === 'string' && label.length > 0 ? label : undefined;
}
}
return undefined;
}
/** A locale's conjunction list ("A, B, and C" / "A、B和C"); `", "` where `Intl` cannot answer. */
export function listJoinerFor(locale: string | undefined): (items: string[]) => string {
// `Intl.ListFormat` is ES2021; this package compiles against the ES2020 lib,
// so the constructor is probed rather than assumed (as `plugin-auth`'s
// invitation role label does).
const ListFormat = (Intl as unknown as { ListFormat?: IntlListFormatConstructor }).ListFormat;
try {
if (ListFormat) {
const format = new ListFormat(locale ?? 'en', { type: 'conjunction' });
return (items) => format.format(items);
}
} catch {
// A tag `Intl` refuses (a tenant's own locale spelling) still gets a list.
}
return (items) => items.join(', ');
}
type IntlListFormatConstructor = new (
locale: string,
options: { type: 'conjunction' },
) => { format(list: readonly string[]): string };
/**
* The summary `message` reads as in `locale`, or `undefined` when that locale
* has no template for it. A locale whose bundle answers only the field-less
* `activityUpdated` (an app's own locale, written before the named-field
* template existed) gets that localized frame for a named-field code, never an
* English one with its field names.
*/
export function composeActivitySummary(
message: ActivitySummaryMessage,
locale: ActivitySummaryLocale,
): string | undefined {
const { translate } = locale;
switch (message.key) {
case 'activityCreated':
case 'activityDeleted':
case 'activityUpdated':
return translate(`messages.${message.key}`, {
object: objectLabelIn(locale, message.object),
label: message.label,
});
case 'activityUpdatedFields': {
const frame = { object: objectLabelIn(locale, message.object), label: message.label };
if (translate('messages.activityUpdatedFields', { ...frame, fields: '' }) === undefined) {
return translate('messages.activityUpdated', frame);
}
const fields = locale.getObjectDef(message.object)?.fields;
const items = message.fields.map((key) => fieldLabelForSummary(key, fields?.[key]));
if (message.more > 0) {
items.push(
translate('messages.activityMoreFields', { count: message.more }) ??
interpolate(enMessages.activityMoreFields as string, { count: message.more }),
);
}
return translate('messages.activityUpdatedFields', { ...frame, fields: listJoinerFor(locale.locale)(items) });
}
case 'fieldChanges': {
const fields = locale.getObjectDef(message.object)?.fields;
const valueIn = (field: string, value: ActivitySummaryValue): string =>
value.option !== undefined
? (optionLabelOn(fields?.[field], value.option) ?? value.text)
: typeof value.boolean === 'boolean'
? (translate(`messages.${booleanMessageKey(value.boolean)}`) ?? value.text)
: value.text;
return message.changes
.map(
(c) =>
`${fieldLabelForSummary(c.field, fields?.[c.field])}: ` +
`${valueIn(c.field, c.from)} → ${valueIn(c.field, c.to)}`,
)
.join('; ');
}
case 'activityMilestone': {
const template = locale.milestoneSummary?.(message.object, message.field, message.value);
if (template === undefined) return undefined;
const fields = locale.getObjectDef(message.object)?.fields;
// The tokens with a stored value render it. A token the fired template
// held whose value was empty renders empty, as it does in the stored
// sentence. [#37635] Any other token (one the template gained after
// the row was written, or one only the translation names) has no value
// this row could give it, so the row keeps its stored sentence rather
// than show a hole where that sentence has none.
const written = new Set(message.names ?? []);
let whole = true;
const text = template.replace(milestoneTokenRe(), (_match: string, token: string) => {
const value = Object.prototype.hasOwnProperty.call(message.tokens, token) ? message.tokens[token] : undefined;
if (!value) {
if (!written.has(token)) whole = false;
return '';
}
return value.option !== undefined ? (optionLabelOn(fields?.[token], value.option) ?? value.text) : value.text;
});
return whole ? text : undefined;
}
}
}
/** The stored sentence for `message`: the write locale's, else the English catalog's. */
export function composeStoredSummary(message: ActivitySummaryMessage, locale: ActivitySummaryLocale): string {
return composeActivitySummary(message, locale) ?? composeActivitySummary(message, withEnglishMessages(locale)) ?? '';
}
const SINGLE_TEMPLATE_KEYS: ReadonlySet<string> = new Set(['activityCreated', 'activityDeleted', 'activityUpdated']);
const isStringList = (v: unknown): v is string[] => Array.isArray(v) && v.every((s) => typeof s === 'string');
const isValue = (v: unknown): v is ActivitySummaryValue =>
isRecord(v) &&
typeof v.text === 'string' &&
(v.option === undefined || typeof v.option === 'string') &&
(v.boolean === undefined || typeof v.boolean === 'boolean');
/** A stored code, or `null` for anything this version cannot compose (it then stays as stored). */
export function readActivitySummaryMessage(value: unknown): ActivitySummaryMessage | null {
if (!isRecord(value) || typeof value.key !== 'string' || typeof value.object !== 'string') return null;
if (SINGLE_TEMPLATE_KEYS.has(value.key)) {
return typeof value.label === 'string' ? (value as ActivitySummaryMessage) : null;
}
if (value.key === 'activityUpdatedFields') {
return typeof value.label === 'string' && isStringList(value.fields) && typeof value.more === 'number'
? (value as ActivitySummaryMessage)
: null;
}
if (value.key === 'activityMilestone') {
const tokens = value.tokens;
return typeof value.field === 'string' &&
typeof value.value === 'string' &&
isRecord(tokens) &&
Object.values(tokens).every(isValue) &&
(value.names === undefined || isStringList(value.names))
? (value as ActivitySummaryMessage)
: null;
}
if (value.key === 'fieldChanges') {
const changes = value.changes;
return Array.isArray(changes) &&
changes.every((c) => isRecord(c) && typeof c.field === 'string' && isValue(c.from) && isValue(c.to))
? (value as ActivitySummaryMessage)
: null;
}
return null;
}
/**
* The slice of `II18nService` a read asks: `t()`, `getLocales()` to negotiate
* when offered, and [#35384] the members the labels are resolved by, as the
* metadata route reads them.
*/
export interface ActivitySummaryI18n {
t(key: string, locale: string, params?: Record<string, unknown>): string;
getLocales?(): unknown;
getTranslations?(locale: string): unknown;
getFallbackLocale?(): string | undefined;
getSourceLocale?(): string | undefined;
getDefaultLocale?(): string;
}
/**
* [#35384] What the metadata route (`GET /meta/object/:name`) translates an
* object definition with, for a request in `locale`: the bundle — every locale
* `service` holds, keyed by locale (`translationBundleOf` in rest) — and the
* `ResolveOptions` that route builds (`metaTranslateOptions` in rest): the
* request's locale, the DECLARED fallback chain (`getFallbackLocale()`), and
* the authored language — the declared `sourceLocale` (`getSourceLocale()`),
* else `defaultLocale` (`getDefaultLocale()`). Each getter is
* feature-detected; a service that declares none gets none. The locale is
* the negotiated one, as objectql's refusal labels hand `translateObject`.
*
* `undefined` — the authored labels stand — for a service that cannot hand its
* translations over (no `getLocales` / `getTranslations`). A throwing service
* is the caller's to survive.
*/
function labelTranslationOf(
service: ActivitySummaryI18n,
locale: string,
): { bundle: TranslationBundle | undefined; options: ResolveOptions } | undefined {
if (typeof service.getLocales !== 'function' || typeof service.getTranslations !== 'function') return undefined;
const locales = service.getLocales();
if (!Array.isArray(locales)) return undefined;
const bundle: Record<string, unknown> = {};
for (const code of locales) {
if (typeof code !== 'string' || code.length === 0) continue;
const data = service.getTranslations(code);
if (data && typeof data === 'object') bundle[code] = data;
}
const fallback = typeof service.getFallbackLocale === 'function' ? service.getFallbackLocale() : undefined;
const source = typeof service.getSourceLocale === 'function' ? service.getSourceLocale() : undefined;
const authored = typeof source === 'string' && source.length > 0
? source
: typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined;
const options: ResolveOptions = {
locale,
...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}),
...(typeof authored === 'string' && authored.length > 0 ? { defaultLocale: authored } : {}),
};
return { bundle: Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined, options };
}
/**
* The locale `service` can ANSWER in, for the locale the reader asked for:
* `resolveBundleLocale` over what `getLocales()` reports. The requested tag
* passes through untouched when there is nothing to negotiate against.
*/
function negotiatedLocale(service: ActivitySummaryI18n, requested: string): string {
if (typeof service.getLocales !== 'function') return requested;
let available: unknown;
try {
available = service.getLocales();
} catch {
return requested;
}
if (!Array.isArray(available) || available.length === 0) return requested;
const offered: Record<string, true> = {};
for (const code of available) {
if (typeof code === 'string' && code.length > 0) offered[code] = true;
}
return resolveBundleLocale(offered, requested) ?? requested;
}
/**
* The language a reader whose `ExecutionContext.locale` is `requested` reads
* in, or `undefined` when this read can compose nothing: no locale, or no
* service with a `t()`.
*
* [#35384] Its `getObjectDef` answers the definition `translateObject` put in
* the reader's language ({@link labelTranslationOf}), built once per object
* for the read; the authored definition when there is nothing to translate
* with, or the translator throws. `getPackagedObjectBase` answers the object's
* packaged base, handed to the translator as `packagedBase`, as `/meta` hands
* it ({@link packagedObjectBaseReader}); absent, or answering nothing, no
* baseline is known and the catalog applies.
*/
export function readerSummaryLocale(
service: ActivitySummaryI18n | undefined,
requested: unknown,
getObjectDef: (objectName: string) => any,
getPackagedObjectBase?: (objectName: string) => unknown,
): ActivitySummaryLocale | undefined {
if (typeof requested !== 'string' || requested.length === 0) return undefined;
if (!service || typeof service.t !== 'function') return undefined;
const locale = negotiatedLocale(service, requested);
let translation: { value: ReturnType<typeof labelTranslationOf> } | undefined;
const definitions = new Map<string, any>();
// [#37635] One answer per milestone for the read: a feed page holds many
// rows of the same milestone, and each answer walks the authored and the
// packaged definitions.
const milestoneTemplates = new Map<string, string | undefined>();
// The packaged base, read once per object for the read: the translated
// definition and every milestone answer ask it.
const packagedBases = new Map<string, unknown>();
const packagedBaseOf = (objectName: string): unknown => {
if (!packagedBases.has(objectName)) packagedBases.set(objectName, getPackagedObjectBase?.(objectName));
return packagedBases.get(objectName);
};
const translatedObjectDef = (objectName: string): any => {
if (definitions.has(objectName)) return definitions.get(objectName);
const def = getObjectDef(objectName);
let served = def;
if (def && typeof def === 'object') {
try {
translation ??= { value: labelTranslationOf(service, locale) };
if (translation.value) {
const packagedBase = packagedBaseOf(objectName);
served = translateObject({ ...def, name: objectName }, translation.value.bundle, {
...translation.value.options,
...(packagedBase && typeof packagedBase === 'object' ? { packagedBase } : {}),
});
}
} catch {
// A misbehaving i18n service must not fail the read: the authored labels stand.
}
}
definitions.set(objectName, served);
return served;
};
return {
translate: (key, params) => {
try {
const text = service.t(key, locale, params);
// `II18nService.t` echoes the key back on a miss.
return typeof text === 'string' && text.length > 0 && text !== key ? text : undefined;
} catch {
// A misbehaving i18n service must not fail the read: the stored text stands.
return undefined;
}
},
locale,
getObjectDef: translatedObjectDef,
milestoneSummary: (objectName, field, value) => {
// NUL cannot occur in an object, field or value name, so the key is unambiguous.
const cacheKey = `${objectName}\u0000${field}\u0000${value}`;
if (milestoneTemplates.has(cacheKey)) return milestoneTemplates.get(cacheKey);
let template: string | undefined;
try {
translation ??= { value: labelTranslationOf(service, locale) };
if (translation.value) {
// ADR-0029 D9.2a: a tenant's rewording of a packaged milestone is
// authored data and keeps its words, judged as a validation message
// is — the served milestone against the packaged one of the same pair,
// through the resolver's one predicate (never a copy of it).
const served = milestoneOn(getObjectDef(objectName), field, value);
const packaged = milestoneOn(packagedBaseOf(objectName), field, value);
if (!scalarOverridesPackagedBase(packaged, 'summary', served?.summary)) {
template = resolveObjectMilestoneSummary(
translation.value.bundle,
objectName,
field,
value,
translation.value.options,
);
}
}
} catch {
// A misbehaving i18n service must not fail the read: the stored text stands.
template = undefined;
}
milestoneTemplates.set(cacheKey, template);
return template;
},
};
}
/** [#37524] The first milestone `def` declares for `field` + `value` — the one that fires, as the writer matches. */
function milestoneOn(def: unknown, field: string, value: string): Record<string, unknown> | undefined {
const milestones = isRecord(def) ? def.activityMilestones : undefined;
if (!Array.isArray(milestones)) return undefined;
for (const m of milestones) {
if (isRecord(m) && m.field === field && String(m.value) === value) return m;
}
return undefined;
}
/** Parse a stored `metadata` value: a JSON object, or `null` for anything else. */
function parseMetadata(raw: unknown): Record<string, unknown> | null {
if (isRecord(raw)) return raw;
if (typeof raw !== 'string' || raw.trim() === '') return null;
try {
const value = JSON.parse(raw);
return isRecord(value) ? value : null;
} catch {
return null;
}
}
/**
* Overlay `row.summary` with its stored code composed in `locale`, in place,
* and — for a caller who is not the system — drop the code from the served
* `metadata`: its parameters are parent field values (the record label, a
* changed value), and the field redaction judges the text columns, not this
* slot. A row whose `summary` the projection did not ask for is not given one.
*
* [#36290] One code is served: a field-change code (`fieldChanges`), which the
* field redaction has already narrowed change by change for this reader
* (`activity-field-redaction.ts`), so the record page can draw one line per
* changed field. This middleware is registered OUTSIDE the redaction for that
* reason: it composes from the narrowed code, never from the stored one.
*/
export function localizeActivityRow(
row: Record<string, unknown>,
locale: ActivitySummaryLocale | undefined,
stripCode: boolean,
): void {
const metadata = parseMetadata(row.metadata);
if (!metadata || !(ACTIVITY_SUMMARY_MESSAGE_KEY in metadata)) return;
if (locale && 'summary' in row) {
const message = readActivitySummaryMessage(metadata[ACTIVITY_SUMMARY_MESSAGE_KEY]);
if (message) {
try {
const text = composeActivitySummary(message, locale);
if (text) row.summary = text;
} catch {
// Composing must never fail the read: the stored sentence stands.
}
}
}
if (stripCode && !isFieldChangeCode(metadata[ACTIVITY_SUMMARY_MESSAGE_KEY])) {
delete metadata[ACTIVITY_SUMMARY_MESSAGE_KEY];
row.metadata = isRecord(row.metadata) ? metadata : JSON.stringify(metadata);
}
}
/** [#36290] A code this version reads as a field-change summary — the one code served to a reader. */
function isFieldChangeCode(value: unknown): boolean {
return readActivitySummaryMessage(value)?.key === 'fieldChanges';
}
/** The engine slice the summary middleware registers on. */
export interface ActivitySummaryEngine {
registerMiddleware?(
fn: (ctx: any, next: () => Promise<void>) => Promise<void>,
options?: { object?: string },
): void;
getSchema?(objectName: string): unknown;
/** [#35384] The schema registry, read for an object's packaged base ({@link packagedObjectBaseReader}). */
registry?: unknown;
}
/**
* [#35384] An object's packaged (code-layer) declaration, off `engine`'s
* schema registry (`registry.getPackagedObjectBase(name)`): the body the
* metadata protocol's `getPackagedObjectBase` reads (`engine.registry`), the
* accessor `/meta` hands `translateObject` as `packagedBase` through
* (`packagedObjectBaseOf` in rest). `undefined` — no baseline known — for a
* registry without the accessor, or one that throws.
*/
function packagedObjectBaseReader(engine: ActivitySummaryEngine): (objectName: string) => unknown {
return (objectName) => {
const registry = engine.registry as { getPackagedObjectBase?: (name: string) => unknown } | undefined;
if (!registry || typeof registry.getPackagedObjectBase !== 'function') return undefined;
try {
return registry.getPackagedObjectBase(objectName);
} catch {
return undefined;
}
};
}
/**
* Install the `sys_activity` summary middleware. `getI18n` is resolved on every
* read: the i18n service may register after this plugin. Register it BEFORE the
* field redaction (`installActivityFieldRedaction`), so the redaction runs
* inside it [#36290]: the redaction judges the stored text by its declared
* sources and narrows the field-change code first, and this middleware then
* composes a kept summary in the reader's language from what the redaction
* left — a narrowed code composes only the changes this reader is served.
*/
export function installActivitySummaryLocale(
engine: ActivitySummaryEngine,
getI18n: () => ActivitySummaryI18n | undefined,
): void {
if (typeof engine.registerMiddleware !== 'function') return;
const getObjectDef = (objectName: string): any => {
try {
return typeof engine.getSchema === 'function' ? engine.getSchema(objectName) : null;
} catch {
return null;
}
};
const getPackagedObjectBase = packagedObjectBaseReader(engine);
engine.registerMiddleware(
async (ctx, next) => {
if (ctx.operation !== 'find' && ctx.operation !== 'findOne') return next();
const added = ensureJudgedColumnsProjected(ctx.ast, ['summary'], ['metadata']);
await next();
const list = (Array.isArray(ctx.result) ? ctx.result : ctx.result ? [ctx.result] : []) as unknown[];
const locale = readerSummaryLocale(getI18n(), ctx.context?.locale, getObjectDef, getPackagedObjectBase);
const stripCode = !!ctx.context && !ctx.context.isSystem;
for (const row of list) {
if (!isRecord(row)) continue;
localizeActivityRow(row, locale, stripCode);
for (const col of added) delete row[col];
}
},
{ object: 'sys_activity' },
);
}