@selfhelp/shared 1.22.1 → 1.24.0

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/dist/index.d.mts +308 -100
  3. package/dist/index.d.ts +308 -100
  4. package/dist/index.js +519 -3
  5. package/dist/index.mjs +495 -3
  6. package/dist/plugin-sdk/index.d.mts +1 -1
  7. package/dist/plugin-sdk/index.d.ts +1 -1
  8. package/dist/plugin-sdk/index.js +3 -1
  9. package/dist/plugin-sdk/index.mjs +3 -1
  10. package/dist/registry/index.d.mts +2 -2
  11. package/dist/registry/index.d.ts +2 -2
  12. package/dist/registry/index.js +3 -1
  13. package/dist/registry/index.mjs +3 -1
  14. package/dist/{styles.registry-DylfiWW_.d.ts → styles.registry-BKWoDg7q.d.ts} +756 -6
  15. package/dist/{styles.registry-Dl55-gWX.d.mts → styles.registry-aopb3vsI.d.mts} +756 -6
  16. package/package.json +1 -1
  17. package/src/api/__tests__/endpoints.test.ts +45 -0
  18. package/src/api/__tests__/formListErrors.test.ts +143 -0
  19. package/src/api/endpoints.ts +41 -0
  20. package/src/api/formListErrors.ts +134 -0
  21. package/src/api/index.ts +1 -0
  22. package/src/content/__tests__/formListState.test.ts +448 -0
  23. package/src/content/__tests__/formRecordPrefill.test.ts +120 -0
  24. package/src/content/formListState.ts +559 -0
  25. package/src/content/formRecordPrefill.ts +108 -5
  26. package/src/content/index.ts +1 -0
  27. package/src/registry/__tests__/platform.test.ts +15 -6
  28. package/src/registry/styles.registry.ts +2 -0
  29. package/src/types/__tests__/version-about.test.ts +80 -0
  30. package/src/types/api/__tests__/formWrites.test.ts +84 -0
  31. package/src/types/api/__tests__/system.test.ts +10 -0
  32. package/src/types/api/form-lists.ts +469 -0
  33. package/src/types/api/forms.ts +149 -4
  34. package/src/types/api/index.ts +1 -0
  35. package/src/types/api/system.ts +9 -0
  36. package/src/types/styles/composite.ts +13 -0
  37. package/src/types/styles/error.ts +54 -4
  38. package/src/types/styles/forms.ts +84 -0
  39. package/src/types/styles/unknown.ts +5 -1
@@ -11,26 +11,52 @@
11
11
  * (`load_record_from`); this helper only reshapes that payload.
12
12
  */
13
13
 
14
+ import type { IFormListFilesCell, IFormListFileValue } from '../types/api/form-lists';
15
+
14
16
  /** Per-language value for a translatable form field. */
15
17
  export interface IFormRecordPrefillTranslatedValue {
16
18
  language_id: number;
17
19
  value: string;
18
20
  }
19
21
 
20
- export type TFormRecordPrefillFieldValue = string | IFormRecordPrefillTranslatedValue[];
22
+ /**
23
+ * A file-input prefill value (contract 4): current files with server-built URLs,
24
+ * never a storage key. Same shape as a list `file`/`image` cell.
25
+ */
26
+ export type TFormRecordPrefillFileValue = IFormListFilesCell;
27
+
28
+ export type TFormRecordPrefillFieldValue =
29
+ | string
30
+ | IFormRecordPrefillTranslatedValue[]
31
+ | TFormRecordPrefillFileValue;
21
32
 
22
33
  export interface IFormRecordPrefill {
23
34
  recordId: number | null;
24
35
  values: Record<string, TFormRecordPrefillFieldValue>;
36
+ /**
37
+ * The version the record had when the page was built (`_version` of its rows). Send it back
38
+ * as `expected_version` when saving or deleting the record: the server refuses a save
39
+ * without it (400) and a save based on an old one (409, the draft stays). Absent when the page
40
+ * offered none (a new record, or a server that does not name it).
41
+ */
42
+ version?: number;
25
43
  }
