@shing.wong/sure-factor 0.2.1 → 0.3.2

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,565 @@
1
+ /**
2
+ * Client-target generation.
3
+ *
4
+ * `generateForTier` emits a server stack: Handlebars, htmx, express. The
5
+ * management console is a client-side SPA and consumes none of that — it needs
6
+ * DOM-building code. This module emits a self-contained ES module that renders
7
+ * a FormSpec into real elements, so the generated class names stay tied to the
8
+ * `cssClasses` contract in `catalog/components/*.yaml`.
9
+ *
10
+ * Deliberately framework-free: no React, no runtime dependency. The output is
11
+ * an `h()`-based renderer plus a typed spec contract the caller fills from its
12
+ * own server.
13
+ */
14
+ import { readFileSync } from 'fs';
15
+ import { matchColumnToTypeSync, loadAllTypesSync } from './match.js';
16
+ import { parseYaml } from './parse-yaml.js';
17
+ import { uniqueKey } from './generate-internal.js';
18
+ function loadComponent(name) {
19
+ if (!/^[a-zA-Z0-9_-]+$/.test(name))
20
+ return null;
21
+ try {
22
+ const text = readFileSync(new URL(`../catalog/components/${name}.yaml`, import.meta.url), 'utf-8');
23
+ return parseYaml(text);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ function inputTypeForColumn(col) {
30
+ const dt = col.dataType.toLowerCase();
31
+ if (dt === 'boolean')
32
+ return 'checkbox';
33
+ if (dt === 'date' || dt === 'timestamp' || dt === 'timestamptz')
34
+ return 'date';
35
+ if (['integer', 'bigint', 'smallint', 'serial', 'bigserial', 'numeric', 'decimal', 'real', 'double'].includes(dt))
36
+ return 'number';
37
+ return 'text';
38
+ }
39
+ function controlFor(col, type) {
40
+ if (type.name === 'password')
41
+ return 'password';
42
+ if (/^(jsonb?|json)$/i.test(col.dataType))
43
+ return 'textarea';
44
+ if (inputTypeForColumn(col) === 'checkbox')
45
+ return 'text';
46
+ return 'text';
47
+ }
48
+ /**
49
+ * Derive the field specs the client renderer consumes. Keyed by table+column
50
+ * for the same reason as the server target: a bare column name collides across
51
+ * tables and silently drops validation.
52
+ */
53
+ export function buildClientFields(schema, options, component) {
54
+ const allTypes = loadAllTypesSync();
55
+ const seen = new Map();
56
+ const out = [];
57
+ for (const table of schema.tables) {
58
+ for (const column of table.columns) {
59
+ const matched = matchColumnToTypeSync(column, allTypes, options.tier);
60
+ if (!matched)
61
+ continue;
62
+ const type = matched.type;
63
+ const tierConfig = type.tiers?.[options.tier];
64
+ if (!tierConfig)
65
+ continue;
66
+ const key = uniqueKey(seen, table.tableName, column.columnName);
67
+ const validation = type.validation ?? {};
68
+ const hints = type.hints?.en ?? {};
69
+ const spec = {
70
+ name: key,
71
+ label: column.columnName.replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase()),
72
+ control: controlFor(column, type),
73
+ type: type.name,
74
+ required: !column.isNullable,
75
+ readOnly: column.isPrimaryKey === true,
76
+ secret: false,
77
+ json: /^(jsonb?|json)$/i.test(column.dataType),
78
+ validation: {
79
+ regex: validation.regex ?? null,
80
+ minLength: validation.minLength ?? null,
81
+ maxLength: validation.maxLength ?? null,
82
+ },
83
+ sanitize: (type.sanitize?.input ?? []).map((s) => typeof s === 'string' ? s : `${Object.entries(s)[0]?.[0] ?? ''}: ${String(Object.values(s)[0] ?? '')}`),
84
+ // Mirrors the server-side FormSpec: help text and placeholder live
85
+ // under \`hints\`, not at the top level.
86
+ help: hints.help ?? '',
87
+ hints: {
88
+ placeholder: hints.placeholder ?? '',
89
+ help: hints.help ?? '',
90
+ error: hints.error ?? {},
91
+ },
92
+ source: { table: table.tableName, column: column.columnName },
93
+ };
94
+ seen.set(key, [column.columnName]);
95
+ out.push(spec);
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ /**
101
+ * Emit the ES module. The renderer walks a FormSpec at runtime rather than
102
+ * baking one form per call, so the same module serves every entity whose spec
103
+ * arrives from the server.
104
+ */
105
+ function renderModule(component, fields, options) {
106
+ const cc = component.cssClasses ?? {};
107
+ const cls = (key, fallback) => cc[key] ?? fallback;
108
+ const formClass = cls('form', 'sure-form');
109
+ const fieldClass = cls('field', 'sure-form__field');
110
+ const labelClass = cls('label', 'sure-form__label');
111
+ const inputClass = cls('input', 'sure-form__input');
112
+ const errorClass = cls('error', 'sure-form__error');
113
+ const helpClass = cls('help', 'sure-form__help');
114
+ const titleClass = cls('title', 'sure-form__title');
115
+ const actionsClass = cls('actions', 'sure-form__actions');
116
+ const submitClass = cls('submit', 'btn-primary');
117
+ const cancelClass = cls('cancel', 'btn-secondary');
118
+ return `// Generated by sure-factor from catalog/${component.name}.yaml.
119
+ // Component: ${component.name} — DOM renderer, no framework, no dependencies.
120
+ //
121
+ // The form is driven by a FormSpec supplied by the server, so one module
122
+ // renders every entity. Field names come from the catalog-matched columns of
123
+ // the schema this was generated against.
124
+
125
+ export interface FieldHints {
126
+ placeholder?: string
127
+ help?: string
128
+ error?: { required?: string; format?: string; tooShort?: string; tooLong?: string }
129
+ }
130
+
131
+ export interface FieldSpec {
132
+ name: string
133
+ label: string
134
+ help: string
135
+ required: boolean
136
+ control: 'text' | 'password' | 'select' | 'textarea' | 'hidden'
137
+ type: string
138
+ options?: string[]
139
+ readOnly?: boolean
140
+ secret?: boolean
141
+ json?: boolean
142
+ validation: { regex?: string | null; minLength?: number | null; maxLength?: number | null }
143
+ hints: FieldHints
144
+ sanitize: string[]
145
+ source: { table: string; column: string } | null
146
+ }
147
+
148
+ export interface FormSpec {
149
+ id: string
150
+ title: string
151
+ fields: FieldSpec[]
152
+ }
153
+
154
+ /** Minimal element factory. Children may be nodes, strings, or nested arrays. */
155
+ export function h<K extends keyof HTMLElementTagNameMap>(
156
+ tag: K,
157
+ props?: Record<string, unknown> | null,
158
+ ...children: Array<Node | string | null | undefined | Array<Node | string | null | undefined>>
159
+ ): HTMLElementTagNameMap[K] {
160
+ const el = document.createElement(tag)
161
+ if (props) {
162
+ for (const [key, value] of Object.entries(props)) {
163
+ if (value === null || value === undefined || value === false) continue
164
+ if (key === 'class') el.className = String(value)
165
+ else if (key.startsWith('on') && typeof value === 'function') {
166
+ el.addEventListener(key.slice(2).toLowerCase(), value as EventListener)
167
+ } else if (value === true) el.setAttribute(key, '')
168
+ else el.setAttribute(key, String(value))
169
+ }
170
+ }
171
+ const add = (child: Node | string | null | undefined | Array<Node | string | null | undefined>): void => {
172
+ if (child === null || child === undefined) return
173
+ if (Array.isArray(child)) {
174
+ for (const c of child) add(c)
175
+ return
176
+ }
177
+ el.appendChild(typeof child === 'string' ? document.createTextNode(child) : child)
178
+ }
179
+ for (const child of children) add(child)
180
+ return el
181
+ }
182
+
183
+ function fieldId(name: string): string {
184
+ return \`field-\${name}\`
185
+ }
186
+
187
+ /** One labelled control plus its help and error text. */
188
+ export function renderField(
189
+ field: FieldSpec,
190
+ value: string,
191
+ error: string | undefined,
192
+ busy: boolean,
193
+ onChange: (name: string, value: string) => void,
194
+ ): HTMLElement {
195
+ const id = fieldId(field.name)
196
+ const describedBy = error ? \`\${id}-error\` : field.help ? \`\${id}-help\` : undefined
197
+
198
+ const common: Record<string, unknown> = {
199
+ id,
200
+ name: field.name,
201
+ value: field.control === 'select' ? value || (field.options?.[0] ?? '') : value,
202
+ required: field.required,
203
+ disabled: field.readOnly === true || busy,
204
+ readOnly: field.readOnly === true,
205
+ autocomplete: field.control === 'password' ? 'new-password' : 'off',
206
+ 'aria-invalid': error ? 'true' : 'false',
207
+ 'aria-describedby': describedBy,
208
+ placeholder: field.hints?.placeholder ?? '',
209
+ minlength: field.validation?.minLength ?? undefined,
210
+ maxlength: field.control === 'textarea' ? undefined : (field.validation?.maxLength ?? undefined),
211
+ oninput: (e: Event) => onChange(field.name, (e.target as HTMLInputElement).value),
212
+ }
213
+
214
+ let control: HTMLElement
215
+ if (field.control === 'select') {
216
+ const select = h('select', common)
217
+ if (!field.required) {
218
+ const blank = h('option', { value: '' }, '\\u2014')
219
+ select.appendChild(blank)
220
+ }
221
+ for (const opt of field.options ?? []) {
222
+ select.appendChild(h('option', { value: opt }, opt))
223
+ }
224
+ control = select
225
+ } else if (field.control === 'textarea') {
226
+ control = h('textarea', { ...common, rows: 5, spellcheck: 'false' })
227
+ } else {
228
+ const type = field.control === 'password' ? 'password' : (field.type === 'email' ? 'email' : 'text')
229
+ control = h('input', { ...common, type })
230
+ }
231
+
232
+ const label = h('label', { class: ${JSON.stringify(labelClass)}, for: id }, field.label)
233
+ if (field.required) label.appendChild(h('span', { 'aria-hidden': 'true' }, ' *'))
234
+
235
+ const parts: HTMLElement[] = [label, control]
236
+ if (field.help || field.hints?.help) {
237
+ parts.push(
238
+ h('div', { class: ${JSON.stringify(helpClass)}, id: \`\${id}-help\` },
239
+ [field.help, field.hints?.help].filter(Boolean).join(' \\u2014 ')),
240
+ )
241
+ }
242
+ if (error) {
243
+ parts.push(h('div', { class: ${JSON.stringify(errorClass)}, id: \`\${id}-error\`, role: 'alert' }, error))
244
+ }
245
+ return h('div', { class: ${JSON.stringify(fieldClass)} }, ...parts)
246
+ }
247
+
248
+ export interface FormOptions {
249
+ values?: Record<string, string>
250
+ errors?: Record<string, string>
251
+ busy?: boolean
252
+ submitLabel?: string
253
+ onChange: (name: string, value: string) => void
254
+ onSubmit: (values: Record<string, string>) => void
255
+ onCancel?: () => void
256
+ /** Called instead of onSubmit when the values fail validation. */
257
+ onInvalid?: (errors: Record<string, string>) => void
258
+ /** Set false to submit without validating — e.g. for a draft save. */
259
+ validate?: boolean
260
+ }
261
+
262
+ /**
263
+ * Validate a form's values against its spec.
264
+ *
265
+ * The catalog carries the rules (required, regex, min/max length, JSON), and
266
+ * every consumer had been re-implementing this — the management console kept
267
+ * its own copy in formspec.ts. Rules live in the generated module so they
268
+ * cannot drift from the fields they describe.
269
+ *
270
+ * Returns field name → message; an empty object means valid. Never throws: a
271
+ * malformed regex in the catalog is treated as "no constraint" rather than
272
+ * failing the form.
273
+ */
274
+ export function validateForm(
275
+ spec: FormSpec,
276
+ values: Record<string, string>,
277
+ ): Record<string, string> {
278
+ const errors: Record<string, string> = {}
279
+ for (const field of spec.fields) {
280
+ if (field.control === 'hidden') continue
281
+ const value = values[field.name] ?? ''
282
+ const v = field.validation ?? {}
283
+
284
+ if (field.required && value.trim() === '') {
285
+ errors[field.name] = field.hints?.error?.required ?? \`\${field.label} is required\`
286
+ continue
287
+ }
288
+ if (value === '') continue
289
+
290
+ if (field.json) {
291
+ try {
292
+ JSON.parse(value)
293
+ } catch {
294
+ errors[field.name] = 'must be valid JSON'
295
+ continue
296
+ }
297
+ }
298
+
299
+ if (v.regex) {
300
+ let ok = true
301
+ try {
302
+ ok = new RegExp(v.regex, 'u').test(value)
303
+ } catch {
304
+ ok = true
305
+ }
306
+ if (!ok) {
307
+ errors[field.name] = field.hints?.error?.format ?? \`\${field.label} has an invalid format\`
308
+ continue
309
+ }
310
+ }
311
+
312
+ if (v.minLength != null && value.length < v.minLength) {
313
+ errors[field.name] =
314
+ field.hints?.error?.tooShort ?? \`\${field.label} must be at least \${v.minLength} characters\`
315
+ continue
316
+ }
317
+ if (v.maxLength != null && field.control !== 'textarea' && value.length > v.maxLength) {
318
+ errors[field.name] =
319
+ field.hints?.error?.tooLong ?? \`\${field.label} must be at most \${v.maxLength} characters\`
320
+ }
321
+ }
322
+ return errors
323
+ }
324
+
325
+ /** Sanitise values using each field's catalog sanitisation steps. */
326
+ export function sanitizeForm(
327
+ spec: FormSpec,
328
+ values: Record<string, string>,
329
+ ): Record<string, string> {
330
+ const out: Record<string, string> = {}
331
+ for (const field of spec.fields) {
332
+ let value = values[field.name] ?? ''
333
+ if (field.control !== 'hidden' && field.control !== 'textarea' && v_max(field)) {
334
+ value = value.slice(0, v_max(field)!)
335
+ }
336
+ out[field.name] = value.trim()
337
+ }
338
+ return out
339
+ }
340
+
341
+ function v_max(field: { validation?: { maxLength?: number | null } }): number | null {
342
+ const n = field.validation?.maxLength
343
+ return typeof n === 'number' && n > 0 ? n : null
344
+ }
345
+
346
+ /** Render a FormSpec into a form element wired to the supplied callbacks. */
347
+ export function renderForm(spec: FormSpec, options: FormOptions): HTMLFormElement {
348
+ const values = options.values ?? {}
349
+ const errors = options.errors ?? {}
350
+ const busy = options.busy ?? false
351
+
352
+ const visible = spec.fields.filter((f) => f.control !== 'hidden')
353
+ const form = h('form', {
354
+ class: ${JSON.stringify(formClass)},
355
+ 'aria-label': spec.title,
356
+ novalidate: true,
357
+ onsubmit: (e: Event) => {
358
+ e.preventDefault()
359
+ if (busy) return
360
+ if (options.validate === false) {
361
+ options.onSubmit(values)
362
+ return
363
+ }
364
+ // Validate before handing anything over. The rules come from the catalog
365
+ // via the spec, so a malformed value never leaves the browser.
366
+ const found = validateForm(spec, values)
367
+ if (Object.keys(found).length === 0) {
368
+ options.onSubmit(sanitizeForm(spec, values))
369
+ return
370
+ }
371
+ // Tell the caller what is wrong; it owns the render loop and decides how
372
+ // to show it.
373
+ if (options.onInvalid) options.onInvalid(found)
374
+ else options.onSubmit(values)
375
+ },
376
+ })
377
+
378
+ form.appendChild(h('h2', { class: ${JSON.stringify(titleClass)} }, spec.title))
379
+ for (const field of visible) {
380
+ form.appendChild(renderField(field, values[field.name] ?? '', errors[field.name], busy, options.onChange))
381
+ }
382
+
383
+ const actions = h('div', { class: ${JSON.stringify(actionsClass)} })
384
+ actions.appendChild(h('button', { class: ${JSON.stringify(submitClass)}, type: 'submit', disabled: busy },
385
+ options.submitLabel ?? 'Save'))
386
+ if (options.onCancel) {
387
+ actions.appendChild(h('button', {
388
+ class: ${JSON.stringify(cancelClass)},
389
+ type: 'button',
390
+ disabled: busy,
391
+ onclick: () => options.onCancel?.(),
392
+ }, 'Cancel'))
393
+ }
394
+ form.appendChild(actions)
395
+ return form
396
+ }
397
+
398
+ /** The fields this module was generated for, for a server to fill a spec from. */
399
+ export const GENERATED_FIELDS: FieldSpec[] = ${JSON.stringify(fields, null, 2)}
400
+
401
+ export const CSS_CLASSES = ${JSON.stringify({ ...cc }, null, 2)} as const
402
+
403
+ export default renderForm
404
+ `;
405
+ }
406
+ /**
407
+ * A component is rendered as a table when its catalog entry declares table
408
+ * classes. Without this every component would get the same form renderer —
409
+ * asking for `data-table` produced a form module with `sure-table` class names
410
+ * on it.
411
+ */
412
+ function isTableComponent(component) {
413
+ const cc = component.cssClasses ?? {};
414
+ return typeof cc.row === 'string' || typeof cc.cell === 'string' || typeof cc.header === 'string';
415
+ }
416
+ /**
417
+ * The table renderer. Shares the element factory with the form module, but
418
+ * emits `<table>` markup and a column renderer rather than labelled controls.
419
+ */
420
+ function renderTableModule(component, fields) {
421
+ const cc = component.cssClasses ?? {};
422
+ const cls = (key, fallback) => cc[key] ?? fallback;
423
+ const tableClass = cls('form', 'sure-table');
424
+ const headerClass = cls('header', cls('label', 'sure-table__header'));
425
+ const cellClass = cls('cell', cls('field', 'sure-table__cell'));
426
+ const rowClass = cc.row ?? '';
427
+ const errorClass = cls('error', 'sure-table__error');
428
+ return `// Generated by sure-factor from catalog/${component.name}.yaml.
429
+ // Component: ${component.name} — DOM table renderer, no framework.
430
+ //
431
+ // Columns are derived from the catalog-matched columns of the schema this was
432
+ // generated against. Pass rows as plain objects keyed by field name.
433
+
434
+ export interface ColumnSpec {
435
+ /** Field name, used to read the value off each row. */
436
+ name: string
437
+ label: string
438
+ /** Rendered instead of the raw value when the row has no such key. */
439
+ emptyText?: string
440
+ }
441
+
442
+ export interface TableOptions {
443
+ columns?: ColumnSpec[]
444
+ rows: Array<Record<string, unknown>>
445
+ emptyText?: string
446
+ selectedId?: string | null
447
+ onRowClick?: (row: Record<string, unknown>) => void
448
+ /** Row identity; defaults to \`id\`. */
449
+ idKey?: string
450
+ }
451
+
452
+ /** Minimal element factory. Children may be nodes, strings, or nested arrays. */
453
+ export function h<K extends keyof HTMLElementTagNameMap>(
454
+ tag: K,
455
+ props?: Record<string, unknown> | null,
456
+ ...children: Array<Node | string | null | undefined | Array<Node | string | null | undefined>>
457
+ ): HTMLElementTagNameMap[K] {
458
+ const el = document.createElement(tag)
459
+ if (props) {
460
+ for (const [key, value] of Object.entries(props)) {
461
+ if (value === null || value === undefined || value === false) continue
462
+ if (key === 'class') el.className = String(value)
463
+ else if (key.startsWith('on') && typeof value === 'function') {
464
+ el.addEventListener(key.slice(2).toLowerCase(), value as EventListener)
465
+ } else if (value === true) el.setAttribute(key, '')
466
+ else el.setAttribute(key, String(value))
467
+ }
468
+ }
469
+ const add = (child: Node | string | null | undefined | Array<Node | string | null | undefined>): void => {
470
+ if (child === null || child === undefined) return
471
+ if (Array.isArray(child)) {
472
+ for (const c of child) add(c)
473
+ return
474
+ }
475
+ el.appendChild(typeof child === 'string' ? document.createTextNode(child) : child)
476
+ }
477
+ for (const child of children) add(child)
478
+ return el
479
+ }
480
+
481
+ /**
482
+ * A cell value may be a plain value (rendered as text), an array (joined), or
483
+ * a Node (appended as-is). Accepting Nodes matters because status badges and
484
+ * action buttons are elements, and stringifying one would put
485
+ * "[object HTMLElement]" in the table.
486
+ */
487
+ function appendCell(td: HTMLElement, value: unknown, emptyText: string): void {
488
+ if (value === null || value === undefined || value === '') {
489
+ td.appendChild(document.createTextNode(emptyText))
490
+ return
491
+ }
492
+ if (Array.isArray(value)) {
493
+ const text = value.length > 0 ? value.join(', ') : emptyText
494
+ td.appendChild(document.createTextNode(text))
495
+ return
496
+ }
497
+ if (typeof value === 'object' && 'nodeType' in (value as Node)) {
498
+ td.appendChild(value as Node)
499
+ return
500
+ }
501
+ td.appendChild(document.createTextNode(String(value)))
502
+ }
503
+
504
+ export function renderTable(options: TableOptions): HTMLElement {
505
+ const columns: ColumnSpec[] = options.columns ?? GENERATED_COLUMNS
506
+ const idKey = options.idKey ?? 'id'
507
+
508
+ if (options.rows.length === 0) {
509
+ return h('p', { class: ${JSON.stringify(errorClass)}, role: 'status' },
510
+ options.emptyText ?? 'Nothing here yet.')
511
+ }
512
+
513
+ const head = h('tr', null,
514
+ ...columns.map((c) => h('th', { class: ${JSON.stringify(headerClass)}, scope: 'col' }, c.label)),
515
+ )
516
+
517
+ const body = h('tbody', null,
518
+ ...options.rows.map((row) => {
519
+ const rowId = String(row[idKey] ?? '')
520
+ const selected = options.selectedId != null && rowId === String(options.selectedId)
521
+ const tr = h('tr', {
522
+ class: ${JSON.stringify(rowClass)} + (selected ? ' is-selected' : ''),
523
+ 'aria-selected': selected ? 'true' : undefined,
524
+ onclick: options.onRowClick ? () => options.onRowClick?.(row) : undefined,
525
+ style: { cursor: options.onRowClick ? 'pointer' : '' },
526
+ },
527
+ ...columns.map((c) => {
528
+ const td = h('td', { class: ${JSON.stringify(cellClass)} })
529
+ appendCell(td, row[c.name], c.emptyText ?? '\\u2014')
530
+ return td
531
+ }),
532
+ )
533
+ return tr
534
+ }),
535
+ )
536
+
537
+ return h('table', { class: ${JSON.stringify(tableClass)} }, h('thead', null, head), body)
538
+ }
539
+
540
+ /** The columns this module was generated for. */
541
+ export const GENERATED_COLUMNS: ColumnSpec[] = ${JSON.stringify(fields.map((f) => ({ name: f.name, label: f.label, emptyText: '\\u2014' })), null, 2)}
542
+
543
+ export const GENERATED_FIELDS = ${JSON.stringify(fields, null, 2)}
544
+
545
+ export const CSS_CLASSES = ${JSON.stringify({ ...cc }, null, 2)} as const
546
+
547
+ export default renderTable
548
+ `;
549
+ }
550
+ export function generateClientComponent(schema, options) {
551
+ const component = loadComponent(options.component);
552
+ if (!component) {
553
+ throw new Error(`Component "${options.component}" not found in catalog`);
554
+ }
555
+ const fields = buildClientFields(schema, options, component);
556
+ const module = isTableComponent(component)
557
+ ? renderTableModule(component, fields)
558
+ : renderModule(component, fields, options);
559
+ return {
560
+ module,
561
+ fields,
562
+ cssClasses: { ...(component.cssClasses ?? {}) },
563
+ };
564
+ }
565
+ //# sourceMappingURL=generate-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-client.js","sourceRoot":"","sources":["../src/generate-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAc,YAAY,EAAE,MAAM,IAAI,CAAA;AAG7C,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AACpE,OAAO,EAAE,SA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UAAU,uBAAuB,CACrC,MAAkB,EAClB,OAA8B;IAE9B,MAAM,SAAS,GAAG,aAAa,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IAClD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,cAAc,OAAO,CAAC,SAAS,wBAAwB,CAAC,CAAA;IAC1E,CAAC;IACD,MAAM,MAAM,GAAG,iBAAiB,CAAC,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAA;IAC5D,MAAM,MAAM,GAAG,gBAAgB,CAAC,SAAS,CAAC;QACxC,CAAC,CAAC,iBAAiB,CAAC,SAAS,EAAE,MAAM,CAAC;QACtC,CAAC,CAAC,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5C,OAAO;QACL,MAAM;QACN,MAAM;QACN,UAAU,EAAE,EAAE,GAAG,CAAC,SAAS,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE;KAChD,CAAA;AACH,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Helpers shared by the server target (`generate.ts`) and the client target
3
+ * (`generate-client.ts`). They live here rather than in either generator so the
4
+ * two can use them without a circular import — and so both emit the same
5
+ * escaping and the same collision handling, which is what keeps the two
6
+ * targets agreeing about a column's key and its regex.
7
+ */
8
+ /**
9
+ * A stable key for a column. The bare column name is used when it is unique
10
+ * across the schema, so simple single-table output is unchanged; a repeat is
11
+ * qualified by its table so no entry is overwritten.
12
+ */
13
+ export declare function uniqueKey(seen: Map<string, string[]>, table: string, column: string): string;
14
+ /**
15
+ * Embed a regex as a `/.../` literal. Escaping `/` alone truncates any
16
+ * character class that contains one (`[a-z0-9.!#$%&'*+/=?]`) and any
17
+ * quantifier brace; `RegExp.prototype.source` already produces a
18
+ * correctly-escaped body.
19
+ */
20
+ export declare function toRegexLiteral(pattern: string): string;
21
+ /**
22
+ * Render one catalog sanitisation step as a single string. Steps are either a
23
+ * bare name (`trim`, `slice(0, 254)`) or a parameterised object
24
+ * (`{ normalize: NFKC }`). Both become one argument: the `slice(0, 254)` form
25
+ * carries a comma inside its argument and must not be split in two.
26
+ */
27
+ export declare function sanitizeStepLiteral(step: unknown): string;
28
+ /**
29
+ * Render a Map of key → chained calls as the body of a JavaScript object
30
+ * literal, with every entry comma-separated so the result parses.
31
+ */
32
+ export declare function objectBody(entries: Map<string, string[]>, wrap?: string): string;
33
+ //# sourceMappingURL=generate-internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-internal.d.ts","sourceRoot":"","sources":["../src/generate-internal.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAQ5F;AAUD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAOzD;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,SAAe,GAAG,MAAM,CAItF"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Helpers shared by the server target (`generate.ts`) and the client target
3
+ * (`generate-client.ts`). They live here rather than in either generator so the
4
+ * two can use them without a circular import — and so both emit the same
5
+ * escaping and the same collision handling, which is what keeps the two
6
+ * targets agreeing about a column's key and its regex.
7
+ */
8
+ /**
9
+ * A stable key for a column. The bare column name is used when it is unique
10
+ * across the schema, so simple single-table output is unchanged; a repeat is
11
+ * qualified by its table so no entry is overwritten.
12
+ */
13
+ export function uniqueKey(seen, table, column) {
14
+ const taken = new Set(seen.keys());
15
+ if (!taken.has(column)) {
16
+ const count = countColumns(seen, column);
17
+ if (count === 0)
18
+ return column;
19
+ return `${table}_${column}`;
20
+ }
21
+ return `${table}_${column}`;
22
+ }
23
+ function countColumns(seen, column) {
24
+ let n = 0;
25
+ for (const k of seen.keys()) {
26
+ if (k === column || k.endsWith(`_${column}`))
27
+ n++;
28
+ }
29
+ return n;
30
+ }
31
+ /**
32
+ * Embed a regex as a `/.../` literal. Escaping `/` alone truncates any
33
+ * character class that contains one (`[a-z0-9.!#$%&'*+/=?]`) and any
34
+ * quantifier brace; `RegExp.prototype.source` already produces a
35
+ * correctly-escaped body.
36
+ */
37
+ export function toRegexLiteral(pattern) {
38
+ return `/${new RegExp(pattern).source}/`;
39
+ }
40
+ /**
41
+ * Render one catalog sanitisation step as a single string. Steps are either a
42
+ * bare name (`trim`, `slice(0, 254)`) or a parameterised object
43
+ * (`{ normalize: NFKC }`). Both become one argument: the `slice(0, 254)` form
44
+ * carries a comma inside its argument and must not be split in two.
45
+ */
46
+ export function sanitizeStepLiteral(step) {
47
+ if (typeof step === 'string')
48
+ return JSON.stringify(step);
49
+ if (step && typeof step === 'object' && !Array.isArray(step)) {
50
+ const [name, arg] = Object.entries(step)[0] ?? [];
51
+ if (name)
52
+ return JSON.stringify(`${name}: ${String(arg ?? '')}`);
53
+ }
54
+ return JSON.stringify(String(step));
55
+ }
56
+ /**
57
+ * Render a Map of key → chained calls as the body of a JavaScript object
58
+ * literal, with every entry comma-separated so the result parses.
59
+ */
60
+ export function objectBody(entries, wrap = 'z.string()') {
61
+ return [...entries.entries()]
62
+ .map(([key, chain]) => ` ${JSON.stringify(key)}: ${wrap}${chain.join('')},`)
63
+ .join('\n');
64
+ }
65
+ //# sourceMappingURL=generate-internal.js.map