@selfhelp/shared 1.3.0 → 1.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +349 -341
  2. package/LICENSE +381 -381
  3. package/README.md +57 -57
  4. package/package.json +102 -102
  5. package/src/api/__tests__/endpoints.test.ts +45 -45
  6. package/src/api/index.ts +5 -5
  7. package/src/assets/__tests__/resolveAssetUrl.test.ts +61 -61
  8. package/src/assets/index.ts +5 -5
  9. package/src/assets/resolveAssetUrl.ts +44 -44
  10. package/src/cms-classes/__tests__/classify.test.ts +63 -63
  11. package/src/cms-classes/allow-list.ts +158 -158
  12. package/src/cms-classes/classify.ts +90 -90
  13. package/src/cms-classes/index.ts +7 -7
  14. package/src/cms-classes/remap.ts +44 -44
  15. package/src/condition/__tests__/evaluate.test.ts +54 -54
  16. package/src/condition/evaluate.ts +121 -121
  17. package/src/condition/index.ts +5 -5
  18. package/src/index.ts +25 -25
  19. package/src/interpolation/__tests__/replaceCalcedValues.test.ts +41 -41
  20. package/src/interpolation/index.ts +5 -5
  21. package/src/interpolation/replaceCalcedValues.ts +27 -27
  22. package/src/plugin-sdk/define.ts +89 -89
  23. package/src/plugin-sdk/index.ts +103 -103
  24. package/src/plugin-sdk/lock.ts +124 -124
  25. package/src/plugin-sdk/manifest.ts +307 -307
  26. package/src/plugin-sdk/realtime.ts +277 -277
  27. package/src/plugin-sdk/registry.ts +105 -105
  28. package/src/plugin-sdk/runtime-shim.ts +140 -140
  29. package/src/plugin-sdk/types.ts +315 -315
  30. package/src/plugin-sdk/version.ts +209 -209
  31. package/src/registry/__tests__/registry.test.ts +135 -135
  32. package/src/registry/index.ts +94 -94
  33. package/src/registry/styles.registry.ts +295 -295
  34. package/src/testing/__tests__/testing-kit.test.ts +228 -228
  35. package/src/testing/index.ts +483 -483
  36. package/src/theme/index.ts +6 -6
  37. package/src/theme/tailwind.ts +73 -73
  38. package/src/theme/tokens.ts +177 -177
  39. package/src/types/api/envelope.ts +34 -34
  40. package/src/types/api/forms.ts +76 -76
  41. package/src/types/api/index.ts +9 -9
  42. package/src/types/api/language.ts +12 -12
  43. package/src/types/api/page.ts +9 -9
  44. package/src/types/index.ts +17 -17
  45. package/src/types/mantine/common.ts +142 -142
  46. package/src/types/pages.ts +107 -107
  47. package/src/types/styles/auth.ts +184 -184
  48. package/src/types/styles/base.ts +72 -72
  49. package/src/types/styles/composite.ts +131 -131
  50. package/src/types/styles/forms.ts +439 -439
  51. package/src/types/styles/interactive.ts +165 -165
  52. package/src/types/styles/layout.ts +184 -184
  53. package/src/types/styles/media.ts +68 -68
  54. package/src/types/styles/typography.ts +118 -118
  55. package/src/types/styles/unknown.ts +220 -220
  56. package/src/utils/__tests__/transformPageData.test.ts +69 -69
  57. package/src/utils/spacing.ts +64 -64
  58. package/src/utils/transformPageData.ts +99 -99