26
44
 
27
- /** Metadata fields that are never form inputs. */
45
+ /**
46
+ * Metadata fields that are never form inputs. The trigger type is skipped under
47
+ * both spellings: `id_action_trigger_types` is the column the data store (and the
48
+ * list engine) returns, `id_actionTriggerTypes` the name older payloads used. A
49
+ * form that wrote it back would be refused ("not allowed in form data"). `_version`
50
+ * is the record's version, read into {@link IFormRecordPrefill.version}.
51
+ */
28
52
  export const FORM_RECORD_PREFILL_SKIP_FIELDS: ReadonlySet<string> = new Set([
29
53
  'record_id',
54
+ '_version',
30
55
  'entry_date',
31
56
  'id_users',
32
57
  'user_name',
33
58
  'user_code',
59
+ 'id_action_trigger_types',
34
60
  'id_actionTriggerTypes',
35
61
  'triggerType',
36
62
  'id_languages',
@@ -66,10 +92,51 @@ function asScalarString(value: unknown): string | null {
66
92
  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
67
93
  return String(value);
68
94
  }
69
- // Nested objects/arrays are not form field values — skip.
95
+ // Nested objects/arrays are not plain text field values — skip (files use asFilesCell).
70
96
  return null;
71
97
  }
72
98
 
99
+ /** Narrow a prefill cell to `{ files: [...] }` when the server sent contract-4 file metadata. */
100
+ export function asFilesCell(value: unknown): TFormRecordPrefillFileValue | null {
101
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
102
+ return null;
103
+ }
104
+ const files = (value as { files?: unknown }).files;
105
+ if (!Array.isArray(files)) {
106
+ return null;
107
+ }
108
+ const out: IFormListFileValue[] = [];
109
+ for (const entry of files) {
110
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
111
+ continue;
112
+ }
113
+ const file = entry as Record<string, unknown>;
114
+ const index = typeof file.index === 'number' ? file.index : Number(file.index);
115
+ const name = typeof file.name === 'string' ? file.name : null;
116
+ const url = typeof file.url === 'string' ? file.url : null;
117
+ if (!Number.isFinite(index) || name === null || url === null) {
118
+ continue;
119
+ }
120
+ const mime = typeof file.mime === 'string' ? file.mime : file.mime === null ? null : undefined;
121
+ const size =
122
+ typeof file.size === 'number'
123
+ ? file.size
124
+ : file.size === null
125
+ ? null
126
+ : typeof file.size === 'string' && Number.isFinite(Number(file.size))
127
+ ? Number(file.size)
128
+ : undefined;
129
+ out.push({
130
+ index: Math.trunc(index),
131
+ name,
132
+ url,
133
+ ...(mime !== undefined ? { mime } : {}),
134
+ ...(size !== undefined ? { size } : {}),
135
+ });
136
+ }
137
+ return { files: out };
138
+ }
139
+
73
140
  /**
74
141
  * Parse hydrated `section_data` rows into `{ recordId, values }`.
75
142
  *
@@ -86,6 +153,7 @@ export function parseFormRecordPrefill(section: IFormRecordPrefillSection): IFor
86
153
  }
87
154
 
88
155
  const recordGroups: Record<number, Record<string, TFormRecordPrefillFieldValue>> = {};
156
+ const recordVersions: Record<number, number> = {};
89
157
 
90
158
  for (const row of sectionDataArray) {
91
159
  if (!row || typeof row !== 'object' || Array.isArray(row)) {
@@ -107,6 +175,12 @@ export function parseFormRecordPrefill(section: IFormRecordPrefillSection): IFor
107
175
  recordGroups[recordId] = {};
108
176
  }
109
177
 
178
+ // Every row of a record (one per language) names the same version.
179
+ const version = asRecordVersion(record._version);
180
+ if (version !== null && recordVersions[recordId] === undefined) {
181
+ recordVersions[recordId] = version;
182
+ }
183
+
110
184
  const languageId =
111
185
  typeof record.id_languages === 'number'
112
186
  ? record.id_languages
@@ -118,6 +192,13 @@ export function parseFormRecordPrefill(section: IFormRecordPrefillSection): IFor
118
192
  if (FORM_RECORD_PREFILL_SKIP_FIELDS.has(fieldName)) {
119
193
  continue;
120
194
  }
195
+ const filesCell = asFilesCell(fieldValue);
196
+ if (filesCell !== null) {
197
+ if (languageId === 1 || !recordGroups[recordId][fieldName]) {
198
+ recordGroups[recordId][fieldName] = filesCell;
199
+ }
200
+ continue;
201
+ }
121
202
  const value = asScalarString(fieldValue);
122
203
  if (value === null) {
123
204
  continue;
@@ -132,7 +213,11 @@ export function parseFormRecordPrefill(section: IFormRecordPrefillSection): IFor
132
213
  }
133
214
  } else if (typeof languageId === 'number') {
134
215
  const current = recordGroups[recordId][fieldName];
135
- if (typeof current === 'string' || !current) {
216
+ if (typeof current === 'string' || Array.isArray(current) === false || !current) {
217
+ if (typeof current === 'object' && current !== null && 'files' in current) {
218
+ // Keep an existing file cell; do not overwrite with text.
219
+ continue;
220
+ }
136
221
  recordGroups[recordId][fieldName] = [{ language_id: languageId, value }];
137
222
  } else {
138
223
  const langValues = current;
@@ -156,7 +241,21 @@ export function parseFormRecordPrefill(section: IFormRecordPrefillSection): IFor
156
241
  }
157
242
 
158
243
  const id = Number(firstRecordId);
159
- return { recordId: id, values: recordGroups[id] ?? {} };
244
+ const version = recordVersions[id];
245
+ return version === undefined
246
+ ? { recordId: id, values: recordGroups[id] ?? {} }
247
+ : { recordId: id, values: recordGroups[id] ?? {}, version };
248
+ }
249
+
250
+ /** A record version as the page offers it: a whole number of at least 1, as a number or as digits. */
251
+ export function asRecordVersion(value: unknown): number | null {
252
+ const candidate =
253
+ typeof value === 'number'
254
+ ? value
255
+ : typeof value === 'string' && /^[1-9]\d*$/.test(value.trim())
256
+ ? Number(value.trim())
257
+ : Number.NaN;
258
+ return Number.isSafeInteger(candidate) && candidate >= 1 ? candidate : null;
160
259
  }
