@selfhelp/shared 1.0.3 → 1.0.5

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,906 @@
1
+ import { I as IStyleRegistryEntry } from '../styles.registry-C3bux91U.mjs';
2
+ import '../common-B96dASgu.mjs';
3
+
4
+ /**
5
+ * SDK contract version. Plugins declare which API they target in
6
+ * `plugin.json` under `pluginApiVersion`. The host installer compares
7
+ * declarations against this constant.
8
+ *
9
+ * Versioning rules:
10
+ * - patch (1.0.0 -> 1.0.1) — additive SDK fix, no contract change.
11
+ * - minor (1.0.x -> 1.1.0) — additive SDK feature.
12
+ * - major (1.x -> 2.0) — breaking SDK change.
13
+ *
14
+ * Independent from the npm `version` of `@selfhelp/shared`.
15
+ */
16
+ declare const PLUGIN_API_VERSION: "1.0";
17
+ interface ISemver {
18
+ major: number;
19
+ minor: number;
20
+ patch: number;
21
+ prerelease?: string;
22
+ }
23
+ declare function parseSemver(version: string): ISemver;
24
+ declare function compareSemver(a: string, b: string): number;
25
+ /**
26
+ * Very small npm-style range matcher supporting `=`, `>=`, `<=`, `>`,
27
+ * `<`, `^`, `~`, and the simple multi-clause syntax used by
28
+ * `plugin.json` compatibility fields. Not a full semver implementation;
29
+ * the backend uses Composer's resolver for actual install-time checks.
30
+ */
31
+ declare function satisfiesSemverRange(version: string, range: string): boolean;
32
+ /**
33
+ * Non-throwing version of {@see assertPluginApiVersion} — returns true
34
+ * when the plugin's declared `pluginApiVersion` is compatible with the
35
+ * host SDK. Used by the frontend `PluginRuntime` so an incompatible
36
+ * plugin is skipped (and logged) instead of crashing the host shell.
37
+ */
38
+ declare function isPluginApiCompatible(required: string, host?: string): boolean;
39
+ /**
40
+ * Throw if the plugin's required `pluginApiVersion` is not compatible
41
+ * with this SDK's `PLUGIN_API_VERSION`. SDK promises:
42
+ * - same major required.
43
+ * - host minor >= plugin's required minor.
44
+ */
45
+ declare function assertPluginApiVersion(required: string): void;
46
+ /**
47
+ * Throw if the running CMS version is not in the plugin's declared
48
+ * compatibility range.
49
+ */
50
+ declare function assertCmsCompatibility(cmsVersion: string, range: string): void;
51
+ /**
52
+ * Enforce the plugin version-semantics rule:
53
+ * - patch (1.0.0 -> 1.0.1) -- no DB change, no migration shipped.
54
+ * - minor (1.0.x -> 1.1.0) -- always carries a DB change/migration.
55
+ * - major (1.x -> 2.x) -- breaking change.
56
+ *
57
+ * The host installer + plugin CI call this with the lock-file `version`
58
+ * and the candidate `version` to verify that what is being shipped
59
+ * matches the semver bump.
60
+ */
61
+ declare function assertPluginVersionSemantics(prevVersion: string | undefined, nextVersion: string, options: {
62
+ hasMigration: boolean;
63
+ }): void;
64
+
65
+ /**
66
+ * TypeScript mirror of `plugin.json` (the schema lives in
67
+ * `sh-selfhelp_backend/docs/plugins/plugin-manifest.schema.json`). When
68
+ * the JSON Schema changes, update these types and bump the
69
+ * `@selfhelp/shared` minor version.
70
+ */
71
+ type IPluginManifestTrustLevel = 'official' | 'reviewed' | 'untrusted';
72
+ /** Every privileged capability is deny-by-default. */
73
+ type IPluginManifestCapability = 'backendBundle' | 'databaseMigrations' | 'readUsers' | 'writeUsers' | 'deleteUsers' | 'readDataTables' | 'writeDataTables' | 'deleteDataTables' | 'externalNetworkAccess' | 'scheduledJobs' | 'publicCallbacks' | 'adminPages' | 'frontendStyles' | 'mobileStyles' | 'realtimePublish' | 'fileUploads' | 'secretAccess' | 'lookupExtend' | 'lookupOwnGroup';
74
+ interface IPluginManifestCompatibility {
75
+ /** SemVer range for the SelfHelp CMS version (e.g. `^2.0`). */
76
+ selfhelp: string;
77
+ /** SemVer range for PHP runtime. */
78
+ php?: string;
79
+ /** SemVer range for Node runtime. */
80
+ node?: string;
81
+ /** SemVer range for React (web). */
82
+ react?: string;
83
+ /** SemVer range for React Native (mobile). */
84
+ reactNative?: string;
85
+ /** SemVer range for Expo SDK. */
86
+ expoSdk?: string;
87
+ }
88
+ interface IPluginManifestDependency {
89
+ /** Plugin id this plugin requires. */
90
+ pluginId: string;
91
+ /** Required SemVer range. */
92
+ version: string;
93
+ /** Optional / required dependency. */
94
+ required: boolean;
95
+ /**
96
+ * When `required: false`, the plugin still works without the dep
97
+ * but enables additional features when present.
98
+ */
99
+ featureFlag?: string;
100
+ }
101
+ interface IPluginManifestConflict {
102
+ pluginId: string;
103
+ /** SemVer range that conflicts. */
104
+ version: string;
105
+ reason: string;
106
+ }
107
+ interface IPluginManifestExternalHost {
108
+ /** Wildcards allowed, e.g. `cdn.example.com` or `*.example.com`. */
109
+ host: string;
110
+ /** What is loaded — `script`, `style`, `font`, `image`, `iframe`, `fetch`. */
111
+ type: 'script' | 'style' | 'font' | 'image' | 'iframe' | 'fetch';
112
+ /** Reason for the external host (shown in admin UI). */
113
+ reason: string;
114
+ }
115
+ interface IPluginManifestSecurity {
116
+ trustLevel: IPluginManifestTrustLevel;
117
+ capabilities: IPluginManifestCapability[];
118
+ /** CSP rules the installer must add (only for `trustLevel !== 'untrusted'`). */
119
+ cspRules?: {
120
+ /** Maps a CSP directive to extra sources. */
121
+ [directive: string]: string[];
122
+ };
123
+ /** External hosts the plugin will load assets/data from. */
124
+ externalHosts?: IPluginManifestExternalHost[];
125
+ /** Path to file containing checksum/signature, optional. */
126
+ signaturePath?: string;
127
+ }
128
+ interface IPluginManifestDataAccess {
129
+ /**
130
+ * Tables the plugin reads. May be `dataTable:*` for any plugin-owned
131
+ * data table, `lookup:<typeCode>` for lookup reads, `dataTable:my`
132
+ * for tables created by this plugin.
133
+ */
134
+ read?: string[];
135
+ /** Tables the plugin writes. */
136
+ write?: string[];
137
+ /** Tables the plugin deletes (rare; requires capability). */
138
+ delete?: string[];
139
+ }
140
+ interface IPluginManifestRealtimeTopic {
141
+ /** Topic key, scoped to this plugin. Example: `survey-response`. */
142
+ key: string;
143
+ /** Human description shown in admin UI. */
144
+ description: string;
145
+ /** Permission required to subscribe; resolved via `PluginRealtimePermissionResolver`. */
146
+ requiredPermission?: string;
147
+ /** JSON Schema path of the topic payload. */
148
+ payloadSchemaPath?: string;
149
+ }
150
+ interface IPluginManifestFeatureFlag {
151
+ key: string;
152
+ description: string;
153
+ /** Default state when no `plugin_feature_flags` row exists. */
154
+ defaultEnabled: boolean;
155
+ /** Optional capability gate; flag cannot be turned on without it. */
156
+ capability?: IPluginManifestCapability;
157
+ }
158
+ interface IPluginManifestLookupExtension {
159
+ /** Lookup type code, e.g. `survey_question_type`. */
160
+ typeCode: string;
161
+ /** Whether the plugin OWNS the type code or only extends it. */
162
+ ownership: 'plugin_extendable' | 'plugin_owned';
163
+ entries: {
164
+ code: string;
165
+ value: string;
166
+ description?: string;
167
+ }[];
168
+ }
169
+ interface IPluginManifestPermission {
170
+ /** Permission key, namespaced like `surveyjs.surveys.manage`. */
171
+ key: string;
172
+ description: string;
173
+ /** Optional default role keys the permission is granted to. */
174
+ defaultRoles?: string[];
175
+ }
176
+ interface IPluginManifestStyle {
177
+ /** Style name (used as `style_name` discriminator). */
178
+ name: string;
179
+ description: string;
180
+ canHaveChildren: boolean;
181
+ /** Optional capability requirement (e.g. `frontendStyles`). */
182
+ capability?: IPluginManifestCapability;
183
+ }
184
+ interface IPluginManifestAdminPage {
185
+ /** Slug under `/admin/plugins-host/{pluginId}/`. */
186
+ slug: string;
187
+ /** Menu label. */
188
+ label: string;
189
+ /** Required permission key. */
190
+ permission: string;
191
+ /** Optional menu icon (Tabler icon name). */
192
+ icon?: string;
193
+ }
194
+ interface IPluginManifestApiRoute {
195
+ /** Symfony route name (must be namespaced with the plugin id). */
196
+ name: string;
197
+ /** HTTP path under `/cms-api/v1/plugins/{pluginId}/...`. */
198
+ path: string;
199
+ methods: ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE')[];
200
+ /** Permission key required. */
201
+ permission?: string;
202
+ }
203
+ interface IPluginManifestScheduledJob {
204
+ /** Job type key. */
205
+ type: string;
206
+ description: string;
207
+ /** Capability gate (always requires `scheduledJobs`). */
208
+ capability: 'scheduledJobs';
209
+ }
210
+ interface IPluginManifestAsset {
211
+ /** Source path within the plugin package. */
212
+ src: string;
213
+ /** Destination path under `/assets/plugins/{pluginId}/...`. */
214
+ dest: string;
215
+ /** Asset type. */
216
+ type: 'script' | 'style' | 'font' | 'image' | 'other';
217
+ }
218
+ interface IPluginManifestHealth {
219
+ /** Optional health-check endpoint name. */
220
+ endpoint?: string;
221
+ /** Health-check service id (resolved through Symfony). */
222
+ serviceId?: string;
223
+ }
224
+ interface IPluginManifestMobile {
225
+ /** npm package name of the mobile component bundle. */
226
+ package: string;
227
+ /** Required SemVer range. */
228
+ version: string;
229
+ /** Whether the mobile package only renders payloads (readonly). */
230
+ readonly: boolean;
231
+ }
232
+ /**
233
+ * Full `plugin.json` shape.
234
+ */
235
+ interface IPluginManifest {
236
+ /** Plugin identifier, e.g. `sh2-shp-survey-js`. */
237
+ id: string;
238
+ /** Human-readable display name. */
239
+ name: string;
240
+ /** Short description. */
241
+ description?: string;
242
+ /** Plugin SemVer version. */
243
+ version: string;
244
+ /** Author / vendor. */
245
+ author?: {
246
+ name: string;
247
+ email?: string;
248
+ url?: string;
249
+ };
250
+ /** SPDX license id. */
251
+ license?: string;
252
+ /** Plugin homepage / repo URL. */
253
+ homepage?: string;
254
+ /** SDK contract version the plugin targets (e.g. `1.0`). */
255
+ pluginApiVersion: string;
256
+ /** Compatibility with the host stack. */
257
+ compatibility: IPluginManifestCompatibility;
258
+ /** Required + optional plugin dependencies. */
259
+ dependencies?: IPluginManifestDependency[];
260
+ /** Plugin conflicts. */
261
+ conflicts?: IPluginManifestConflict[];
262
+ /** Composer package (only for `trustLevel !== 'untrusted'`). */
263
+ backend?: {
264
+ package: string;
265
+ bundleClass: string;
266
+ migrationsNamespace?: string;
267
+ };
268
+ /** npm package for frontend. */
269
+ frontend?: {
270
+ package: string;
271
+ version: string;
272
+ };
273
+ /** Optional mobile package. */
274
+ mobile?: IPluginManifestMobile;
275
+ /** Required security declarations. */
276
+ security: IPluginManifestSecurity;
277
+ /** Permissions the plugin contributes. */
278
+ permissions?: IPluginManifestPermission[];
279
+ /** Manifest-declared data access. */
280
+ dataAccess?: IPluginManifestDataAccess;
281
+ /** Realtime topics. */
282
+ realtimeTopics?: IPluginManifestRealtimeTopic[];
283
+ /** Feature flags. */
284
+ featureFlags?: IPluginManifestFeatureFlag[];
285
+ /** Lookup contributions. */
286
+ lookups?: {
287
+ extends?: IPluginManifestLookupExtension[];
288
+ };
289
+ /** Styles contributed to the registry. */
290
+ styles?: IPluginManifestStyle[];
291
+ /** Admin pages mounted under `/admin/plugins-host/{pluginId}/`. */
292
+ adminPages?: IPluginManifestAdminPage[];
293
+ /** Plugin-owned API routes. */
294
+ apiRoutes?: IPluginManifestApiRoute[];
295
+ /** Scheduled jobs. */
296
+ scheduledJobs?: IPluginManifestScheduledJob[];
297
+ /** Vendored assets. */
298
+ assets?: IPluginManifestAsset[];
299
+ /** Health-check declaration. */
300
+ health?: IPluginManifestHealth;
301
+ /** Optional metadata / labels. */
302
+ labels?: Record<string, string>;
303
+ }
304
+
305
+ /**
306
+ * TypeScript mirror of `registry.json` served by a plugin registry.
307
+ * The host installer fetches registries (public and private), merges
308
+ * per-channel metadata, and shows update availability + changelogs in
309
+ * the admin UI.
310
+ */
311
+ type TPluginRegistryChannel = 'stable' | 'beta' | 'alpha' | 'nightly';
312
+ interface IPluginRegistryVersionEntry {
313
+ /** SemVer version. */
314
+ version: string;
315
+ /** Channel this version was published to. */
316
+ channel: TPluginRegistryChannel;
317
+ /** ISO datetime the version was published. */
318
+ publishedAt: string;
319
+ /** Whether this version is a breaking change vs the previous one. */
320
+ breaking?: boolean;
321
+ /** Whether the host installer should block this version. */
322
+ blocked?: boolean;
323
+ /** Optional reason for `blocked: true`. */
324
+ blockedReason?: string;
325
+ /** Composer / npm tarball or git source URL. */
326
+ sources: {
327
+ backend?: {
328
+ type: 'composer' | 'git';
329
+ package?: string;
330
+ ref?: string;
331
+ url?: string;
332
+ };
333
+ frontend?: {
334
+ type: 'npm' | 'git';
335
+ package?: string;
336
+ url?: string;
337
+ };
338
+ mobile?: {
339
+ type: 'npm' | 'git';
340
+ package?: string;
341
+ url?: string;
342
+ };
343
+ };
344
+ /** SHA-256 checksum of the published artifact. */
345
+ checksumSha256: string;
346
+ /** Optional Ed25519 signature, base64. */
347
+ signatureEd25519?: string;
348
+ /** Compatibility metadata mirrored from the manifest. */
349
+ compatibility: {
350
+ selfhelp: string;
351
+ php?: string;
352
+ node?: string;
353
+ react?: string;
354
+ reactNative?: string;
355
+ expoSdk?: string;
356
+ pluginApiVersion: string;
357
+ };
358
+ /** Plain-text changelog. Markdown supported. */
359
+ changelog?: string;
360
+ /** Mirror of `dependencies` from the manifest, for resolver-only consumption. */
361
+ dependencies?: {
362
+ pluginId: string;
363
+ version: string;
364
+ required: boolean;
365
+ }[];
366
+ }
367
+ interface IPluginRegistryEntry {
368
+ /** Plugin id (e.g. `sh2-shp-survey-js`). */
369
+ id: string;
370
+ /** Display name. */
371
+ name: string;
372
+ /** Short description. */
373
+ description?: string;
374
+ /** Homepage / repo URL. */
375
+ homepage?: string;
376
+ /** Trust level published by the registry. */
377
+ trustLevel: 'official' | 'reviewed' | 'untrusted';
378
+ /** Available versions. */
379
+ versions: IPluginRegistryVersionEntry[];
380
+ /** Optional public icon URL. */
381
+ iconUrl?: string;
382
+ /** Optional categories. */
383
+ categories?: string[];
384
+ }
385
+ /**
386
+ * Registry root document.
387
+ *
388
+ * Mirrors `plugin-registry.schema.json`. The schema document calls the
389
+ * version field `registryVersion` (integer, bumped only on breaking
390
+ * registry-document changes); we keep the legacy `schemaVersion` field
391
+ * as a compatibility alias so existing consumers do not break.
392
+ */
393
+ interface IPluginRegistry {
394
+ /** Registry schema generation. Bumped only on breaking registry-document changes. */
395
+ registryVersion: number;
396
+ /** Registry display name. */
397
+ name: string;
398
+ /** Registry homepage / maintainer URL. */
399
+ homepage?: string;
400
+ /** ISO timestamp this registry was published. */
401
+ publishedAt?: string;
402
+ /** Public key used to verify per-version signatures. */
403
+ trustKey?: {
404
+ algo: 'ed25519';
405
+ publicKeyId: string;
406
+ publicKey: string;
407
+ };
408
+ /** Channels this registry exposes (subset of stable/beta/alpha/nightly). */
409
+ channels?: TPluginRegistryChannel[];
410
+ /** Listed plugins. */
411
+ plugins: IPluginRegistryEntry[];
412
+ }
413
+
414
+ /**
415
+ * TypeScript mirror of `selfhelp.plugins.lock.json`. This file lives at
416
+ * the project root of the backend deployment and is the deterministic
417
+ * source of truth for which plugin versions are installed, what migrations
418
+ * ran, which checksums are pinned, and what mobile packages each EAS
419
+ * profile bundles.
420
+ *
421
+ * The lock file is written atomically by the install/update command. It
422
+ * is NEVER edited by hand.
423
+ */
424
+ interface IPluginLockMigration {
425
+ /** Doctrine migration class name. */
426
+ className: string;
427
+ /** Migration file SHA-256 hash, recorded for tamper detection. */
428
+ sha256: string;
429
+ /** ISO datetime the migration was executed. */
430
+ executedAt: string;
431
+ /** Whether `down()` is declared safe by the plugin. */
432
+ safeDown: boolean;
433
+ }
434
+ interface IPluginLockMobileEntry {
435
+ /** EAS profile name (e.g. `production-default`, `production-bern`). */
436
+ profile: string;
437
+ /** npm package + version that this profile bundles for the plugin. */
438
+ package: string;
439
+ version: string;
440
+ }
441
+ interface IPluginLockEntry {
442
+ /** Plugin id. */
443
+ id: string;
444
+ /** Pinned plugin version (the manifest version that was installed). */
445
+ version: string;
446
+ /** SDK contract version the plugin targets. */
447
+ pluginApiVersion: string;
448
+ /** Trust level recorded at install time. */
449
+ trustLevel: 'official' | 'reviewed' | 'untrusted';
450
+ /** Capabilities granted at install time. */
451
+ capabilities: string[];
452
+ /** Source descriptor that produced the install. */
453
+ source: {
454
+ kind: 'public-registry' | 'private-registry' | 'git' | 'local';
455
+ url?: string;
456
+ gitSha?: string;
457
+ registryUrl?: string;
458
+ };
459
+ /** Backend Composer package + version, if any. */
460
+ backend?: {
461
+ package: string;
462
+ version: string;
463
+ bundleClass: string;
464
+ };
465
+ /** Frontend npm package + version, if any. */
466
+ frontend?: {
467
+ package: string;
468
+ version: string;
469
+ };
470
+ /** Per-EAS-profile mobile package pin. */
471
+ mobile?: IPluginLockMobileEntry[];
472
+ /** SHA-256 checksum of the published artifact. */
473
+ checksumSha256: string;
474
+ /** Optional Ed25519 signature, base64. */
475
+ signatureEd25519?: string;
476
+ /** Hashes of every migration this plugin has executed. */
477
+ migrations: IPluginLockMigration[];
478
+ /** Plugin-owned style names contributed at install time. */
479
+ ownedStyles: string[];
480
+ /** Plugin-owned API route names contributed at install time. */
481
+ ownedApiRoutes: string[];
482
+ /** Plugin-owned realtime topics contributed at install time. */
483
+ ownedRealtimeTopics: string[];
484
+ /** Plugin-owned lookup type codes (`plugin_owned`) contributed at install time. */
485
+ ownedLookupTypeCodes: string[];
486
+ /** Feature flags shipped with the plugin and their default state. */
487
+ featureFlags: {
488
+ key: string;
489
+ defaultEnabled: boolean;
490
+ }[];
491
+ /** Whether the plugin is currently enabled. */
492
+ enabled: boolean;
493
+ /** ISO datetime of the install/update event. */
494
+ installedAt: string;
495
+ /** ISO datetime of the last update. */
496
+ updatedAt: string;
497
+ /** Optional notes that the installer wants to surface. */
498
+ notes?: string;
499
+ }
500
+ /**
501
+ * Root document of `selfhelp.plugins.lock.json`.
502
+ *
503
+ * Mirrors `plugin-lock.schema.json`. The schema requires
504
+ * `lockfileVersion`, `generatedAt`, `sdk`, and `plugins`. The schema
505
+ * stores plugins as a keyed object (`{ [pluginId]: lockedPlugin }`),
506
+ * but for typed consumers we expose it as an array of entries plus the
507
+ * keyed object so both shapes are usable.
508
+ */
509
+ interface IPluginLock {
510
+ /** Lock-file schema generation. Bumped only on breaking changes. */
511
+ lockfileVersion: number;
512
+ /** ISO datetime the lock file was last written. */
513
+ generatedAt: string;
514
+ /** SDK contract pin captured at write time. */
515
+ sdk: {
516
+ /** SemVer of the `@selfhelp/shared` package that wrote this file. */
517
+ version: string;
518
+ /** Plugin API version the host honors at write time. */
519
+ pluginApiVersion: string;
520
+ };
521
+ /**
522
+ * Installed plugins keyed by plugin id. Each entry follows
523
+ * `IPluginLockEntry`. The schema stores this as an object, not an
524
+ * array, so iteration order is undefined.
525
+ */
526
+ plugins: Record<string, IPluginLockEntry>;
527
+ /**
528
+ * Optional install mode hint, preserved for tooling that already
529
+ * read it from earlier lock-file revisions.
530
+ */
531
+ installMode?: 'development' | 'managed' | 'trusted';
532
+ }
533
+
534
+ /**
535
+ * Runtime types used by `definePlugin()` / `defineMobilePlugin()` calls.
536
+ *
537
+ * Plugins are loaded by `PluginRuntime` at boot. The runtime imports the
538
+ * plugin's npm package, calls its exported `register()` function and
539
+ * passes it an `IPluginApi` instance. The plugin returns an
540
+ * `IPluginRegistration` describing what it contributes (styles, admin
541
+ * pages, menu items, health checks, etc.).
542
+ *
543
+ * Frontend (`react`) and mobile (`react-native`) plugins share most of
544
+ * the surface; mobile-only types are suffixed with `Mobile`.
545
+ */
546
+
547
+ /**
548
+ * Generic component renderer. We avoid pulling in React types here to
549
+ * keep the SDK framework-agnostic; the runtime casts to the appropriate
550
+ * component type at registration time.
551
+ */
552
+ type TPluginComponent<TProps = unknown> = (props: TProps) => unknown;
553
+ /**
554
+ * Definition of a CMS style contributed by a plugin.
555
+ */
556
+ interface IStyleDefinition extends Omit<IStyleRegistryEntry, 'category'> {
557
+ /** Style name (becomes the `style_name` discriminator). */
558
+ name: string;
559
+ /**
560
+ * Category. Plugins should usually pick `'plugin'`, but may opt into
561
+ * an existing category (e.g. `'forms'`) when the style is a
562
+ * drop-in replacement.
563
+ */
564
+ category: IStyleRegistryEntry['category'];
565
+ /** Style implementation component (React or React Native). */
566
+ component: TPluginComponent;
567
+ }
568
+ /**
569
+ * Admin page contributed by a plugin. Mounted under
570
+ * `/admin/plugins-host/{pluginId}/{slug}` in the frontend.
571
+ */
572
+ interface IAdminPageDefinition {
573
+ /** URL slug relative to the host shell. */
574
+ slug: string;
575
+ /** Display title in tabs / breadcrumbs. */
576
+ title: string;
577
+ /** Required permission key. */
578
+ permission?: string;
579
+ /** Page component (React). */
580
+ component: TPluginComponent;
581
+ /** Optional preloader hook called during SSR/prefetch. */
582
+ prefetch?: () => Promise<void>;
583
+ }
584
+ /**
585
+ * Menu item contributed by a plugin.
586
+ */
587
+ interface IMenuItemDefinition {
588
+ /** Stable key. */
589
+ key: string;
590
+ /** Display label. */
591
+ label: string;
592
+ /** Optional Tabler icon name. */
593
+ icon?: string;
594
+ /** Target href; defaults to the admin page slug. */
595
+ href?: string;
596
+ /** Required permission key. */
597
+ permission?: string;
598
+ /** Position relative to existing host menus. */
599
+ position?: {
600
+ section: 'admin' | 'cms' | 'tools';
601
+ order: number;
602
+ };
603
+ }
604
+ /**
605
+ * Health-check declaration. Invoked through the doctor command and the
606
+ * Plugin detail page's Health tab.
607
+ */
608
+ interface IPluginHealthCheck {
609
+ /** Stable key (e.g. `surveyjs.license`). */
610
+ key: string;
611
+ /** Display label. */
612
+ label: string;
613
+ /** Optional severity threshold. */
614
+ severity?: 'info' | 'warning' | 'error';
615
+ /** Runs the check; returns ok/warn/error + detail. */
616
+ run: () => Promise<{
617
+ status: 'ok' | 'warn' | 'error';
618
+ detail?: string;
619
+ }>;
620
+ }
621
+ /**
622
+ * Feature-flag declaration. The host installer seeds the flag based on
623
+ * `defaultEnabled`; admins toggle through the Plugin detail page.
624
+ */
625
+ interface IPluginFeatureFlag {
626
+ key: string;
627
+ label: string;
628
+ description?: string;
629
+ defaultEnabled: boolean;
630
+ }
631
+ /**
632
+ * Realtime topic declared by the plugin. Wraps Mercure topics under the
633
+ * scoped path `selfhelp/plugin/{pluginId}/{topicKey}`. Plugins never
634
+ * talk to Mercure directly.
635
+ */
636
+ interface IPluginRealtimeTopic<TPayload = unknown> {
637
+ /** Topic key, unique within the plugin. */
638
+ key: string;
639
+ /** Optional permission required to subscribe. */
640
+ requiredPermission?: string;
641
+ /**
642
+ * Optional payload validator. Receives the SSE event data and must
643
+ * either return the typed payload or throw. The SDK runs this on
644
+ * the receiving side; the publisher runs the same validator before
645
+ * publishing.
646
+ */
647
+ validate?: (raw: unknown) => TPayload;
648
+ }
649
+ /**
650
+ * Realtime publisher exposed to plugin server-side code (mostly inside
651
+ * the plugin's Symfony bundle). Plugins must never instantiate Mercure
652
+ * clients directly.
653
+ */
654
+ interface IPluginRealtimePublisher {
655
+ /** Publish a payload to a topic registered by the plugin. */
656
+ publish<TPayload>(topicKey: string, payload: TPayload, options?: {
657
+ /** Audience scope. Defaults to `permission`. */
658
+ audience?: 'permission' | 'broadcast' | 'admins';
659
+ /** Per-publish topic parameters (e.g. survey id). */
660
+ topicParams?: Record<string, string | number>;
661
+ }): Promise<void>;
662
+ }
663
+ /**
664
+ * Rich text editor adapter. Both the SurveyJS plugin's `rich-text`
665
+ * question type and the CMS core's `rich-text-editor` style consume
666
+ * this adapter so a single Tiptap-based editor backs both.
667
+ *
668
+ * Plugins must provide a sanitization step on the backend; this
669
+ * adapter only owns the editor UI.
670
+ */
671
+ interface IRichTextEditorAdapterOptions {
672
+ /** Optional editor mode hint. */
673
+ mode?: 'inline' | 'block';
674
+ /**
675
+ * Allowed format for the stored value:
676
+ * - `markdown` — string of Markdown.
677
+ * - `sanitized-html` — HTML string passed through DOMPurify on the
678
+ * backend.
679
+ * - `prosemirror-json` — JSON shape produced by Tiptap.
680
+ */
681
+ format: 'markdown' | 'sanitized-html' | 'prosemirror-json';
682
+ /** Optional toolbar restriction. */
683
+ toolbar?: ('bold' | 'italic' | 'underline' | 'strike' | 'code' | 'link' | 'heading' | 'bulletList' | 'orderedList' | 'blockquote' | 'image')[];
684
+ /** Whether to allow image upload. */
685
+ allowImages?: boolean;
686
+ /** Whether to allow links. */
687
+ allowLinks?: boolean;
688
+ /** Custom placeholder text. */
689
+ placeholder?: string;
690
+ }
691
+ interface IRichTextEditorValue {
692
+ /** Versioned format token, matches the adapter `format`. */
693
+ format: 'markdown' | 'sanitized-html' | 'prosemirror-json';
694
+ /** Stringified content (Markdown / HTML) or stringified JSON. */
695
+ content: string;
696
+ }
697
+ /**
698
+ * The host-side editor adapter passed to plugins through `IPluginApi`.
699
+ */
700
+ interface IRichTextEditorAdapter {
701
+ /**
702
+ * Mount the editor at the given DOM node (web) or component node
703
+ * (mobile) with the initial value. The returned object exposes a
704
+ * setter and a destroyer.
705
+ */
706
+ mount(target: unknown, options: IRichTextEditorAdapterOptions & {
707
+ initialValue?: IRichTextEditorValue;
708
+ onChange?: (value: IRichTextEditorValue) => void;
709
+ }): {
710
+ setValue(value: IRichTextEditorValue): void;
711
+ destroy(): void;
712
+ };
713
+ }
714
+ /**
715
+ * Host API passed to plugins at registration time.
716
+ */
717
+ interface IPluginApi {
718
+ /** Plugin id (provided by the host so the plugin does not duplicate it). */
719
+ pluginId: string;
720
+ /** Plugin version, mirrored from the manifest. */
721
+ pluginVersion: string;
722
+ /** Live feature-flag accessor. */
723
+ isFeatureEnabled(flagKey: string): boolean;
724
+ /** Host realtime publisher (only available on the backend side). */
725
+ realtime?: IPluginRealtimePublisher;
726
+ /** Host rich-text editor adapter. */
727
+ richTextEditor: IRichTextEditorAdapter;
728
+ /**
729
+ * Logger that respects the host's debug config. Avoid `console.log`
730
+ * in plugin code; route everything through this.
731
+ */
732
+ log: {
733
+ debug(message: string, context?: Record<string, unknown>): void;
734
+ info(message: string, context?: Record<string, unknown>): void;
735
+ warn(message: string, context?: Record<string, unknown>): void;
736
+ error(message: string, context?: Record<string, unknown>): void;
737
+ };
738
+ }
739
+ /**
740
+ * Same shape on mobile, minus the rich-text editor adapter when the
741
+ * plugin only supports read-only mobile rendering.
742
+ */
743
+ interface IMobilePluginApi extends Omit<IPluginApi, 'richTextEditor'> {
744
+ /** Mobile builds without rich-text support set this to `null`. */
745
+ richTextEditor: IRichTextEditorAdapter | null;
746
+ }
747
+ /**
748
+ * Returned by `definePlugin()` for the frontend / admin side of a
749
+ * plugin.
750
+ */
751
+ interface IPluginRegistration {
752
+ /** Plugin id, must match the manifest. */
753
+ id: string;
754
+ /** Plugin version, must match the manifest. */
755
+ version: string;
756
+ /** SDK contract version the plugin targets. */
757
+ pluginApiVersion: string;
758
+ /** CMS styles the plugin contributes. */
759
+ styles?: IStyleDefinition[];
760
+ /** Admin pages the plugin contributes. */
761
+ adminPages?: IAdminPageDefinition[];
762
+ /** Menu items the plugin contributes. */
763
+ menuItems?: IMenuItemDefinition[];
764
+ /** Health checks the plugin exposes to the host. */
765
+ healthChecks?: IPluginHealthCheck[];
766
+ /** Feature flags the plugin declares. */
767
+ featureFlags?: IPluginFeatureFlag[];
768
+ /** Realtime topics the plugin publishes / subscribes to. */
769
+ realtimeTopics?: IPluginRealtimeTopic[];
770
+ }
771
+ /**
772
+ * Returned by `defineMobilePlugin()` for the mobile side of a plugin.
773
+ */
774
+ interface IMobilePluginRegistration {
775
+ id: string;
776
+ version: string;
777
+ pluginApiVersion: string;
778
+ /** Mobile-only style implementations. */
779
+ styles?: IStyleDefinition[];
780
+ /** Mobile-only realtime topics. */
781
+ realtimeTopics?: IPluginRealtimeTopic[];
782
+ /** Mobile feature flags (mirror of the manifest flags). */
783
+ featureFlags?: IPluginFeatureFlag[];
784
+ }
785
+
786
+ /**
787
+ * `definePlugin()` / `defineMobilePlugin()` are the only entry points
788
+ * plugins call. They validate the SDK version, register style entries
789
+ * in the shared registry, and return the registration object the host
790
+ * `PluginRuntime` reads.
791
+ */
792
+
793
+ /**
794
+ * Plugin frontend / admin entry point.
795
+ *
796
+ * Example:
797
+ * export const register = definePlugin({
798
+ * id: 'sh2-shp-survey-js',
799
+ * version: '1.0.0',
800
+ * pluginApiVersion: '1.0',
801
+ * styles: [{ name: 'surveyjs', component: SurveyJsStyle, ... }],
802
+ * });
803
+ */
804
+ declare function definePlugin(registration: IPluginRegistration): IPluginRegistration;
805
+ /**
806
+ * Plugin mobile entry point. Same contract as `definePlugin()` but
807
+ * mobile-only. Mobile builds bundle plugin packages per EAS profile,
808
+ * so this runs inside the mobile Metro bundle at app boot.
809
+ */
810
+ declare function defineMobilePlugin(registration: IMobilePluginRegistration): IMobilePluginRegistration;
811
+ /**
812
+ * Declare a realtime topic for type-safe publish/subscribe. Returns the
813
+ * topic descriptor; the host installer registers it through
814
+ * `PluginRealtimeTopicRegistryEvent` so admins can audit topics in the
815
+ * Plugin detail page.
816
+ */
817
+ declare function definePluginRealtimeTopic<TPayload>(descriptor: IPluginRealtimeTopic<TPayload>): IPluginRealtimeTopic<TPayload>;
818
+
819
+ /**
820
+ * `usePluginRealtime` — universal React hook for plugin Mercure topic
821
+ * subscription.
822
+ *
823
+ * Implements the contract laid out in the plan section 10 "Realtime
824
+ * infrastructure & no-polling policy":
825
+ *
826
+ * const { data, isOnline, lastEventAt, error } = usePluginRealtime<TPayload>({
827
+ * pluginId: 'sh2-shp-survey-js',
828
+ * topic: 'surveys/{surveyId}/responses',
829
+ * topicParams: { surveyId: 42 },
830
+ * });
831
+ *
832
+ * The hook:
833
+ *
834
+ * - opens a same-origin `EventSource` against
835
+ * `/api/plugins/events?pluginId=…&topic=…` (the host BFF route),
836
+ * - listens for messages on the requested topic event-name,
837
+ * - exposes the latest payload + connection state,
838
+ * - reconnects with exponential backoff on transient errors,
839
+ * - is a no-op in environments without `EventSource` (server / RN).
840
+ *
841
+ * Mobile apps must inject their own `react-native-sse`-backed
842
+ * implementation through the optional `transportFactory` argument;
843
+ * this keeps the shared SDK free of React Native imports while still
844
+ * letting the same plugin code re-use the same hook signature on web
845
+ * and on device. The mobile package documents the wrapper.
846
+ *
847
+ * IMPORTANT: this hook never polls. If `EventSource` cannot connect, it
848
+ * surfaces `isOnline = false` and the consumer is expected to show an
849
+ * "offline" banner — not to set up a `setInterval` fallback.
850
+ */
851
+ /**
852
+ * Subset of the WHATWG `EventSource` API the hook actually relies on.
853
+ * Declared inline so the SDK does not pull DOM types into projects that
854
+ * disable `dom` (e.g. some Expo TypeScript setups).
855
+ */
856
+ interface IRealtimeTransport {
857
+ addEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
858
+ removeEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
859
+ close(): void;
860
+ readyState: number;
861
+ }
862
+ type TRealtimeTransportFactory = (url: string) => IRealtimeTransport;
863
+ interface IUsePluginRealtimeOptions<TPayload = unknown> {
864
+ /** Plugin id (`plugin.json#id`). */
865
+ pluginId: string;
866
+ /** Topic key as declared in the manifest (e.g. `surveys/{surveyId}/responses`). */
867
+ topic: string;
868
+ /** Values that fill the `{placeholders}` in `topic`. */
869
+ topicParams?: Record<string, string | number>;
870
+ /** Disable subscription without unmounting the consumer. */
871
+ enabled?: boolean;
872
+ /**
873
+ * Override the SSE endpoint. Defaults to `/api/plugins/events`. The
874
+ * host BFF proxies it through to Symfony's per-plugin Mercure
875
+ * bootstrap so the subscriber JWT never reaches the browser.
876
+ */
877
+ endpoint?: string;
878
+ /**
879
+ * Optional transport factory. Used by the mobile package to plug in
880
+ * `react-native-sse` (or any other SSE-compatible client) without
881
+ * pulling RN imports into the shared SDK.
882
+ */
883
+ transportFactory?: TRealtimeTransportFactory;
884
+ /** Parser for the event payload. Defaults to `JSON.parse`. */
885
+ parse?: (raw: string) => TPayload;
886
+ }
887
+ interface IUsePluginRealtimeResult<TPayload = unknown> {
888
+ /** Latest payload emitted on the topic, or `null` before the first event. */
889
+ data: TPayload | null;
890
+ /** `true` once the SSE handshake has succeeded for the current subscription. */
891
+ isOnline: boolean;
892
+ /** Wall-clock time of the last successful event, or `null`. */
893
+ lastEventAt: Date | null;
894
+ /** Most recent transport-level error, or `null` when healthy. */
895
+ error: Error | null;
896
+ }
897
+ /**
898
+ * Subscribe a React/React-Native component to one Mercure plugin topic
899
+ * and re-render whenever a new payload arrives.
900
+ *
901
+ * Returns `{ data, isOnline, lastEventAt, error }`. Always cleans up on
902
+ * unmount and on prop change.
903
+ */
904
+ declare function usePluginRealtime<TPayload = unknown>(options: IUsePluginRealtimeOptions<TPayload>): IUsePluginRealtimeResult<TPayload>;
905
+
906
+ export { type IAdminPageDefinition, type IMenuItemDefinition, type IMobilePluginApi, type IMobilePluginRegistration, type IPluginApi, type IPluginFeatureFlag, type IPluginHealthCheck, type IPluginLock, type IPluginLockEntry, type IPluginLockMigration, type IPluginLockMobileEntry, type IPluginManifest, type IPluginManifestAdminPage, type IPluginManifestApiRoute, type IPluginManifestAsset, type IPluginManifestCapability, type IPluginManifestCompatibility, type IPluginManifestConflict, type IPluginManifestDataAccess, type IPluginManifestDependency, type IPluginManifestExternalHost, type IPluginManifestFeatureFlag, type IPluginManifestHealth, type IPluginManifestLookupExtension, type IPluginManifestMobile, type IPluginManifestPermission, type IPluginManifestRealtimeTopic, type IPluginManifestScheduledJob, type IPluginManifestSecurity, type IPluginManifestStyle, type IPluginManifestTrustLevel, type IPluginRealtimePublisher, type IPluginRealtimeTopic, type IPluginRegistration, type IPluginRegistry, type IPluginRegistryEntry, type IPluginRegistryVersionEntry, type IRealtimeTransport, type IRichTextEditorAdapter, type IRichTextEditorAdapterOptions, type IRichTextEditorValue, type IStyleDefinition, type IUsePluginRealtimeOptions, type IUsePluginRealtimeResult, PLUGIN_API_VERSION, type TPluginRegistryChannel, type TRealtimeTransportFactory, assertCmsCompatibility, assertPluginApiVersion, assertPluginVersionSemantics, compareSemver, defineMobilePlugin, definePlugin, definePluginRealtimeTopic, isPluginApiCompatible, parseSemver, satisfiesSemverRange, usePluginRealtime };