@@ -1,483 +1,483 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- /**
6
- * `@selfhelp/shared/testing` — the plugin certification kit.
7
- *
8
- * Every plugin's certification suite imports from this subpath so the
9
- * "standard suite every plugin must pass" stays identical across plugins
10
- * (canonical Testing Rule: plugin certification).
11
- *
12
- * Scope: this kit performs the **static manifest certification** — pure,
13
- * deterministic checks a plugin's CI (and any TS consumer) can run against a
14
- * parsed `plugin.json` without a database or a running host:
15
- *
16
- * - manifest-valid required fields + semver/version-format sanity
17
- * - capabilities-vs-trust-level known capabilities, trust-level limits,
18
- * and declared-surface ↔ capability completeness
19
- * - compatibility-shape the adopted single-range compatibility shape
20
- * - lookup-ownership lookup extension ownership + entries
21
- * - db-naming owned table / data-table-prefix naming rules
22
- *
23
- * The **runtime** lifecycle (install → update → rollback → uninstall → purge,
24
- * realtime-topic registration, cleanup) is enforced by the backend host
25
- * certification (`tests/Certification/*` + `PluginCapabilityValidator` /
26
- * `PluginApiRouteSynchronizer` etc.), not here — a TS unit kit cannot install a
27
- * Composer package or run Doctrine migrations. The two layers are
28
- * complementary: this kit gates the manifest before publishing; the host gates
29
- * the actual install.
30
- *
31
- * Checks are built on the existing plugin SDK (`IPluginManifest`, the capability
32
- * union, and the semver helpers) so the kit never re-implements manifest typing
33
- * or range parsing.
34
- */
35
-
36
- import {
37
- parseSemver,
38
- type IPluginManifest,
39
- type IPluginManifestCapability,
40
- } from '../plugin-sdk';
41
-
42
- /** Version of the certification kit contract (asserted by a stability test). */
43
- export const CERTIFICATION_KIT_VERSION = '1.0.0';
44
-
45
- // ---------------------------------------------------------------------------
46
- // Check result + report shapes
47
- // ---------------------------------------------------------------------------
48
-
49
- export interface ICertificationCheckResult {
50
- /** Stable check name (one of {@link CERTIFICATION_CHECKS}). */
51
- readonly name: string;
52
- readonly passed: boolean;
53
- /** Human-readable failures; empty when the check passed. */
54
- readonly errors: readonly string[];
55
- }
56
-
57
- export interface IPluginCertificationReport {
58
- readonly pluginId: string;
59
- readonly kitVersion: string;
60
- /** True only when every check passed. */
61
- readonly passed: boolean;
62
- readonly results: readonly ICertificationCheckResult[];
63
- }
64
-
65
- // ---------------------------------------------------------------------------
66
- // definePluginCertification — declares + runs the standard certification suite.
67
- // ---------------------------------------------------------------------------
68
-
69
- export interface IPluginCertificationConfig {
70
- /** Plugin id under test, e.g. `sh2-shp-survey-js`. */
71
- pluginId: string;
72
- /** Path to the plugin's `plugin.json` manifest (for reporter context). */
73
- manifestPath?: string;
74
- /** Path to the lock file the certification seeds from. */
75
- lockFilePath?: string;
76
- /** Capabilities the plugin declares; the runner asserts they are granted. */
77
- capabilities?: readonly string[];
78
- /** Mercure topics the plugin owns; verified through {@link mockMercureHub}. */
79
- realtimeTopics?: readonly string[];
80
- }
81
-
82
- export interface IPluginCertificationSuite {
83
- readonly pluginId: string;
84
- readonly kitVersion: string;
85
- readonly config: IPluginCertificationConfig;
86
- /** The ordered static checks every plugin manifest must pass. */
87
- readonly checks: readonly string[];
88
- /** Run all static checks against a parsed manifest and return a report. */
89
- run(manifest: IPluginManifest): IPluginCertificationReport;
90
- }
91
-
92
- /** The canonical, ordered certification checks (names are the stable contract). */
93
- export const CERTIFICATION_CHECKS: readonly string[] = [
94
- 'manifest-valid',
95
- 'capabilities-vs-trust-level',
96
- 'compatibility-shape',
97
- 'lookup-ownership',
98
- 'db-naming',
99
- ];
100
-
101
- /** Every privileged capability the host knows about (mirrors the manifest schema enum). */
102
- const KNOWN_CAPABILITIES: ReadonlySet<string> = new Set<IPluginManifestCapability>([
103
- 'backendBundle',
104
- 'databaseMigrations',
105
- 'readUsers',
106
- 'writeUsers',
107
- 'deleteUsers',
108
- 'readDataTables',
109
- 'writeDataTables',
110
- 'deleteDataTables',
111
- 'externalNetworkAccess',
112
- 'scheduledJobs',
113
- 'publicCallbacks',
114
- 'adminPages',
115
- 'frontendStyles',
116
- 'mobileStyles',
117
- 'realtimePublish',
118
- 'fileUploads',
119
- 'secretAccess',
120
- 'lookupExtend',
121
- 'lookupOwnGroup',
122
- ]);
123
-
124
- /**
125
- * Capabilities an `untrusted` plugin may NOT declare (AGENTS.md: untrusted
126
- * plugins cannot ship a bundle, migrations, scheduled jobs, direct user/data
127
- * access, secrets, or outbound network).
128
- */
129
- const UNTRUSTED_FORBIDDEN_CAPABILITIES: readonly string[] = [
130
- 'backendBundle',
131
- 'databaseMigrations',
132
- 'scheduledJobs',
133
- 'readUsers',
134
- 'writeUsers',
135
- 'deleteUsers',
136
- 'readDataTables',
137
- 'writeDataTables',
138
- 'deleteDataTables',
139
- 'secretAccess',
140
- 'externalNetworkAccess',
141
- ];
142
-
143
- const COMPATIBILITY_KEYS: readonly string[] = ['selfhelp', 'php', 'node', 'react', 'reactNative', 'expoSdk'];
144
- const OWNED_TABLE_PATTERN = /^[a-z][a-z0-9_]*$/;
145
- const OWNED_PREFIX_PATTERN = /^[a-z][a-z0-9_]*_$/;
146
- const PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*$/;
147
- const PLUGIN_API_VERSION_PATTERN = /^\d+\.\d+$/;
148
-
149
- /**
150
- * A single npm-style range token: optional operator + a partial-or-full
151
- * version (e.g. `^8.4`, `>=8.0.0-dev`, `<9.0.0`, `~1.2.0`, `*`). Intentionally
152
- * tolerant of the partial `major` / `major.minor` forms plugins use for
153
- * platform ranges — this validates the SHAPE, not exact resolvability (the
154
- * backend's Composer resolver does the real check at install time).
155
- */
156
- const RANGE_TOKEN_PATTERN = /^(\*|x|(\^|~|>=|<=|>|<|=)?\d+(\.\d+)?(\.\d+)?(-[0-9A-Za-z.-]+)?)$/;
157
-
158
- function makeResult(name: string, errors: string[]): ICertificationCheckResult {
159
- return { name, passed: errors.length === 0, errors };
160
- }
161
-
162
- /** True when every clause/token of `range` looks like an npm-style range. */
163
- function isValidRange(range: string): boolean {
164
- const clauses = range.split('||').map((c) => c.trim()).filter((c) => c !== '');
165
- if (clauses.length === 0) {
166
- return false;
167
- }
168
- return clauses.every((clause) =>
169
- clause
170
- .split(/\s+/)
171
- .filter((t) => t !== '')
172
- .every((token) => RANGE_TOKEN_PATTERN.test(token)),
173
- );
174
- }
175
-
176
- function asCapabilityList(manifest: IPluginManifest): string[] {
177
- const caps = manifest.security?.capabilities;
178
- return Array.isArray(caps) ? caps.map((c) => String(c)) : [];
179
- }
180
-
181
- /** manifest-valid: required fields are present and well-formed. */
182
- export function checkManifestValid(manifest: IPluginManifest): ICertificationCheckResult {
183
- const errors: string[] = [];
184
-
185
- if (!manifest.id || typeof manifest.id !== 'string') {
186
- errors.push('id is required.');
187
- } else if (!PLUGIN_ID_PATTERN.test(manifest.id)) {
188
- errors.push(`id '${manifest.id}' must match ${PLUGIN_ID_PATTERN}.`);
189
- }
190
-
191
- if (!manifest.name || typeof manifest.name !== 'string') {
192
- errors.push('name is required.');
193
- }
194
-
195
- if (!manifest.version || typeof manifest.version !== 'string') {
196
- errors.push('version is required.');
197
- } else {
198
- try {
199
- parseSemver(manifest.version);
200
- } catch {
201
- errors.push(`version '${manifest.version}' is not valid semver.`);
202
- }
203
- }
204
-
205
- if (!manifest.pluginApiVersion || typeof manifest.pluginApiVersion !== 'string') {
206
- errors.push('pluginApiVersion is required.');
207
- } else if (!PLUGIN_API_VERSION_PATTERN.test(manifest.pluginApiVersion)) {
208
- errors.push(`pluginApiVersion '${manifest.pluginApiVersion}' must look like '<major>.<minor>'.`);
209
- }
210
-
211
- if (!manifest.compatibility || typeof manifest.compatibility !== 'object') {
212
- errors.push('compatibility is required.');
213
- }
214
-
215
- if (!manifest.security || typeof manifest.security !== 'object') {
216
- errors.push('security is required.');
217
- } else {
218
- if (!manifest.security.trustLevel) {
219
- errors.push('security.trustLevel is required.');
220
- }
221
- if (!Array.isArray(manifest.security.capabilities)) {
222
- errors.push('security.capabilities must be an array.');
223
- }
224
- }
225
-
226
- return makeResult('manifest-valid', errors);
227
- }
228
-
229
- /**
230
- * capabilities-vs-trust-level: capabilities are known, respect the trust-level
231
- * limits, and every declared surface has the capability that gates it.
232
- */
233
- export function checkCapabilitiesVsTrustLevel(manifest: IPluginManifest): ICertificationCheckResult {
234
- const errors: string[] = [];
235
- const caps = asCapabilityList(manifest);
236
- const capSet = new Set(caps);
237
- const trustLevel = manifest.security?.trustLevel;
238
-
239
- for (const cap of caps) {
240
- if (!KNOWN_CAPABILITIES.has(cap)) {
241
- errors.push(`unknown capability '${cap}'.`);
242
- }
243
- }
244
-
245
- if (trustLevel === 'untrusted') {
246
- for (const cap of UNTRUSTED_FORBIDDEN_CAPABILITIES) {
247
- if (capSet.has(cap)) {
248
- errors.push(`untrusted plugins may not declare capability '${cap}'.`);
249
- }
250
- }
251
- }
252
-
253
- const require = (condition: boolean, capability: string, surface: string): void => {
254
- if (condition && !capSet.has(capability)) {
255
- errors.push(`${surface} requires the '${capability}' capability.`);
256
- }
257
- };
258
-
259
- require(Boolean(manifest.backend?.bundleClass), 'backendBundle', 'declaring a backend bundle');
260
- require(Boolean(manifest.backend?.migrationsNamespace), 'databaseMigrations', 'declaring a migrations namespace');
261
- require((manifest.scheduledJobs?.length ?? 0) > 0, 'scheduledJobs', 'declaring scheduled jobs');
262
- require((manifest.adminPages?.length ?? 0) > 0, 'adminPages', 'declaring admin pages');
263
- require((manifest.realtimeTopics?.length ?? 0) > 0, 'realtimePublish', 'declaring realtime topics');
264
-
265
- if ((manifest.styles?.length ?? 0) > 0 && !capSet.has('frontendStyles') && !capSet.has('mobileStyles')) {
266
- errors.push("declaring styles requires the 'frontendStyles' or 'mobileStyles' capability.");
267
- }
268
-
269
- for (const ext of manifest.lookups?.extends ?? []) {
270
- if (ext.ownership === 'plugin_owned') {
271
- require(true, 'lookupOwnGroup', `owning lookup group '${ext.typeCode}'`);
272
- } else if (ext.ownership === 'plugin_extendable') {
273
- require(true, 'lookupExtend', `extending lookup group '${ext.typeCode}'`);
274
- }
275
- }
276
-
277
- require((manifest.dataAccess?.write?.length ?? 0) > 0, 'writeDataTables', 'declaring data-table writes');
278
- require((manifest.dataAccess?.delete?.length ?? 0) > 0, 'deleteDataTables', 'declaring data-table deletes');
279
-
280
- return makeResult('capabilities-vs-trust-level', errors);
281
- }
282
-
283
- /**
284
- * compatibility-shape: the adopted single-range compatibility shape —
285
- * `compatibility.selfhelp` is a SemVer **range string** (not the rejected
286
- * per-surface object), with optional platform ranges, and no unknown keys.
287
- */
288
- export function checkCompatibilityShape(manifest: IPluginManifest): ICertificationCheckResult {
289
- const errors: string[] = [];
290
- const compatibility = manifest.compatibility as unknown as Record<string, unknown> | undefined;
291
-
292
- if (!compatibility || typeof compatibility !== 'object') {
293
- return makeResult('compatibility-shape', ['compatibility is required.']);
294
- }
295
-
296
- const selfhelp = compatibility.selfhelp;
297
- if (typeof selfhelp !== 'string') {
298
- errors.push(
299
- 'compatibility.selfhelp must be a SemVer range string (single-range shape), not an object or missing.',
300
- );
301
- } else if (selfhelp.trim() === '' || !isValidRange(selfhelp)) {
302
- errors.push(`compatibility.selfhelp '${selfhelp}' is not a valid SemVer range.`);
303
- }
304
-
305
- for (const key of Object.keys(compatibility)) {
306
- if (!COMPATIBILITY_KEYS.includes(key)) {
307
- errors.push(`compatibility has unknown key '${key}'.`);
308
- continue;
309
- }
310
- if (key === 'selfhelp') {
311
- continue;
312
- }
313
- const value = compatibility[key];
314
- if (typeof value !== 'string' || !isValidRange(value)) {
315
- errors.push(`compatibility.${key} must be a valid SemVer range string.`);
316
- }
317
- }
318
-
319
- return makeResult('compatibility-shape', errors);
320
- }
321
-
322
- /** lookup-ownership: lookup extensions declare a valid ownership + entries. */
323
- export function checkLookupOwnership(manifest: IPluginManifest): ICertificationCheckResult {
324
- const errors: string[] = [];
325
-
326
- for (const ext of manifest.lookups?.extends ?? []) {
327
- const label = ext.typeCode || '<missing typeCode>';
328
- if (!ext.typeCode) {
329
- errors.push('lookup extension is missing typeCode.');
330
- }
331
- if (ext.ownership !== 'plugin_owned' && ext.ownership !== 'plugin_extendable') {
332
- errors.push(`lookup '${label}' has invalid ownership '${String(ext.ownership)}'.`);
333
- }
334
- if (!Array.isArray(ext.entries) || ext.entries.length === 0) {
335
- errors.push(`lookup '${label}' must declare at least one entry.`);
336
- continue;
337
- }
338
- for (const entry of ext.entries) {
339
- if (!entry.code || !entry.value) {
340
- errors.push(`lookup '${label}' has an entry missing code/value.`);
341
- }
342
- }
343
- }
344
-
345
- return makeResult('lookup-ownership', errors);
346
- }
347
-
348
- /** db-naming: owned tables + data-table prefix follow lowercase_snake_case. */
349
- export function checkDbNaming(manifest: IPluginManifest): ICertificationCheckResult {
350
- const errors: string[] = [];
351
- const dataAccess = manifest.dataAccess;
352
-
353
- for (const table of dataAccess?.ownedTables ?? []) {
354
- if (!OWNED_TABLE_PATTERN.test(table)) {
355
- errors.push(`owned table '${table}' must be lowercase_snake_case (${OWNED_TABLE_PATTERN}).`);
356
- }
357
- }
358
-
359
- const prefix = dataAccess?.ownedDataTablePrefix;
360
- if (prefix !== undefined && prefix !== '' && !OWNED_PREFIX_PATTERN.test(prefix)) {
361
- errors.push(`ownedDataTablePrefix '${prefix}' must be lowercase_snake_case ending in '_' (${OWNED_PREFIX_PATTERN}).`);
362
- }
363
-
364
- return makeResult('db-naming', errors);
365
- }
366
-
367
- /** Run the full ordered static certification against a parsed manifest. */
368
- export function runCertificationChecks(manifest: IPluginManifest): ICertificationCheckResult[] {
369
- return [
370
- checkManifestValid(manifest),
371
- checkCapabilitiesVsTrustLevel(manifest),
372
- checkCompatibilityShape(manifest),
373
- checkLookupOwnership(manifest),
374
- checkDbNaming(manifest),
375
- ];
376
- }
377
-
378
- /**
379
- * Declare a plugin certification suite. The returned suite exposes the stable
380
- * ordered check names plus an executable {@link IPluginCertificationSuite.run}
381
- * that validates a parsed manifest and returns a typed report.
382
- */
383
- export function definePluginCertification(config: IPluginCertificationConfig): IPluginCertificationSuite {
384
- if (!config.pluginId || config.pluginId.trim() === '') {
385
- throw new Error('definePluginCertification: pluginId is required.');
386
- }
387
-
388
- return {
389
- pluginId: config.pluginId,
390
- kitVersion: CERTIFICATION_KIT_VERSION,
391
- config,
392
- checks: CERTIFICATION_CHECKS,
393
- run(manifest: IPluginManifest): IPluginCertificationReport {
394
- const results = runCertificationChecks(manifest);
395
- return {
396
- pluginId: config.pluginId,
397
- kitVersion: CERTIFICATION_KIT_VERSION,
398
- passed: results.every((r) => r.passed),
399
- results,
400
- };
401
- },
402
- };
403
- }
404
-
405
- // ---------------------------------------------------------------------------
406
- // mockMercureHub — in-memory Mercure recorder (mirrors backend MercureTestRecorder).
407
- // ---------------------------------------------------------------------------
408
-
409
- export interface IRecordedMercureUpdate {
410
- topic: string;
411
- data: unknown;
412
- }
413
-
414
- export interface IMockMercureHub {
415
- /** Record a publish call (drop-in for the real hub's publish). */
416
- publish(topic: string, data?: unknown): void;
417
- /** All recorded updates in publish order. */
418
- readonly updates: readonly IRecordedMercureUpdate[];
419
- /** Distinct topics that were published to. */
420
- publishedTopics(): string[];
421
- /** Number of updates published to a given topic. */
422
- countForTopic(topic: string): number;
423
- /** Clear all recorded updates (use in afterEach). */
424
- reset(): void;
425
- }
426
-
427
- /**
428
- * Create an in-memory Mercure hub spy. Plugins assert published topics /
429
- * payloads against it instead of polling a real hub (canonical Testing
430
- * Rule 13: Mercure verified via a recorder, never polling).
431
- */
432
- export function mockMercureHub(): IMockMercureHub {
433
- const updates: IRecordedMercureUpdate[] = [];
434
- return {
435
- updates,
436
- publish(topic: string, data: unknown = null): void {
437
- updates.push({ topic, data });
438
- },
439
- publishedTopics(): string[] {
440
- return [...new Set(updates.map((u) => u.topic))];
441
- },
442
- countForTopic(topic: string): number {
443
- return updates.filter((u) => u.topic === topic).length;
444
- },
445
- reset(): void {
446
- updates.length = 0;
447
- },
448
- };
449
- }
450
-
451
- // ---------------------------------------------------------------------------
452
- // seedFromLockFile — read installed-plugin info from a lock file (subset).
453
- // ---------------------------------------------------------------------------
454
-
455
- export interface ILockFilePluginEntry {
456
- pluginId: string;
457
- version: string;
458
- }
459
-
460
- export interface ILockFileSeed {
461
- plugins: ILockFilePluginEntry[];
462
- }
463
-
464
- /**
465
- * Parse the `plugins` map of a `selfhelp.plugins.lock.json` document into a
466
- * deterministic seed list. Tolerant of partial documents.
467
- */
468
- export function seedFromLockFile(lockJson: unknown): ILockFileSeed {
469
- const plugins: ILockFilePluginEntry[] = [];
470
- if (lockJson && typeof lockJson === 'object' && 'plugins' in lockJson) {
471
- const raw = (lockJson as { plugins: unknown }).plugins;
472
- if (raw && typeof raw === 'object') {
473
- for (const [pluginId, entry] of Object.entries(raw as Record<string, unknown>)) {
474
- const version =
475
- entry && typeof entry === 'object' && 'version' in entry
476
- ? String((entry as { version: unknown }).version)
477
- : '0.0.0';
478
- plugins.push({ pluginId, version });
479
- }
480
- }
481
- }
482
- return { plugins };
483
- }
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * `@selfhelp/shared/testing` — the plugin certification kit.
7
+ *
8
+ * Every plugin's certification suite imports from this subpath so the
9
+ * "standard suite every plugin must pass" stays identical across plugins
10
+ * (canonical Testing Rule: plugin certification).
11
+ *
12
+ * Scope: this kit performs the **static manifest certification** — pure,
13
+ * deterministic checks a plugin's CI (and any TS consumer) can run against a
14
+ * parsed `plugin.json` without a database or a running host:
15
+ *
16
+ * - manifest-valid required fields + semver/version-format sanity
17
+ * - capabilities-vs-trust-level known capabilities, trust-level limits,
18
+ * and declared-surface ↔ capability completeness
19
+ * - compatibility-shape the adopted single-range compatibility shape
20
+ * - lookup-ownership lookup extension ownership + entries
21
+ * - db-naming owned table / data-table-prefix naming rules
22
+ *
23
+ * The **runtime** lifecycle (install → update → rollback → uninstall → purge,
24
+ * realtime-topic registration, cleanup) is enforced by the backend host
25
+ * certification (`tests/Certification/*` + `PluginCapabilityValidator` /
26
+ * `PluginApiRouteSynchronizer` etc.), not here — a TS unit kit cannot install a
27
+ * Composer package or run Doctrine migrations. The two layers are
28
+ * complementary: this kit gates the manifest before publishing; the host gates
29
+ * the actual install.
30
+ *
31
+ * Checks are built on the existing plugin SDK (`IPluginManifest`, the capability
32
+ * union, and the semver helpers) so the kit never re-implements manifest typing
33
+ * or range parsing.
34
+ */
35
+
36
+ import {
37
+ parseSemver,
38
+ type IPluginManifest,
39
+ type IPluginManifestCapability,
40
+ } from '../plugin-sdk';
41
+
42
+ /** Version of the certification kit contract (asserted by a stability test). */
43
+ export const CERTIFICATION_KIT_VERSION = '1.0.0';
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Check result + report shapes
47
+ // ---------------------------------------------------------------------------
48
+
49
+ export interface ICertificationCheckResult {
50
+ /** Stable check name (one of {@link CERTIFICATION_CHECKS}). */
51
+ readonly name: string;
52
+ readonly passed: boolean;
53
+ /** Human-readable failures; empty when the check passed. */
54
+ readonly errors: readonly string[];
55
+ }
56
+
57
+ export interface IPluginCertificationReport {
58
+ readonly pluginId: string;
59
+ readonly kitVersion: string;
60
+ /** True only when every check passed. */
61
+ readonly passed: boolean;
62
+ readonly results: readonly ICertificationCheckResult[];
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // definePluginCertification — declares + runs the standard certification suite.
67
+ // ---------------------------------------------------------------------------
68
+
69
+ export interface IPluginCertificationConfig {
70
+ /** Plugin id under test, e.g. `sh2-shp-survey-js`. */
71
+ pluginId: string;
72
+ /** Path to the plugin's `plugin.json` manifest (for reporter context). */
73
+ manifestPath?: string;
74
+ /** Path to the lock file the certification seeds from. */
75
+ lockFilePath?: string;
76
+ /** Capabilities the plugin declares; the runner asserts they are granted. */
77
+ capabilities?: readonly string[];
78
+ /** Mercure topics the plugin owns; verified through {@link mockMercureHub}. */
79
+ realtimeTopics?: readonly string[];
80
+ }
81
+
82
+ export interface IPluginCertificationSuite {
83
+ readonly pluginId: string;
84
+ readonly kitVersion: string;
85
+ readonly config: IPluginCertificationConfig;
86
+ /** The ordered static checks every plugin manifest must pass. */
87
+ readonly checks: readonly string[];
88
+ /** Run all static checks against a parsed manifest and return a report. */
89
+ run(manifest: IPluginManifest): IPluginCertificationReport;
90
+ }
91
+
92
+ /** The canonical, ordered certification checks (names are the stable contract). */
93
+ export const CERTIFICATION_CHECKS: readonly string[] = [
94
+ 'manifest-valid',
95
+ 'capabilities-vs-trust-level',
96
+ 'compatibility-shape',
97
+ 'lookup-ownership',
98
+ 'db-naming',
99
+ ];
100
+
101
+ /** Every privileged capability the host knows about (mirrors the manifest schema enum). */
102
+ const KNOWN_CAPABILITIES: ReadonlySet<string> = new Set<IPluginManifestCapability>([
103
+ 'backendBundle',
104
+ 'databaseMigrations',
105
+ 'readUsers',
106
+ 'writeUsers',
107
+ 'deleteUsers',
108
+ 'readDataTables',
109
+ 'writeDataTables',
110
+ 'deleteDataTables',
111
+ 'externalNetworkAccess',
112
+ 'scheduledJobs',
113
+ 'publicCallbacks',
114
+ 'adminPages',
115
+ 'frontendStyles',
116
+ 'mobileStyles',
117
+ 'realtimePublish',
118
+ 'fileUploads',
119
+ 'secretAccess',
120
+ 'lookupExtend',
121
+ 'lookupOwnGroup',
122
+ ]);
123
+
124
+ /**
125
+ * Capabilities an `untrusted` plugin may NOT declare (AGENTS.md: untrusted
126
+ * plugins cannot ship a bundle, migrations, scheduled jobs, direct user/data
127
+ * access, secrets, or outbound network).
128
+ */
129
+ const UNTRUSTED_FORBIDDEN_CAPABILITIES: readonly string[] = [
130
+ 'backendBundle',
131
+ 'databaseMigrations',
132
+ 'scheduledJobs',
133
+ 'readUsers',
134
+ 'writeUsers',
135
+ 'deleteUsers',
136
+ 'readDataTables',
137
+ 'writeDataTables',
138
+ 'deleteDataTables',
139
+ 'secretAccess',
140
+ 'externalNetworkAccess',
141
+ ];
142
+
143
+ const COMPATIBILITY_KEYS: readonly string[] = ['selfhelp', 'php', 'node', 'react', 'reactNative', 'expoSdk'];
144
+ const OWNED_TABLE_PATTERN = /^[a-z][a-z0-9_]*$/;
145
+ const OWNED_PREFIX_PATTERN = /^[a-z][a-z0-9_]*_$/;
146
+ const PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*$/;
147
+ const PLUGIN_API_VERSION_PATTERN = /^\d+\.\d+$/;
148
+
149
+ /**
150
+ * A single npm-style range token: optional operator + a partial-or-full
151
+ * version (e.g. `^8.4`, `>=8.0.0-dev`, `<9.0.0`, `~1.2.0`, `*`). Intentionally
152
+ * tolerant of the partial `major` / `major.minor` forms plugins use for
153
+ * platform ranges — this validates the SHAPE, not exact resolvability (the
154
+ * backend's Composer resolver does the real check at install time).
155
+ */
156
+ const RANGE_TOKEN_PATTERN = /^(\*|x|(\^|~|>=|<=|>|<|=)?\d+(\.\d+)?(\.\d+)?(-[0-9A-Za-z.-]+)?)$/;
157
+
158
+ function makeResult(name: string, errors: string[]): ICertificationCheckResult {
159
+ return { name, passed: errors.length === 0, errors };
160
+ }
161
+
162
+ /** True when every clause/token of `range` looks like an npm-style range. */
163
+ function isValidRange(range: string): boolean {
164
+ const clauses = range.split('||').map((c) => c.trim()).filter((c) => c !== '');
165
+ if (clauses.length === 0) {
166
+ return false;
167
+ }
168
+ return clauses.every((clause) =>
169
+ clause
170
+ .split(/\s+/)
171
+ .filter((t) => t !== '')
172
+ .every((token) => RANGE_TOKEN_PATTERN.test(token)),
173
+ );
174
+ }
175
+
176
+ function asCapabilityList(manifest: IPluginManifest): string[] {
177
+ const caps = manifest.security?.capabilities;
178
+ return Array.isArray(caps) ? caps.map((c) => String(c)) : [];
179
+ }
180
+
181
+ /** manifest-valid: required fields are present and well-formed. */
182
+ export function checkManifestValid(manifest: IPluginManifest): ICertificationCheckResult {
183
+ const errors: string[] = [];
184
+
185
+ if (!manifest.id || typeof manifest.id !== 'string') {
186
+ errors.push('id is required.');
187
+ } else if (!PLUGIN_ID_PATTERN.test(manifest.id)) {
188
+ errors.push(`id '${manifest.id}' must match ${PLUGIN_ID_PATTERN}.`);
189
+ }
190
+
191
+ if (!manifest.name || typeof manifest.name !== 'string') {
192
+ errors.push('name is required.');
193
+ }
194
+
195
+ if (!manifest.version || typeof manifest.version !== 'string') {
196
+ errors.push('version is required.');
197
+ } else {
198
+ try {
199
+ parseSemver(manifest.version);
200
+ } catch {
201
+ errors.push(`version '${manifest.version}' is not valid semver.`);
202
+ }
203
+ }
204
+
205
+ if (!manifest.pluginApiVersion || typeof manifest.pluginApiVersion !== 'string') {
206
+ errors.push('pluginApiVersion is required.');
207
+ } else if (!PLUGIN_API_VERSION_PATTERN.test(manifest.pluginApiVersion)) {
208
+ errors.push(`pluginApiVersion '${manifest.pluginApiVersion}' must look like '<major>.<minor>'.`);
209
+ }
210
+
211
+ if (!manifest.compatibility || typeof manifest.compatibility !== 'object') {
212
+ errors.push('compatibility is required.');
213
+ }
214
+
215
+ if (!manifest.security || typeof manifest.security !== 'object') {
216
+ errors.push('security is required.');
217
+ } else {
218
+ if (!manifest.security.trustLevel) {
219
+ errors.push('security.trustLevel is required.');
220
+ }
221
+ if (!Array.isArray(manifest.security.capabilities)) {
222
+ errors.push('security.capabilities must be an array.');
223
+ }
224
+ }
225
+
226
+ return makeResult('manifest-valid', errors);
227
+ }
228
+
229
+ /**
230
+ * capabilities-vs-trust-level: capabilities are known, respect the trust-level
231
+ * limits, and every declared surface has the capability that gates it.
232
+ */
233
+ export function checkCapabilitiesVsTrustLevel(manifest: IPluginManifest): ICertificationCheckResult {
234
+ const errors: string[] = [];
235
+ const caps = asCapabilityList(manifest);
236
+ const capSet = new Set(caps);
237
+ const trustLevel = manifest.security?.trustLevel;
238
+
239
+ for (const cap of caps) {
240
+ if (!KNOWN_CAPABILITIES.has(cap)) {
241
+ errors.push(`unknown capability '${cap}'.`);
242
+ }
243
+ }
244
+
245
+ if (trustLevel === 'untrusted') {
246
+ for (const cap of UNTRUSTED_FORBIDDEN_CAPABILITIES) {
247
+ if (capSet.has(cap)) {
248
+ errors.push(`untrusted plugins may not declare capability '${cap}'.`);
249
+ }
250
+ }
251
+ }
252
+
253
+ const require = (condition: boolean, capability: string, surface: string): void => {
254
+ if (condition && !capSet.has(capability)) {
255
+ errors.push(`${surface} requires the '${capability}' capability.`);
256
+ }
257
+ };
258
+
259
+ require(Boolean(manifest.backend?.bundleClass), 'backendBundle', 'declaring a backend bundle');
260
+ require(Boolean(manifest.backend?.migrationsNamespace), 'databaseMigrations', 'declaring a migrations namespace');
261
+ require((manifest.scheduledJobs?.length ?? 0) > 0, 'scheduledJobs', 'declaring scheduled jobs');
262
+ require((manifest.adminPages?.length ?? 0) > 0, 'adminPages', 'declaring admin pages');
263
+ require((manifest.realtimeTopics?.length ?? 0) > 0, 'realtimePublish', 'declaring realtime topics');
264
+
265
+ if ((manifest.styles?.length ?? 0) > 0 && !capSet.has('frontendStyles') && !capSet.has('mobileStyles')) {
266
+ errors.push("declaring styles requires the 'frontendStyles' or 'mobileStyles' capability.");
267
+ }
268
+
269
+ for (const ext of manifest.lookups?.extends ?? []) {
270
+ if (ext.ownership === 'plugin_owned') {
271
+ require(true, 'lookupOwnGroup', `owning lookup group '${ext.typeCode}'`);
272
+ } else if (ext.ownership === 'plugin_extendable') {
273
+ require(true, 'lookupExtend', `extending lookup group '${ext.typeCode}'`);
274
+ }
275
+ }
276
+
277
+ require((manifest.dataAccess?.write?.length ?? 0) > 0, 'writeDataTables', 'declaring data-table writes');
278
+ require((manifest.dataAccess?.delete?.length ?? 0) > 0, 'deleteDataTables', 'declaring data-table deletes');
279
+
280
+ return makeResult('capabilities-vs-trust-level', errors);
281
+ }
282
+
283
+ /**
284
+ * compatibility-shape: the adopted single-range compatibility shape —
285
+ * `compatibility.selfhelp` is a SemVer **range string** (not the rejected
286
+ * per-surface object), with optional platform ranges, and no unknown keys.
287
+ */
288
+ export function checkCompatibilityShape(manifest: IPluginManifest): ICertificationCheckResult {
289
+ const errors: string[] = [];
290
+ const compatibility = manifest.compatibility as unknown as Record<string, unknown> | undefined;
291
+
292
+ if (!compatibility || typeof compatibility !== 'object') {
293
+ return makeResult('compatibility-shape', ['compatibility is required.']);
294
+ }
295
+
296
+ const selfhelp = compatibility.selfhelp;
297
+ if (typeof selfhelp !== 'string') {
298
+ errors.push(
299
+ 'compatibility.selfhelp must be a SemVer range string (single-range shape), not an object or missing.',
300
+ );
301
+ } else if (selfhelp.trim() === '' || !isValidRange(selfhelp)) {
302
+ errors.push(`compatibility.selfhelp '${selfhelp}' is not a valid SemVer range.`);
303
+ }
304
+
305
+ for (const key of Object.keys(compatibility)) {
306
+ if (!COMPATIBILITY_KEYS.includes(key)) {
307
+ errors.push(`compatibility has unknown key '${key}'.`);
308
+ continue;
309
+ }
310
+ if (key === 'selfhelp') {
311
+ continue;
312
+ }
313
+ const value = compatibility[key];
314
+ if (typeof value !== 'string' || !isValidRange(value)) {
315
+ errors.push(`compatibility.${key} must be a valid SemVer range string.`);
316
+ }
317
+ }
318
+
319
+ return makeResult('compatibility-shape', errors);
320
+ }
321
+
322
+ /** lookup-ownership: lookup extensions declare a valid ownership + entries. */
323
+ export function checkLookupOwnership(manifest: IPluginManifest): ICertificationCheckResult {
324
+ const errors: string[] = [];
325
+
326
+ for (const ext of manifest.lookups?.extends ?? []) {
327
+ const label = ext.typeCode || '<missing typeCode>';
328
+ if (!ext.typeCode) {
329
+ errors.push('lookup extension is missing typeCode.');
330
+ }
331
+ if (ext.ownership !== 'plugin_owned' && ext.ownership !== 'plugin_extendable') {
332
+ errors.push(`lookup '${label}' has invalid ownership '${String(ext.ownership)}'.`);
333
+ }
334
+ if (!Array.isArray(ext.entries) || ext.entries.length === 0) {
335
+ errors.push(`lookup '${label}' must declare at least one entry.`);
336
+ continue;
337
+ }
338
+ for (const entry of ext.entries) {
339
+ if (!entry.code || !entry.value) {
340
+ errors.push(`lookup '${label}' has an entry missing code/value.`);
341
+ }
342
+ }
343
+ }
344
+
345
+ return makeResult('lookup-ownership', errors);
346
+ }
347
+
348
+ /** db-naming: owned tables + data-table prefix follow lowercase_snake_case. */
349
+ export function checkDbNaming(manifest: IPluginManifest): ICertificationCheckResult {
350
+ const errors: string[] = [];
351
+ const dataAccess = manifest.dataAccess;
352
+
353
+ for (const table of dataAccess?.ownedTables ?? []) {
354
+ if (!OWNED_TABLE_PATTERN.test(table)) {
355
+ errors.push(`owned table '${table}' must be lowercase_snake_case (${OWNED_TABLE_PATTERN}).`);
356
+ }
357
+ }
358
+
359
+ const prefix = dataAccess?.ownedDataTablePrefix;
360
+ if (prefix !== undefined && prefix !== '' && !OWNED_PREFIX_PATTERN.test(prefix)) {
361
+ errors.push(`ownedDataTablePrefix '${prefix}' must be lowercase_snake_case ending in '_' (${OWNED_PREFIX_PATTERN}).`);
362
+ }
363
+
364
+ return makeResult('db-naming', errors);
365
+ }
366
+
367
+ /** Run the full ordered static certification against a parsed manifest. */
368
+ export function runCertificationChecks(manifest: IPluginManifest): ICertificationCheckResult[] {
369
+ return [
370
+ checkManifestValid(manifest),
371
+ checkCapabilitiesVsTrustLevel(manifest),
372
+ checkCompatibilityShape(manifest),
373
+ checkLookupOwnership(manifest),
374
+ checkDbNaming(manifest),
375
+ ];
376
+ }
377
+
378
+ /**
379
+ * Declare a plugin certification suite. The returned suite exposes the stable
380
+ * ordered check names plus an executable {@link IPluginCertificationSuite.run}
381
+ * that validates a parsed manifest and returns a typed report.
382
+ */
383
+ export function definePluginCertification(config: IPluginCertificationConfig): IPluginCertificationSuite {
384
+ if (!config.pluginId || config.pluginId.trim() === '') {
385
+ throw new Error('definePluginCertification: pluginId is required.');
386
+ }
387
+
388
+ return {
389
+ pluginId: config.pluginId,
390
+ kitVersion: CERTIFICATION_KIT_VERSION,
391
+ config,
392
+ checks: CERTIFICATION_CHECKS,
393
+ run(manifest: IPluginManifest): IPluginCertificationReport {
394
+ const results = runCertificationChecks(manifest);
395
+ return {
396
+ pluginId: config.pluginId,
397
+ kitVersion: CERTIFICATION_KIT_VERSION,
398
+ passed: results.every((r) => r.passed),
399
+ results,
400
+ };
401
+ },
402
+ };
403
+ }
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // mockMercureHub — in-memory Mercure recorder (mirrors backend MercureTestRecorder).
407
+ // ---------------------------------------------------------------------------
408
+
409
+ export interface IRecordedMercureUpdate {
410
+ topic: string;
411
+ data: unknown;
412
+ }
413
+
414
+ export interface IMockMercureHub {
415
+ /** Record a publish call (drop-in for the real hub's publish). */
416
+ publish(topic: string, data?: unknown): void;
417
+ /** All recorded updates in publish order. */
418
+ readonly updates: readonly IRecordedMercureUpdate[];
419
+ /** Distinct topics that were published to. */
420
+ publishedTopics(): string[];
421
+ /** Number of updates published to a given topic. */
422
+ countForTopic(topic: string): number;
423
+ /** Clear all recorded updates (use in afterEach). */
424
+ reset(): void;
425
+ }
426
+
427
+ /**
428
+ * Create an in-memory Mercure hub spy. Plugins assert published topics /
429
+ * payloads against it instead of polling a real hub (canonical Testing
430
+ * Rule 13: Mercure verified via a recorder, never polling).
431
+ */
432
+ export function mockMercureHub(): IMockMercureHub {
433
+ const updates: IRecordedMercureUpdate[] = [];
434
+ return {
435
+ updates,
436
+ publish(topic: string, data: unknown = null): void {
437
+ updates.push({ topic, data });
438
+ },
439
+ publishedTopics(): string[] {
440
+ return [...new Set(updates.map((u) => u.topic))];
441
+ },
442
+ countForTopic(topic: string): number {
443
+ return updates.filter((u) => u.topic === topic).length;
444
+ },
445
+ reset(): void {
446
+ updates.length = 0;
447
+ },
448
+ };
449
+ }
450
+
451
+ // ---------------------------------------------------------------------------
452
+ // seedFromLockFile — read installed-plugin info from a lock file (subset).
453
+ // ---------------------------------------------------------------------------
454
+
455
+ export interface ILockFilePluginEntry {
456
+ pluginId: string;
457
+ version: string;
458
+ }
459
+
460
+ export interface ILockFileSeed {
461
+ plugins: ILockFilePluginEntry[];
462
+ }
463
+
464
+ /**
465
+ * Parse the `plugins` map of a `selfhelp.plugins.lock.json` document into a
466
+ * deterministic seed list. Tolerant of partial documents.
467
+ */
468
+ export function seedFromLockFile(lockJson: unknown): ILockFileSeed {
469
+ const plugins: ILockFilePluginEntry[] = [];
470
+ if (lockJson && typeof lockJson === 'object' && 'plugins' in lockJson) {
471
+ const raw = (lockJson as { plugins: unknown }).plugins;
472
+ if (raw && typeof raw === 'object') {
473
+ for (const [pluginId, entry] of Object.entries(raw as Record<string, unknown>)) {
474
+ const version =
475
+ entry && typeof entry === 'object' && 'version' in entry
476
+ ? String((entry as { version: unknown }).version)
477
+ : '0.0.0';
478
+ plugins.push({ pluginId, version });
479
+ }
480
+ }
481
+ }
482
+ return { plugins };
483
+ }