161
260
 
162
261
  /**
@@ -174,6 +273,10 @@ export function flattenFormRecordPrefillValues(
174
273
  out[key] = value;
175
274
  continue;
176
275
  }
276
+ if (value && typeof value === 'object' && !Array.isArray(value) && 'files' in value) {
277
+ // File cells stay structured; callers that need plain strings omit them.
278
+ continue;
279
+ }
177
280
  if (!Array.isArray(value) || value.length === 0) {
178
281
  continue;
179
282
  }
@@ -6,3 +6,4 @@ export * from './inlineFormat';
6
6
  export * from './optionLabels';
7
7
  export * from './fieldsMapLabels';
8
8
  export * from './formRecordPrefill';
9
+ export * from './formListState';
@@ -146,12 +146,13 @@ describe('style placement targeting', () => {
146
146
 
147
147
  /**
148
148
  * Catalog parity (mobile rendering plan, milestone one + entry-record-form).
149
- * The core registry must match the established backend catalog (91 styles):
150
- * the eight previously-missing system/data/reference styles are present, and
151
- * the sixteen deferred speculative styles are absent. Drift here means the
149
+ * The core registry must match the established backend catalog (93 styles):
150
+ * the eight previously-missing system/data/reference styles are present, the
151
+ * two list styles (`entry-form-list`, `data-view`) are present, and the
152
+ * sixteen deferred speculative styles are absent. Drift here means the
152
153
  * shared contract and the backend catalog have diverged.
153
154
  */
