@selfhelp/shared 1.0.1 → 1.0.4

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,490 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/plugin-sdk/index.ts
21
+ var plugin_sdk_exports = {};
22
+ __export(plugin_sdk_exports, {
23
+ PLUGIN_API_VERSION: () => PLUGIN_API_VERSION,
24
+ assertCmsCompatibility: () => assertCmsCompatibility,
25
+ assertPluginApiVersion: () => assertPluginApiVersion,
26
+ assertPluginVersionSemantics: () => assertPluginVersionSemantics,
27
+ compareSemver: () => compareSemver,
28
+ defineMobilePlugin: () => defineMobilePlugin,
29
+ definePlugin: () => definePlugin,
30
+ definePluginRealtimeTopic: () => definePluginRealtimeTopic,
31
+ isPluginApiCompatible: () => isPluginApiCompatible,
32
+ parseSemver: () => parseSemver,
33
+ satisfiesSemverRange: () => satisfiesSemverRange,
34
+ usePluginRealtime: () => usePluginRealtime
35
+ });
36
+ module.exports = __toCommonJS(plugin_sdk_exports);
37
+
38
+ // src/plugin-sdk/version.ts
39
+ var PLUGIN_API_VERSION = "1.0";
40
+ var SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
41
+ function parseSemver(version) {
42
+ const match = SEMVER_REGEX.exec(version);
43
+ if (!match) {
44
+ throw new Error(`[plugin-sdk] not a valid semver: '${version}'.`);
45
+ }
46
+ return {
47
+ major: Number(match[1]),
48
+ minor: Number(match[2]),
49
+ patch: Number(match[3]),
50
+ prerelease: match[4]
51
+ };
52
+ }
53
+ function compareSemver(a, b) {
54
+ const pa = parseSemver(a);
55
+ const pb = parseSemver(b);
56
+ if (pa.major !== pb.major) return pa.major - pb.major;
57
+ if (pa.minor !== pb.minor) return pa.minor - pb.minor;
58
+ if (pa.patch !== pb.patch) return pa.patch - pb.patch;
59
+ if (pa.prerelease && pb.prerelease) return pa.prerelease.localeCompare(pb.prerelease);
60
+ if (pa.prerelease) return -1;
61
+ if (pb.prerelease) return 1;
62
+ return 0;
63
+ }
64
+ function satisfiesSemverRange(version, range) {
65
+ const v = parseSemver(version);
66
+ return range.split("||").some((clause) => clause.trim().split(/\s+/).every((part) => matchSingle(v, part.trim())));
67
+ }
68
+ function matchSingle(v, part) {
69
+ if (!part) return true;
70
+ if (part === "*" || part === "x") return true;
71
+ if (part.startsWith("^")) {
72
+ const target = parseSemver(part.slice(1));
73
+ if (target.major === 0) {
74
+ if (target.minor === 0) return v.major === 0 && v.minor === 0 && v.patch === target.patch;
75
+ return v.major === 0 && v.minor === target.minor && (v.patch > target.patch || v.patch === target.patch && !v.prerelease);
76
+ }
77
+ return v.major === target.major && compareSemverObj(v, target) >= 0;
78
+ }
79
+ if (part.startsWith("~")) {
80
+ const target = parseSemver(part.slice(1));
81
+ return v.major === target.major && v.minor === target.minor && v.patch >= target.patch;
82
+ }
83
+ if (part.startsWith(">=")) return compareSemverObj(v, parseSemver(part.slice(2).trim())) >= 0;
84
+ if (part.startsWith("<=")) return compareSemverObj(v, parseSemver(part.slice(2).trim())) <= 0;
85
+ if (part.startsWith(">")) return compareSemverObj(v, parseSemver(part.slice(1).trim())) > 0;
86
+ if (part.startsWith("<")) return compareSemverObj(v, parseSemver(part.slice(1).trim())) < 0;
87
+ if (part.startsWith("=")) return compareSemverObj(v, parseSemver(part.slice(1).trim())) === 0;
88
+ return compareSemverObj(v, parseSemver(part)) === 0;
89
+ }
90
+ function compareSemverObj(a, b) {
91
+ if (a.major !== b.major) return a.major - b.major;
92
+ if (a.minor !== b.minor) return a.minor - b.minor;
93
+ if (a.patch !== b.patch) return a.patch - b.patch;
94
+ if (a.prerelease && b.prerelease) return a.prerelease.localeCompare(b.prerelease);
95
+ if (a.prerelease) return -1;
96
+ if (b.prerelease) return 1;
97
+ return 0;
98
+ }
99
+ function isPluginApiCompatible(required, host = PLUGIN_API_VERSION) {
100
+ const [reqMajor, reqMinor] = required.split(".").map((p) => Number(p));
101
+ const [hostMajor, hostMinor] = host.split(".").map((p) => Number(p));
102
+ if (Number.isNaN(reqMajor) || Number.isNaN(reqMinor) || Number.isNaN(hostMajor) || Number.isNaN(hostMinor)) {
103
+ return false;
104
+ }
105
+ if (hostMajor !== reqMajor) return false;
106
+ return hostMinor >= reqMinor;
107
+ }
108
+ function assertPluginApiVersion(required) {
109
+ const [reqMajor, reqMinor] = required.split(".").map((p) => Number(p));
110
+ const [hostMajor, hostMinor] = PLUGIN_API_VERSION.split(".").map((p) => Number(p));
111
+ if (Number.isNaN(reqMajor) || Number.isNaN(reqMinor)) {
112
+ throw new Error(`[plugin-sdk] invalid pluginApiVersion '${required}'.`);
113
+ }
114
+ if (hostMajor !== reqMajor) {
115
+ throw new Error(
116
+ `[plugin-sdk] incompatible pluginApiVersion: plugin wants '${required}' but host is '${PLUGIN_API_VERSION}'.`
117
+ );
118
+ }
119
+ if (hostMinor < reqMinor) {
120
+ throw new Error(
121
+ `[plugin-sdk] host SDK too old for plugin: plugin wants '${required}', host is '${PLUGIN_API_VERSION}'.`
122
+ );
123
+ }
124
+ }
125
+ function assertCmsCompatibility(cmsVersion, range) {
126
+ if (!satisfiesSemverRange(cmsVersion, range)) {
127
+ throw new Error(
128
+ `[plugin-sdk] CMS version '${cmsVersion}' does not satisfy plugin compatibility range '${range}'.`
129
+ );
130
+ }
131
+ }
132
+ function assertPluginVersionSemantics(prevVersion, nextVersion, options) {
133
+ const next = parseSemver(nextVersion);
134
+ if (!prevVersion) {
135
+ return;
136
+ }
137
+ const prev = parseSemver(prevVersion);
138
+ const bumpedMajor = next.major > prev.major;
139
+ const bumpedMinor = next.minor > prev.minor && next.major === prev.major;
140
+ const bumpedPatch = next.patch > prev.patch && next.minor === prev.minor && next.major === prev.major;
141
+ if (bumpedMajor) {
142
+ return;
143
+ }
144
+ if (bumpedMinor) {
145
+ if (!options.hasMigration) {
146
+ throw new Error(
147
+ `[plugin-sdk] plugin minor bump (${prevVersion} -> ${nextVersion}) must ship a DB migration.`
148
+ );
149
+ }
150
+ return;
151
+ }
152
+ if (bumpedPatch) {
153
+ if (options.hasMigration) {
154
+ throw new Error(
155
+ `[plugin-sdk] plugin patch bump (${prevVersion} -> ${nextVersion}) must not ship a DB migration.`
156
+ );
157
+ }
158
+ return;
159
+ }
160
+ if (compareSemver(nextVersion, prevVersion) <= 0) {
161
+ throw new Error(
162
+ `[plugin-sdk] plugin version did not increase: prev '${prevVersion}', next '${nextVersion}'.`
163
+ );
164
+ }
165
+ }
166
+
167
+ // src/registry/styles.registry.ts
168
+ var BASE_STYLE_REGISTRY = {
169
+ // ===== auth =====
170
+ login: { description: "User login form", category: "auth", frontendOnly: true, canHaveChildren: false },
171
+ register: { description: "User registration form", category: "auth", frontendOnly: true, canHaveChildren: false },
172
+ validate: { description: "Email/account validation flow", category: "auth", frontendOnly: true, canHaveChildren: true },
173
+ resetPassword: { description: "Reset password form", category: "auth", frontendOnly: true, canHaveChildren: false },
174
+ twoFactorAuth: { description: "Two-factor auth code form", category: "auth", frontendOnly: true, canHaveChildren: false },
175
+ profile: { description: "User profile management", category: "auth", frontendOnly: true, canHaveChildren: false },
176
+ // ===== layout =====
177
+ container: { description: "Mantine Container with responsive max-width", category: "layout", frontendOnly: true, canHaveChildren: true },
178
+ box: { description: "Generic Mantine Box wrapper", category: "layout", frontendOnly: true, canHaveChildren: true },
179
+ flex: { description: "Mantine Flex layout", category: "layout", frontendOnly: true, canHaveChildren: true },
180
+ group: { description: "Mantine Group horizontal layout", category: "layout", frontendOnly: true, canHaveChildren: true },
181
+ stack: { description: "Mantine Stack vertical layout", category: "layout", frontendOnly: true, canHaveChildren: true },
182
+ "simple-grid": { description: "Mantine SimpleGrid", category: "layout", frontendOnly: true, canHaveChildren: true },
183
+ grid: { description: "Mantine Grid", category: "layout", frontendOnly: true, canHaveChildren: true },
184
+ "grid-column": { description: "Mantine Grid.Col", category: "layout", frontendOnly: true, canHaveChildren: true },
185
+ space: { description: "Mantine Space spacer", category: "layout", frontendOnly: true, canHaveChildren: false },
186
+ divider: { description: "Mantine Divider", category: "layout", frontendOnly: true, canHaveChildren: false },
187
+ paper: { description: "Mantine Paper surface", category: "layout", frontendOnly: true, canHaveChildren: true },
188
+ center: { description: "Mantine Center alignment", category: "layout", frontendOnly: true, canHaveChildren: true },
189
+ "scroll-area": { description: "Mantine ScrollArea", category: "layout", frontendOnly: true, canHaveChildren: true },
190
+ card: { description: "Mantine Card", category: "layout", frontendOnly: true, canHaveChildren: true },
191
+ "card-segment": { description: "Mantine Card.Section", category: "layout", frontendOnly: true, canHaveChildren: true },
192
+ "aspect-ratio": { description: "Mantine AspectRatio wrapper", category: "layout", frontendOnly: true, canHaveChildren: true },
193
+ "background-image": { description: "Mantine BackgroundImage", category: "layout", frontendOnly: true, canHaveChildren: true },
194
+ // ===== typography =====
195
+ title: { description: "Mantine Title", category: "typography", frontendOnly: true, canHaveChildren: false },
196
+ text: { description: "Mantine Text", category: "typography", frontendOnly: true, canHaveChildren: false },
197
+ code: { description: "Mantine Code (inline / block)", category: "typography", frontendOnly: true, canHaveChildren: false },
198
+ highlight: { description: "Mantine Highlight", category: "typography", frontendOnly: true, canHaveChildren: false },
199
+ blockquote: { description: "Mantine Blockquote", category: "typography", frontendOnly: true, canHaveChildren: false },
200
+ "html-tag": { description: "Generic HTML tag wrapper (web), maps to View on RN", category: "typography", frontendOnly: true, canHaveChildren: true },
201
+ kbd: { description: "Mantine Kbd", category: "typography", frontendOnly: true, canHaveChildren: false },
202
+ typography: { description: "Mantine Typography wrapper", category: "typography", frontendOnly: true, canHaveChildren: true },
203
+ fieldset: { description: "Mantine Fieldset", category: "typography", frontendOnly: true, canHaveChildren: true },
204
+ spoiler: { description: "Mantine Spoiler reveal", category: "typography", frontendOnly: true, canHaveChildren: true },
205
+ // ===== media =====
206
+ image: { description: "Mantine Image / RN Image", category: "media", frontendOnly: true, canHaveChildren: false },
207
+ video: { description: "HTML5 video / expo-video", category: "media", frontendOnly: true, canHaveChildren: false },
208
+ audio: { description: "HTML5 audio / expo-audio", category: "media", frontendOnly: true, canHaveChildren: false },
209
+ figure: { description: "Figure with caption", category: "media", frontendOnly: true, canHaveChildren: true },
210
+ carousel: { description: "Embla on web, reanimated-carousel on RN", category: "media", frontendOnly: true, canHaveChildren: true },
211
+ // ===== interactive =====
212
+ button: { description: "Mantine Button / HeroUI Button", category: "interactive", frontendOnly: true, canHaveChildren: false },
213
+ link: { description: "Anchor / Pressable navigation", category: "interactive", frontendOnly: true, canHaveChildren: false },
214
+ "action-icon": { description: "Mantine ActionIcon", category: "interactive", frontendOnly: true, canHaveChildren: false },
215
+ alert: { description: "Mantine Alert", category: "interactive", frontendOnly: true, canHaveChildren: true },
216
+ badge: { description: "Mantine Badge", category: "interactive", frontendOnly: true, canHaveChildren: false },
217
+ avatar: { description: "Mantine Avatar", category: "interactive", frontendOnly: true, canHaveChildren: false },
218
+ chip: { description: "Mantine Chip", category: "interactive", frontendOnly: true, canHaveChildren: false },
219
+ indicator: { description: "Mantine Indicator dot", category: "interactive", frontendOnly: true, canHaveChildren: true },
220
+ "theme-icon": { description: "Mantine ThemeIcon", category: "interactive", frontendOnly: true, canHaveChildren: false },
221
+ notification: { description: "Mantine Notification", category: "interactive", frontendOnly: true, canHaveChildren: false },
222
+ // ===== forms =====
223
+ "form-log": { description: "Append-only form (one row per submit)", category: "forms", frontendOnly: true, canHaveChildren: true },
224
+ "form-record": { description: "Per-user record form", category: "forms", frontendOnly: true, canHaveChildren: true },
225
+ input: { description: "Plain HTML input", category: "forms", frontendOnly: true, canHaveChildren: false },
226
+ "text-input": { description: "Mantine TextInput", category: "forms", frontendOnly: true, canHaveChildren: false },
227
+ textarea: { description: "Mantine Textarea", category: "forms", frontendOnly: true, canHaveChildren: false },
228
+ "rich-text-editor": { description: "Tiptap editor on web; READ-ONLY viewer on mobile v1", category: "forms", frontendOnly: true, canHaveChildren: false },
229
+ select: { description: "HTML select / Mantine Select", category: "forms", frontendOnly: true, canHaveChildren: false },
230
+ radio: { description: "Mantine Radio / RadioGroup", category: "forms", frontendOnly: true, canHaveChildren: false },
231
+ checkbox: { description: "Mantine Checkbox", category: "forms", frontendOnly: true, canHaveChildren: false },
232
+ slider: { description: "Mantine Slider", category: "forms", frontendOnly: true, canHaveChildren: false },
233
+ "range-slider": { description: "Mantine RangeSlider", category: "forms", frontendOnly: true, canHaveChildren: false },
234
+ datepicker: { description: "Mantine DatePicker", category: "forms", frontendOnly: true, canHaveChildren: false },
235
+ switch: { description: "Mantine Switch", category: "forms", frontendOnly: true, canHaveChildren: false },
236
+ combobox: { description: "Mantine Combobox", category: "forms", frontendOnly: true, canHaveChildren: false },
237
+ "color-input": { description: "Mantine ColorInput", category: "forms", frontendOnly: true, canHaveChildren: false },
238
+ "color-picker": { description: "Mantine ColorPicker", category: "forms", frontendOnly: true, canHaveChildren: false },
239
+ "file-input": { description: "Mantine FileInput / DocumentPicker on RN", category: "forms", frontendOnly: true, canHaveChildren: false },
240
+ "number-input": { description: "Mantine NumberInput", category: "forms", frontendOnly: true, canHaveChildren: false },
241
+ "segmented-control": { description: "Mantine SegmentedControl", category: "forms", frontendOnly: true, canHaveChildren: false },
242
+ rating: { description: "Mantine Rating", category: "forms", frontendOnly: true, canHaveChildren: false },
243
+ progress: { description: "Mantine Progress", category: "forms", frontendOnly: true, canHaveChildren: false },
244
+ "progress-root": { description: "Mantine Progress.Root", category: "forms", frontendOnly: true, canHaveChildren: true },
245
+ "progress-section": { description: "Mantine Progress.Section", category: "forms", frontendOnly: true, canHaveChildren: false },
246
+ // ===== composite =====
247
+ accordion: { description: "Mantine Accordion", category: "composite", frontendOnly: true, canHaveChildren: true },
248
+ "accordion-item": { description: "Mantine Accordion.Item", category: "composite", frontendOnly: true, canHaveChildren: true },
249
+ tabs: { description: "Mantine Tabs", category: "composite", frontendOnly: true, canHaveChildren: true },
250
+ tab: { description: "Mantine Tabs.Tab + Tabs.Panel pair", category: "composite", frontendOnly: true, canHaveChildren: true },
251
+ timeline: { description: "Mantine Timeline", category: "composite", frontendOnly: true, canHaveChildren: true },
252
+ list: { description: "Mantine List", category: "composite", frontendOnly: true, canHaveChildren: true },
253
+ "list-item": { description: "Mantine List.Item", category: "composite", frontendOnly: true, canHaveChildren: true },
254
+ entryList: { description: "Data-driven list of entries (form-log table)", category: "composite", frontendOnly: true, canHaveChildren: true },
255
+ entryRecord: { description: "Single-record container", category: "composite", frontendOnly: true, canHaveChildren: true },
256
+ entryRecordDelete: { description: "Inline delete confirmation for an entry", category: "composite", frontendOnly: true, canHaveChildren: false },
257
+ loop: { description: "Loop / repeater over backend-provided rows", category: "composite", frontendOnly: true, canHaveChildren: true }
258
+ };
259
+ var PLUGIN_STYLE_REGISTRY = {};
260
+ var REGISTERED_PLUGIN_KEYS = /* @__PURE__ */ new Map();
261
+ function extendStyleRegistry(entries, options) {
262
+ const { pluginId, pluginVersion } = options;
263
+ const ownedKeys = REGISTERED_PLUGIN_KEYS.get(pluginId) ?? /* @__PURE__ */ new Set();
264
+ const addedKeys = [];
265
+ for (const [name, entry] of Object.entries(entries)) {
266
+ if (Object.prototype.hasOwnProperty.call(BASE_STYLE_REGISTRY, name)) {
267
+ throw new Error(
268
+ `[shared/registry] plugin '${pluginId}' tried to register core style '${name}'.`
269
+ );
270
+ }
271
+ const existing = PLUGIN_STYLE_REGISTRY[name];
272
+ if (existing && existing.pluginId !== pluginId) {
273
+ throw new Error(
274
+ `[shared/registry] plugin '${pluginId}' tried to register style '${name}' already owned by '${existing.pluginId}'.`
275
+ );
276
+ }
277
+ PLUGIN_STYLE_REGISTRY[name] = {
278
+ ...entry,
279
+ pluginId,
280
+ pluginVersion
281
+ };
282
+ ownedKeys.add(name);
283
+ addedKeys.push(name);
284
+ }
285
+ REGISTERED_PLUGIN_KEYS.set(pluginId, ownedKeys);
286
+ return function dispose() {
287
+ for (const key of addedKeys) {
288
+ const existing = PLUGIN_STYLE_REGISTRY[key];
289
+ if (existing && existing.pluginId === pluginId) {
290
+ delete PLUGIN_STYLE_REGISTRY[key];
291
+ ownedKeys.delete(key);
292
+ }
293
+ }
294
+ if (ownedKeys.size === 0) {
295
+ REGISTERED_PLUGIN_KEYS.delete(pluginId);
296
+ }
297
+ };
298
+ }
299
+
300
+ // src/plugin-sdk/define.ts
301
+ function definePlugin(registration) {
302
+ assertPluginApiVersion(registration.pluginApiVersion);
303
+ if (registration.styles?.length) {
304
+ extendStyleRegistry(toRegistryRecord(registration.styles), {
305
+ pluginId: registration.id,
306
+ pluginVersion: registration.version
307
+ });
308
+ }
309
+ return registration;
310
+ }
311
+ function defineMobilePlugin(registration) {
312
+ assertPluginApiVersion(registration.pluginApiVersion);
313
+ if (registration.styles?.length) {
314
+ extendStyleRegistry(toRegistryRecord(registration.styles), {
315
+ pluginId: registration.id,
316
+ pluginVersion: registration.version
317
+ });
318
+ }
319
+ return registration;
320
+ }
321
+ function definePluginRealtimeTopic(descriptor) {
322
+ return descriptor;
323
+ }
324
+ function toRegistryRecord(styles) {
325
+ const out = {};
326
+ for (const style of styles) {
327
+ out[style.name] = {
328
+ description: style.description,
329
+ category: style.category,
330
+ frontendOnly: true,
331
+ canHaveChildren: style.canHaveChildren
332
+ };
333
+ }
334
+ return out;
335
+ }
336
+
337
+ // src/plugin-sdk/realtime.ts
338
+ var import_react = require("react");
339
+ var DEFAULT_ENDPOINT = "/api/plugins/events";
340
+ var MAX_RECONNECT_DELAY_MS = 3e4;
341
+ var INITIAL_RECONNECT_DELAY_MS = 1e3;
342
+ function expandTopic(topic, params) {
343
+ return topic.replace(/\{([^}]+)\}/g, (_match, name) => {
344
+ const value = params[name];
345
+ if (value === void 0) {
346
+ throw new Error(
347
+ `usePluginRealtime: topic "${topic}" references {${name}} but topicParams.${name} was not provided.`
348
+ );
349
+ }
350
+ return encodeURIComponent(String(value));
351
+ });
352
+ }
353
+ function buildSseUrl(endpoint, pluginId, expandedTopic) {
354
+ const params = new URLSearchParams({
355
+ pluginId,
356
+ topic: expandedTopic
357
+ });
358
+ const separator = endpoint.includes("?") ? "&" : "?";
359
+ return `${endpoint}${separator}${params.toString()}`;
360
+ }
361
+ function isEventSourceAvailable() {
362
+ return typeof globalThis !== "undefined" && typeof globalThis.EventSource !== "undefined";
363
+ }
364
+ function defaultTransportFactory(url) {
365
+ const Ctor = globalThis.EventSource;
366
+ return new Ctor(url);
367
+ }
368
+ function usePluginRealtime(options) {
369
+ const {
370
+ pluginId,
371
+ topic,
372
+ topicParams = {},
373
+ enabled = true,
374
+ endpoint = DEFAULT_ENDPOINT,
375
+ transportFactory,
376
+ parse
377
+ } = options;
378
+ const [data, setData] = (0, import_react.useState)(null);
379
+ const [isOnline, setIsOnline] = (0, import_react.useState)(false);
380
+ const [lastEventAt, setLastEventAt] = (0, import_react.useState)(null);
381
+ const [error, setError] = (0, import_react.useState)(null);
382
+ const parseRef = (0, import_react.useRef)(parse);
383
+ parseRef.current = parse;
384
+ const topicParamsKey = JSON.stringify(topicParams);
385
+ (0, import_react.useEffect)(() => {
386
+ if (!enabled) {
387
+ setIsOnline(false);
388
+ return;
389
+ }
390
+ const factory = transportFactory ?? (isEventSourceAvailable() ? defaultTransportFactory : null);
391
+ if (factory === null) {
392
+ setIsOnline(false);
393
+ return;
394
+ }
395
+ let cancelled = false;
396
+ let transport = null;
397
+ let reconnectTimer = null;
398
+ let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
399
+ let expandedTopic;
400
+ try {
401
+ expandedTopic = expandTopic(topic, JSON.parse(topicParamsKey));
402
+ } catch (err) {
403
+ setError(err instanceof Error ? err : new Error(String(err)));
404
+ setIsOnline(false);
405
+ return;
406
+ }
407
+ const eventName = `plugin/${pluginId}/${expandedTopic}`;
408
+ const url = buildSseUrl(endpoint, pluginId, expandedTopic);
409
+ const onOpen = () => {
410
+ if (cancelled) return;
411
+ reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
412
+ setIsOnline(true);
413
+ setError(null);
414
+ };
415
+ const onEvent = (evt) => {
416
+ if (cancelled) return;
417
+ const raw = evt.data;
418
+ if (typeof raw !== "string") return;
419
+ try {
420
+ const payload = parseRef.current ? parseRef.current(raw) : JSON.parse(raw);
421
+ setData(payload);
422
+ setLastEventAt(/* @__PURE__ */ new Date());
423
+ } catch (parseErr) {
424
+ setError(parseErr instanceof Error ? parseErr : new Error(String(parseErr)));
425
+ }
426
+ };
427
+ const onError = (evt) => {
428
+ if (cancelled || !transport) return;
429
+ setIsOnline(false);
430
+ setError(evt instanceof Error ? evt : new Error("Plugin realtime transport error"));
431
+ if (transport.readyState === 2) {
432
+ try {
433
+ transport.close();
434
+ } catch {
435
+ }
436
+ transport = null;
437
+ reconnectTimer = setTimeout(connect, reconnectDelay);
438
+ reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
439
+ }
440
+ };
441
+ const connect = () => {
442
+ if (cancelled) return;
443
+ try {
444
+ transport = factory(url);
445
+ } catch (createErr) {
446
+ setError(createErr instanceof Error ? createErr : new Error(String(createErr)));
447
+ setIsOnline(false);
448
+ return;
449
+ }
450
+ transport.addEventListener("open", onOpen);
451
+ transport.addEventListener(eventName, onEvent);
452
+ transport.addEventListener("message", onEvent);
453
+ transport.addEventListener("error", onError);
454
+ };
455
+ connect();
456
+ return () => {
457
+ cancelled = true;
458
+ if (reconnectTimer !== null) {
459
+ clearTimeout(reconnectTimer);
460
+ }
461
+ if (transport) {
462
+ try {
463
+ transport.removeEventListener("open", onOpen);
464
+ transport.removeEventListener(eventName, onEvent);
465
+ transport.removeEventListener("message", onEvent);
466
+ transport.removeEventListener("error", onError);
467
+ transport.close();
468
+ } catch {
469
+ }
470
+ transport = null;
471
+ }
472
+ };
473
+ }, [enabled, endpoint, pluginId, topic, topicParamsKey, transportFactory]);
474
+ return { data, isOnline, lastEventAt, error };
475
+ }
476
+ // Annotate the CommonJS export names for ESM import in node:
477
+ 0 && (module.exports = {
478
+ PLUGIN_API_VERSION,
479
+ assertCmsCompatibility,
480
+ assertPluginApiVersion,
481
+ assertPluginVersionSemantics,
482
+ compareSemver,
483
+ defineMobilePlugin,
484
+ definePlugin,
485
+ definePluginRealtimeTopic,
486
+ isPluginApiCompatible,
487
+ parseSemver,
488
+ satisfiesSemverRange,
489
+ usePluginRealtime
490
+ });