Repository navigation
Expand file tree
/
Copy pathrule-message-render.ts
More file actions
252 lines (238 loc) · 12.3 KB
/
Copy pathrule-message-render.ts
File metadata and controls
252 lines (238 loc) · 12.3 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
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#37909, ruling P3, parameters 5–8] Fill the `{{ }}` holes of a validation
* rule's message — or of the translation of it a refusal shows — with the
* judged record's values.
*
* The message is an ADR-0032 §3 template over two roots,
* `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS` (`@objectstack/spec/data`):
* `record`, the merged record the rule judged, and `previous`, the stored row
* before an update (`null` on an insert, so a `previous.FIELD` hole renders
* empty there). The doors (`objectstack validate` / `compile`, the publish
* gate) judge every message and every translation as that template; this
* module renders it, through the formula template engine (`templateEngine`) —
* ⛔ never a second engine — with the formatters that engine whitelists and
* nothing implicit: a value renders as the engine renders it (`null` and an
* absent value as nothing), and a formatter makes the rest explicit.
*
* ## What a hole may show (parameter 6, the human floor)
*
* A hole names one of the object's own fields, one segment deep, and shows its
* value only when that field is in {@link RuleMessageRendering.showable}: the
* fields the person the refusal is worded for may read, unmasked (the engine
* computes the set once per write, `engine-rule-message-rendering.ts`). Every
* other hole renders empty: a field that person cannot read, a field masked
* for them, a credential or internal field, a field the object does not
* declare, a read through a field (`{{ record.account.name }}`), a bare root
* and a hole over any other root. With no {@link RuleMessageRendering} at all,
* every hole renders empty. The scope the engine evaluates over holds the
* showable values only, so a hole is empty twice over: blanked before the
* render, and absent from its scope.
*
* What the deployment is told, through {@link RuleMessageRendering.warn}: a
* hole no reader could ever see filled — over another root, a bare root, a
* read through a field, a field the object does not declare: a message stored
* before the doors judged it — is named with its rule, so it can be rewritten.
* A hole empty only for this reader (a field they cannot read, or see masked)
* is ⛔ never reported: that is the floor working, not a fault. When the field
* security could not be asked at all ({@link RuleMessageRendering.unanswered}),
* the cause is written once.
*
* The verdict never depends on this: the rule was judged before its message is
* rendered, and the rendered sentence is the violation's `message` alone —
* ⛔ no value is written into the envelope's machine fields.
*
* ## When a template does not render
*
* A message carrying no `{{` is returned as written, exactly as before. A
* template that does not compile (a message stored before the doors judged it:
* a hole holding logic, an unknown formatter, unbalanced delimiters) does not
* render; {@link renderRuleMessage} says so, and the caller decides (a
* translation falls back to the authored message, an authored message that
* does not render is shown as written, as it was). A template that passes the
* doors always renders: see {@link tenantCurrencyHole} for the one hole the
* doors accept whose value depends on the deployment.
*/
import { currencyDefaultRefusal, templateEngine } from '@objectstack/formula';
import { VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS } from '@objectstack/spec/data';
/** What a rule message's holes may show and format with — computed by the engine once per write. */
export interface RuleMessageRendering {
/**
* The fields of the object a hole may show the value of: the fields the
* person the refusal is worded for may read, unmasked, less every
* credential and internal field. A hole over any other field renders empty.
*/
readonly showable: ReadonlySet<string>;
/**
* The fields the object declares. A hole over a field outside it is one no
* reader could see filled, and {@link warn} names it; without this set, no
* hole is reported for its field.
*/
readonly declared?: ReadonlySet<string>;
/**
* Why no field is showable on this write, when the field security could not
* be asked (no security service, one that does not answer, the grants of the
* person an elevated write was made for unreadable). Written to {@link warn}
* when a hole renders empty for it.
*/
readonly unanswered?: string;
/**
* The tenant default currency (`ExecutionContext.currency`, the organization's
* `localization.currency`) a `currency` hole with no argument formats in;
* `undefined` when the organization has none.
*/
readonly currency?: string;
/** The reference timezone a `datetime` hole renders in (`ExecutionContext.timezone`). */
readonly timezone?: string;
/**
* Where a message that does not render as authored is reported (the write's
* logger; the engine writes each distinct line once per write).
*/
readonly warn?: (message: string) => void;
}
/** The values a rule message's holes read: the record the rule judged, and the stored row before it. */
export interface RuleMessageValues {
/** The merged record the rule judged (the prior row overlaid with the write). */
readonly record: Record<string, unknown>;
/** The stored row before an update; `null` on an insert, `undefined` when not in hand. */
readonly previous: Record<string, unknown> | null | undefined;
}
/** A rendered message, or why the template did not render. */
export type RuleMessageRender = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly reason: string };
/** Every `{{ … }}` hole — the template engine's `HOLE_RE`. */
const HOLE = /\{\{([^}]*)\}\}/g;
/** A hole's path — the template engine's `PATH_ONLY_RE`; a hole that fails it is left to the compile. */
const HOLE_PATH = /^[\w$.[\]]+$/;
const ROOTS: ReadonlySet<string> = new Set(VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS);
/** Whether `text` carries a `{{` — the only messages this module renders. */
export function carriesTemplateHole(text: unknown): text is string {
return typeof text === 'string' && text.includes('{{');
}
/** The values of `row` a hole may show: the showable fields it carries, in a container with no prototype. */
function showableValues(row: Record<string, unknown> | null | undefined, showable: ReadonlySet<string>): Record<string, unknown> | undefined {
if (row === null || row === undefined || typeof row !== 'object') return undefined;
const out: Record<string, unknown> = Object.create(null);
for (const field of showable) {
if (Object.prototype.hasOwnProperty.call(row, field)) out[field] = row[field];
}
return out;
}
/**
* [Parameter 8 — the fork, pending the maintainer's ruling] A `currency` hole
* with no argument formats in the tenant default currency, and the doors
* accept it whatever the deployment. With no tenant default the engine refuses
* the whole sentence (`currencyDefaultRefusal`), so a template that passed the
* doors would not render. Provisionally (option A of the fork put to the
* maintainer), the hole renders empty, as a hole over a field the caller cannot
* read does, and the deployment is told which setting fills it; ⛔ the amount
* is never formatted in a currency nobody chose, nor shown unformatted.
*/
function tenantCurrencyHole(hole: string, subject: string, warn: ((message: string) => void) | undefined): string {
warn?.(
`${subject}: the hole ${hole} formats in the tenant default currency, and none reached this write (the `
+ 'organization has none set, or the write carried none): the hole renders empty. Set the default currency '
+ 'in Setup → Company Settings → Language & Region (`localization.currency`), or name the currency in the '
+ 'hole (`currency:EUR`).',
);
return '';
}
/**
* Why a hole can never show a value, whoever reads it, or `undefined` when it
* can: the doors refuse each of these, so only a message stored before them
* carries one.
*/
function structuralBlank(segments: readonly string[], declared: ReadonlySet<string> | undefined): string | undefined {
const [root, field] = segments;
if (root === undefined || !ROOTS.has(root)) {
return `reads \`${root ?? ''}\`, which is not a root a rule message reads (${[...ROOTS].map((r) => `\`${r}\``).join(', ')})`;
}
if (field === undefined) return `names the root \`${root}\` alone, not one of its fields`;
if (segments.length > 2) return 'reads through a field; a hole reads one of the object\'s own fields, one segment deep';
if (declared !== undefined && !declared.has(field)) return `names \`${field}\`, which the object does not declare`;
return undefined;
}
/**
* The template with every hole that may not show a value blanked (see the
* module header). A hole that does not parse as a path is left as written,
* for the compile to refuse.
*/
function blankUnshowableHoles(
template: string,
values: RuleMessageValues,
rendering: RuleMessageRendering | undefined,
subject: string,
): string {
return template.replace(HOLE, (hole, inner: string) => {
const bar = inner.indexOf('|');
const path = (bar === -1 ? inner : inner.slice(0, bar)).trim();
// Not a path: the compile names it, and the template does not render.
if (!HOLE_PATH.test(path)) return hole;
const segments = path.replace(/\[(\w+)\]/g, '.$1').split('.').filter((segment) => segment !== '');
if (rendering === undefined) return '';
const structural = structuralBlank(segments, rendering.declared);
if (structural !== undefined) {
rendering.warn?.(`${subject}: the hole ${hole} ${structural}, so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`);
return '';
}
const [root, field] = segments as [string, string];
if (!rendering.showable.has(field)) {
// Empty for this reader only: the floor, reported only when the field
// security could not be asked at all.
if (rendering.unanswered !== undefined) {
rendering.warn?.(`rule message holes render empty on this write: ${rendering.unanswered}.`);
}
return '';
}
if (root === 'previous' && (values.previous === null || values.previous === undefined)) return '';
if (bar !== -1) {
const formatter = inner.slice(bar + 1).trim();
const colon = formatter.indexOf(':');
const name = (colon === -1 ? formatter : formatter.slice(0, colon)).trim();
if (name === 'currency' && colon === -1 && currencyDefaultRefusal(hole, rendering.currency) !== null) {
return tenantCurrencyHole(hole, subject, rendering.warn);
}
}
return hole;
});
}
/**
* Render one rule message (or one translation of it) over the judged record.
*
* A message carrying no `{{` comes back as written. Otherwise each hole that
* may not show a value is blanked, and the rest render through the template
* engine in `locale` (the refusal's negotiated locale) over the showable
* values of `values.record` and `values.previous`. `subject` names the
* message in what {@link RuleMessageRendering.warn} is told (the rule, its
* object, and which translation).
*/
export function renderRuleMessage(
template: string,
values: RuleMessageValues,
rendering: RuleMessageRendering | undefined,
locale: string | undefined,
subject = 'a validation rule message',
): RuleMessageRender {
if (!carriesTemplateHole(template)) return { ok: true, text: template };
const source = blankUnshowableHoles(template, values, rendering, subject);
const showable = rendering?.showable ?? new Set<string>();
const record = showableValues(values.record, showable);
const previous = showableValues(values.previous, showable);
try {
const result = templateEngine.evaluate<string>(
{ dialect: 'template', source },
{
...(record !== undefined ? { record } : {}),
...(previous !== undefined ? { previous } : {}),
...(locale ? { locale } : {}),
...(rendering?.currency ? { currency: rendering.currency } : {}),
...(rendering?.timezone ? { timezone: rendering.timezone } : {}),
},
);
if (!result.ok) return { ok: false, reason: result.error.message };
return { ok: true, text: String(result.value) };
} catch (error) {
// A formatter refuses by throwing (`currency:eur`); the doors refuse every
// such hole, so only a message stored before them meets this.
return { ok: false, reason: error instanceof Error ? error.message : String(error) };
}
}