154
- describe('core catalog parity (91 established styles)', () => {
155
+ describe('core catalog parity (93 established styles)', () => {
155
156
  const CORE_NAMES = Object.keys(BASE_STYLE_REGISTRY);
156
157
 
157
158
  const PREVIOUSLY_MISSING = [
@@ -165,11 +166,19 @@ describe('core catalog parity (91 established styles)', () => {
165
166
  'input-otp', 'search-field', 'fab-button', 'biometric-login-button',
166
167
  ];
167
168
 
168
- it('contains exactly the 91 established core styles', () => {
169
- expect(CORE_NAMES).toHaveLength(91);
169
+ it('contains exactly the 93 established core styles', () => {
170
+ expect(CORE_NAMES).toHaveLength(93);
170
171
  expect(CORE_NAMES).toContain('entry-record-form');
171
172
  });
172
173
 
174
+ it('registers the list styles as forms-category styles on both platforms', () => {
175
+ expect(BASE_STYLE_REGISTRY['entry-form-list']).toMatchObject({ category: 'forms', canHaveChildren: true });
176
+ expect(BASE_STYLE_REGISTRY['data-view']).toMatchObject({ category: 'forms', canHaveChildren: true });
177
+ for (const name of ['entry-form-list', 'data-view']) {
178
+ expect(getStylePlatforms(name)).toEqual(['web', 'mobile']);
179
+ }
180
+ });
181
+
173
182
  it('includes every previously-missing established style', () => {
174
183
  for (const name of PREVIOUSLY_MISSING) {
175
184
  expect(CORE_NAMES, `missing established style: ${name}`).toContain(name);
@@ -227,6 +227,8 @@ export const BASE_STYLE_REGISTRY = {
227
227
  'ref-container': { description: 'Renders content referenced from another section', category: 'layout', canHaveChildren: true },
228
228
  'data-container': { description: 'Data-scoped container (renders subtree against a data scope)', category: 'layout', canHaveChildren: true },
229
229
  'entry-table': { description: 'Built-in admin CRUD grid over a form\'s records (search/sort/paginate/CSV, add / edit / delete actions)', category: 'forms', canHaveChildren: false },
230
+ 'entry-form-list': { description: 'Entry list with form: server-rendered list of records with create / view / edit / delete, quick actions and history', category: 'forms', canHaveChildren: true },
231
+ 'data-view': { description: 'Read-only server-rendered table, cards or your own layout (sections placed inside, drawn once per record) of records of a data table', category: 'forms', canHaveChildren: true },
230
232
  } as const satisfies Record<string, IStyleRegistryEntry>;
231
233
 
232
234
  /**
@@ -0,0 +1,80 @@
1
+ /*
2
+ * SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ * SPDX-License-Identifier: MPL-2.0
4
+ */
5
+
6
+ import { describe, expect, it } from 'vitest';
7
+ import type { IAboutItem, IPlatformAbout, IVersionStyle } from '../index';
8
+
9
+ /**
10
+ * Contract pin for the "about the platform" block of the `version` style
11
+ * (backend `PlatformAboutService`, web `VersionStyle`, mobile `Version`).
12
+ * The types are imported from the package's types barrel so the test also fails
13
+ * if they stop being exported there; the shapes are checked by `tsc` (the
14
+ * fixtures below do not compile if a key is renamed, dropped or made optional).
15
+ */
16
+ describe('version style about contract', () => {
17
+ const guest: IPlatformAbout = {
18
+ detail: false,
19
+ product: { name: 'SelfHelp', version: '0.1.43' },
20
+ frameworks: [{ name: 'PHP', version: null, license: 'PHP-3.01' }],
21
+ plugins: [],
22
+ libraries: [{ name: 'doctrine/orm', version: null, license: 'MIT' }],
23
+ };
24
+
25
+ const admin: IPlatformAbout = {
26
+ ...guest,
27
+ detail: true,
28
+ frameworks: [{ name: 'PHP', version: '8.4.1', license: 'PHP-3.01' }],
29
+ libraries: [{ name: 'doctrine/orm', version: '3.3.0', license: 'MIT OR Apache-2.0' }],
30
+ };
31
+
32
+ it('shows only the product version to a caller without detail', () => {
33
+ const versions = [...guest.frameworks, ...guest.plugins, ...guest.libraries].map((item) => item.version);
34
+
35
+ expect(guest.detail).toBe(false);
36
+ expect(guest.product.version).toBe('0.1.43');
37
+ expect(versions.every((version) => version === null)).toBe(true);
38
+ });
39
+
40
+ it('carries exact versions and joined licences for a caller with detail', () => {
41
+ const item: IAboutItem | undefined = admin.libraries[0];
42
+
43
+ expect(admin.detail).toBe(true);
44
+ expect(item?.version).toBe('3.3.0');
45
+ expect(item?.license).toBe('MIT OR Apache-2.0');
46
+ });
47
+
48
+ it('is always present on a version section, together with its translatable headings', () => {
49
+ const section: Pick<
50
+ IVersionStyle,
51
+ | 'style_name'
52
+ | 'about'
53
+ | 'title'
54
+ | 'label_frameworks'
55
+ | 'label_plugins'
56
+ | 'label_libraries'
57
+ | 'label_web'
58
+ | 'label_app'
59
+ | 'label_filter'
60
+ | 'label_no_match'
61
+ > = {
62
+ style_name: 'version',
63
+ about: guest,
64
+ title: { content: 'About this platform' },
65
+ label_frameworks: { content: 'Frameworks' },
66
+ label_plugins: { content: 'Plugins' },
67
+ label_libraries: { content: 'Libraries' },
68
+ label_web: { content: 'Website' },
69
+ label_app: { content: 'Mobile app' },
70
+ label_filter: { content: 'Filter' },
71
+ label_no_match: { content: 'Nothing matches the filter.' },
72
+ };
73
+
74
+ expect(section.style_name).toBe('version');
75
+ expect(section.about.plugins).toEqual([]);
76
+ expect(section.label_web?.content).toBe('Website');
77
+ expect(section.label_filter?.content).toBe('Filter');
78
+ expect(section.label_no_match?.content).toBe('Nothing matches the filter.');
79
+ });
80
+ });
@@ -0,0 +1,84 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Compile-time contract of the form and list writes: the server refuses an
7
+ * interactive update, delete, quick action or restore that names no record
8
+ * version (400), and judges every request by the configuration the person looks
9
+ * at (`preview`). `npm run typecheck` fails when a type drifts from that; the
10
+ * runtime assertions only keep the file a real test.
11
+ */
12
+ import { describe, expect, expectTypeOf, it } from 'vitest';
13
+ import type { IFormListQuickActionRequest, IFormListRestoreRequest } from '../form-lists';
14
+ import type {
15
+ IFormDeleteRequest,
16
+ IFormEffectiveContext,
17
+ IFormInputError,
18
+ IFormInvalidData,
19
+ IFormSubmitRequest,
20
+ IFormUpdateRequest,
21
+ TFormInputRule,
22
+ TFormWriteRefusalReason,
23
+ } from '../forms';
24
+
25
+ describe('form write contracts', () => {
26
+ it('requires the record version of an interactive update and delete', () => {
27
+ // @ts-expect-error an update without expected_version is refused by the server (400 expected_version_required)
28
+ const update: IFormUpdateRequest = { section_id: 1, form_data: {} };
29
+ // @ts-expect-error a delete without expected_version is refused by the server (400 expected_version_required)
30
+ const remove: IFormDeleteRequest = { record_id: 1, section_id: 1 };
31
+
32
+ expectTypeOf<IFormUpdateRequest['expected_version']>().toEqualTypeOf<number>();
33
+ expectTypeOf<IFormDeleteRequest['expected_version']>().toEqualTypeOf<number>();
34
+ expectTypeOf<IFormListQuickActionRequest['expected_version']>().toEqualTypeOf<number>();
35
+ expect([update, remove]).toHaveLength(2);
36
+ });
37
+
38
+ it('lets a restore preview omit the version and sends the version of a real one', () => {
39
+ const preview: IFormListRestoreRequest = { page_id: 1, version: 2, dry_run: true };
40
+ const restore: IFormListRestoreRequest = { page_id: 1, version: 2, expected_version: 3 };
41
+
42
+ expectTypeOf<IFormListRestoreRequest['expected_version']>().toEqualTypeOf<number | undefined>();
43
+ expect([preview.dry_run, restore.expected_version]).toEqual([true, 3]);
44
+ });
45
+
46
+ it('lets every write and read name the page version it acts on', () => {
47
+ const draft: IFormEffectiveContext = { preview: true };
48
+
49
+ expectTypeOf<IFormSubmitRequest['preview']>().toEqualTypeOf<boolean | undefined>();
50
+ expectTypeOf<IFormUpdateRequest['preview']>().toEqualTypeOf<boolean | undefined>();
51
+ expectTypeOf<IFormDeleteRequest['preview']>().toEqualTypeOf<boolean | undefined>();
52
+ expectTypeOf<IFormListQuickActionRequest['preview']>().toEqualTypeOf<boolean | undefined>();
53
+ expectTypeOf<IFormListRestoreRequest['preview']>().toEqualTypeOf<boolean | undefined>();
54
+ expect(draft.preview).toBe(true);
55
+ });
56
+
57
+ it('describes a refused value by the rule of its input', () => {
58
+ const error: IFormInputError = { field: 'Title', key: 'section_9', rule: 'required', message: 'This field is required.' };
59
+ const data: IFormInvalidData = { reason: 'invalid_form_data', errors: [error] };
60
+
61
+ expectTypeOf<IFormInputError['rule']>().toEqualTypeOf<TFormInputRule>();
62
+ expectTypeOf<IFormInvalidData['reason']>().toEqualTypeOf<'invalid_form_data'>();
63
+ expect(data.errors[0]?.rule).toBe('required');
64
+ });
65
+
66
+ it('lists the refusals a write can answer with', () => {
67
+ const reasons: TFormWriteRefusalReason[] = [
68
+ 'expected_version_required',
69
+ 'invalid_expected_version',
70
+ 'unsupported_target_selection',
71
+ 'protected_field',
72
+ 'unknown_field',
73
+ 'invalid_file_value',
74
+ 'table_mismatch',
75
+ 'login_required',
76
+ 'operation_disabled',
77
+ 'history_disabled',
78
+ 'unknown_action',
79
+ 'action_not_available',
80
+ ];
81
+
82
+ expect(new Set(reasons).size).toBe(reasons.length);
83
+ });
84
+ });
@@ -169,6 +169,12 @@ describe('system maintenance contracts', () => {
169
169
  safe_mode: false,
170
170
  maintenance_mode: false,
171
171
  installed_plugins: [{ id: 'sh2-shp-survey-js', version: '0.2.20', compatible: true }],
172
+ // The admin route always carries exact versions (it needs admin.system.read).
173
+ frameworks: [
174
+ { name: 'PHP', version: '8.4.1', license: 'PHP-3.01' },
175
+ { name: 'Redis', version: null, license: null },
176
+ ],
177
+ libraries: [{ name: 'doctrine/orm', version: '3.3.0', license: 'MIT' }],
172
178
  };
173
179
  const preflight: IUpdatePreflight = {
174
180
  preflight_id: 'pf-001',
@@ -196,6 +202,10 @@ describe('system maintenance contracts', () => {
196
202
  };
197
203
 
198
204
  expect(version.installed_plugins[0]?.compatible).toBe(true);
205
+ expect(version.frameworks[0]?.version).toBe('8.4.1');
206
+ // An unreadable server version is listed with `null`, never dropped.
207
+ expect(version.frameworks[1]?.version).toBeNull();
208
+ expect(version.libraries[0]?.license).toBe('MIT');
199
209
  expect(preflight.status).toBe('ok');
200
210
  expect(status.progress_percent).toBe(42);
201
211
  });