@selfhelp/shared 1.15.3 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,26 @@ All notable changes to `@selfhelp/shared` will be documented in this file.
9
9
 
10
10
  This project follows semantic versioning.
11
11
 
12
+ ## v1.16.0
13
+
14
+ **Mobile host-services bridge** — a typed contract so a plugin's mobile package
15
+ routes protected API calls through the native host (which owns the access token,
16
+ the single 401-refresh round-trip, and session-expiry) instead of injecting raw
17
+ tokens into plugin/WebView code. Additive only — new `plugin-sdk` module +
18
+ exports — so `^1.x` consumers are unaffected; the SurveyJS mobile WebView
19
+ renderer (`@selfhelp/sh2-shp-survey-js-mobile`) and the mobile host adopt it.
20
+
21
+ ### Added (additive, non-breaking)
22
+
23
+ - **`plugin-sdk/host-services.ts`** new exports (via `@selfhelp/shared/plugin-sdk`):
24
+ - `IMobileHostServices` (`apiBaseUrl()`, `getAccessToken()`, `request()`),
25
+ `IMobileHostRequest`, `IMobileHostResponse<TData>`, `TMobileHostMethod`;
26
+ - the singleton registry `setMobileHostServices()` / `getMobileHostServices()`
27
+ (host registers at boot; the plugin consumes at runtime).
28
+ - **`MOBILE_RENDERER_VERSION`** bumped `0.1.0 -> 0.2.0` (additive renderer
29
+ feature). Plugins declaring `compatibility.mobile: ^0.2.0` gate against it
30
+ through `isMobileRendererCompatible`.
31
+
12
32
  ## v1.15.3
13
33
 
14
34
  **Live Preview shared theme + language sync** — extends the bridge contract so a
@@ -30,8 +30,13 @@ declare const PLUGIN_API_VERSION: "0.1.0";
30
30
  *
31
31
  * Bump rules mirror the SDK contract: patch = additive fix, minor = additive
32
32
  * renderer feature, major = breaking mobile renderer change.
33
+ *
34
+ * `0.2.0` adds the typed mobile host-services bridge (`IMobileHostServices` +
35
+ * `set/getMobileHostServices`) so a plugin's mobile package routes protected
36
+ * API calls through the native host (token + 401-refresh owned host-side)
37
+ * instead of injecting raw tokens — an additive renderer feature.
33
38
  */
34
- declare const MOBILE_RENDERER_VERSION: "0.1.0";
39
+ declare const MOBILE_RENDERER_VERSION: "0.2.0";
35
40
  interface ISemver {
36
41
  major: number;
37
42
  minor: number;
@@ -692,6 +697,106 @@ declare function defineMobilePlugin(registration: IMobilePluginRegistration): IM
692
697
  */
693
698
  declare function definePluginRealtimeTopic<TPayload>(descriptor: IPluginRealtimeTopic<TPayload>): IPluginRealtimeTopic<TPayload>;
694
699
 
700
+ /**
701
+ * Mobile host-services bridge (mobile renderer contract, `MOBILE_RENDERER_VERSION`).
702
+ *
703
+ * A plugin's mobile package renders its UI (commonly inside an isolated
704
+ * WebView), but it MUST NOT own authenticated backend access. Instead the
705
+ * native mobile host registers an `IMobileHostServices` implementation at
706
+ * boot, and the plugin performs every protected API call through it. This
707
+ * keeps the access token, the 401-refresh round-trip, session-expiry, the
708
+ * API base URL, and client headers (`X-Client-Type: mobile`, locale) in the
709
+ * host — never inside plugin/WebView code.
710
+ *
711
+ * Design constraints:
712
+ * - Framework-agnostic: no `react` / `react-native` / `axios` imports here.
713
+ * The host wires its own HTTP client (e.g. the shared axios singleton)
714
+ * into `request`.
715
+ * - Singleton: the host calls {@link setMobileHostServices} once during
716
+ * boot; the plugin calls {@link getMobileHostServices} at runtime.
717
+ * - The token is intentionally NOT a required input to plugin calls. A
718
+ * plugin may read {@link IMobileHostServices.getAccessToken} only for
719
+ * non-sensitive bootstrapping; it must never implement its own refresh.
720
+ */
721
+ /** HTTP method accepted by the host request bridge. */
722
+ type TMobileHostMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
723
+ /**
724
+ * A protected backend request the plugin asks the host to perform. The
725
+ * host prepends {@link IMobileHostServices.apiBaseUrl}, attaches the bearer
726
+ * token + client headers, and handles a single 401-refresh retry.
727
+ */
728
+ interface IMobileHostRequest {
729
+ /**
730
+ * Path relative to the host API base, e.g.
731
+ * `/cms-api/v1/plugins/<id>/published/<key>`. Absolute URLs are rejected
732
+ * by the host so a plugin cannot redirect protected calls off-origin.
733
+ */
734
+ path: string;
735
+ /** HTTP method. Defaults to `GET`. */
736
+ method?: TMobileHostMethod;
737
+ /** JSON-serialisable request body (sent as `application/json`). */
738
+ body?: unknown;
739
+ /** Extra request headers (e.g. a plugin runtime-config echo header). */
740
+ headers?: Record<string, string>;
741
+ /** Query parameters appended to the path. */
742
+ query?: Record<string, string | number | boolean>;
743
+ }
744
+ /**
745
+ * Result of a host request. `data` is the parsed response body (the SelfHelp
746
+ * API envelope `{ status, message, data, ... }` for API routes), so the
747
+ * plugin reads `response.data.data` for the inner payload. `reason` mirrors
748
+ * the backend error discriminator (e.g. `already_submitted_once`) so the
749
+ * plugin can branch on lifecycle errors without re-parsing the body.
750
+ */
751
+ interface IMobileHostResponse<TData = unknown> {
752
+ /** True for 2xx responses. */
753
+ ok: boolean;
754
+ /** HTTP status code (0 when the request never reached the server). */
755
+ status: number;
756
+ /** Parsed response body, or `null` when there is no JSON body. */
757
+ data: TData | null;
758
+ /** Backend error `reason` discriminator, when present. */
759
+ reason?: string;
760
+ /** Human-readable error message for non-ok responses. */
761
+ error?: string;
762
+ /**
763
+ * True when the call failed because the session could not be
764
+ * authenticated even after the host's refresh attempt (a 401 the host
765
+ * could not recover). The plugin should surface a "session expired"
766
+ * state rather than a generic error.
767
+ */
768
+ sessionExpired?: boolean;
769
+ }
770
+ /**
771
+ * Authenticated host services exposed to a plugin's mobile package. The
772
+ * host owns the token + refresh; the plugin only describes the request.
773
+ */
774
+ interface IMobileHostServices {
775
+ /** Resolved API base URL the host calls (e.g. `https://cms.example.com`). */
776
+ apiBaseUrl(): string;
777
+ /**
778
+ * Current access token, or `null` when unauthenticated. Exposed only for
779
+ * non-sensitive bootstrapping (e.g. deciding whether to show a login
780
+ * prompt). Plugins must route protected calls through {@link request},
781
+ * which attaches the token host-side, instead of injecting this value.
782
+ */
783
+ getAccessToken(): string | null;
784
+ /** Perform an authenticated request with host-managed 401 refresh. */
785
+ request<TData = unknown>(req: IMobileHostRequest): Promise<IMobileHostResponse<TData>>;
786
+ }
787
+ /**
788
+ * Register the host services implementation. Called once by the native
789
+ * mobile host during boot (before any plugin renders). Re-registering
790
+ * replaces the previous implementation (e.g. on a server switch).
791
+ */
792
+ declare function setMobileHostServices(services: IMobileHostServices | null): void;
793
+ /**
794
+ * Read the registered host services. Returns `null` when no host has
795
+ * registered yet — a plugin must treat that as "host too old / not ready"
796
+ * and degrade gracefully (it must never fall back to its own token logic).
797
+ */
798
+ declare function getMobileHostServices(): IMobileHostServices | null;
799
+
695
800
  /**
696
801
  * `usePluginRealtime` — universal React hook for plugin Mercure topic
697
802
  * subscription.
@@ -874,4 +979,4 @@ declare function isPluginRuntimeShimSpecifier(value: unknown): value is TPluginR
874
979
  */
875
980
  declare const PLUGIN_RUNTIME_IMPORT_MAP: Readonly<Record<TPluginRuntimeShimSpecifier, string>>;
876
981
 
877
- export { type IAdminPageDefinition, type IFieldRendererDefinition, type IMenuItemDefinition, type IMobilePluginApi, type IMobilePluginRegistration, type IPluginApi, type IPluginFeatureFlag, type IPluginFieldRendererProps, type IPluginHealthCheck, type IPluginLock, type IPluginLockEntry, type IPluginLockMigration, type IPluginLockMobileEntry, type IPluginRealtimePublisher, type IPluginRealtimeTopic, type IPluginRegistration, type IPluginRegistry, type IPluginRelease, type IRealtimeTransport, type IRegistryReleaseRef, type IRegistrySignatureBlock, type IRichTextEditorAdapter, type IRichTextEditorAdapterOptions, type IRichTextEditorValue, type IStyleDefinition, type IUsePluginRealtimeOptions, type IUsePluginRealtimeResult, MOBILE_RENDERER_VERSION, PLUGIN_API_VERSION, PLUGIN_REGISTRY_CHANNELS, PLUGIN_RUNTIME_GLOBAL_KEY, PLUGIN_RUNTIME_IMPORT_MAP, PLUGIN_RUNTIME_SHIM_BASE_PATH, PLUGIN_RUNTIME_SHIM_SPECIFIERS, type TPluginRegistryChannel, type TPluginRuntimeShimSpecifier, type TRealtimeTransportFactory, assertCmsCompatibility, assertPluginApiVersion, assertPluginVersionSemantics, buildPluginRuntimeShimPath, compareSemver, defineMobilePlugin, definePlugin, definePluginRealtimeTopic, isMobileRendererCompatible, isPluginApiCompatible, isPluginRuntimeShimSpecifier, parseSemver, satisfiesSemverRange, usePluginRealtime };
982
+ export { type IAdminPageDefinition, type IFieldRendererDefinition, type IMenuItemDefinition, type IMobileHostRequest, type IMobileHostResponse, type IMobileHostServices, type IMobilePluginApi, type IMobilePluginRegistration, type IPluginApi, type IPluginFeatureFlag, type IPluginFieldRendererProps, type IPluginHealthCheck, type IPluginLock, type IPluginLockEntry, type IPluginLockMigration, type IPluginLockMobileEntry, type IPluginRealtimePublisher, type IPluginRealtimeTopic, type IPluginRegistration, type IPluginRegistry, type IPluginRelease, type IRealtimeTransport, type IRegistryReleaseRef, type IRegistrySignatureBlock, type IRichTextEditorAdapter, type IRichTextEditorAdapterOptions, type IRichTextEditorValue, type IStyleDefinition, type IUsePluginRealtimeOptions, type IUsePluginRealtimeResult, MOBILE_RENDERER_VERSION, PLUGIN_API_VERSION, PLUGIN_REGISTRY_CHANNELS, PLUGIN_RUNTIME_GLOBAL_KEY, PLUGIN_RUNTIME_IMPORT_MAP, PLUGIN_RUNTIME_SHIM_BASE_PATH, PLUGIN_RUNTIME_SHIM_SPECIFIERS, type TMobileHostMethod, type TPluginRegistryChannel, type TPluginRuntimeShimSpecifier, type TRealtimeTransportFactory, assertCmsCompatibility, assertPluginApiVersion, assertPluginVersionSemantics, buildPluginRuntimeShimPath, compareSemver, defineMobilePlugin, definePlugin, definePluginRealtimeTopic, getMobileHostServices, isMobileRendererCompatible, isPluginApiCompatible, isPluginRuntimeShimSpecifier, parseSemver, satisfiesSemverRange, setMobileHostServices, usePluginRealtime };
@@ -30,8 +30,13 @@ declare const PLUGIN_API_VERSION: "0.1.0";
30
30
  *
31
31
  * Bump rules mirror the SDK contract: patch = additive fix, minor = additive
32
32
  * renderer feature, major = breaking mobile renderer change.
33
+ *
34
+ * `0.2.0` adds the typed mobile host-services bridge (`IMobileHostServices` +
35
+ * `set/getMobileHostServices`) so a plugin's mobile package routes protected
36
+ * API calls through the native host (token + 401-refresh owned host-side)
37
+ * instead of injecting raw tokens — an additive renderer feature.
33
38
  */
34
- declare const MOBILE_RENDERER_VERSION: "0.1.0";
39
+ declare const MOBILE_RENDERER_VERSION: "0.2.0";
35
40
  interface ISemver {
36
41
  major: number;
37
42
  minor: number;
@@ -692,6 +697,106 @@ declare function defineMobilePlugin(registration: IMobilePluginRegistration): IM
692
697
  */
693
698
  declare function definePluginRealtimeTopic<TPayload>(descriptor: IPluginRealtimeTopic<TPayload>): IPluginRealtimeTopic<TPayload>;
694
699
 
700
+ /**
701
+ * Mobile host-services bridge (mobile renderer contract, `MOBILE_RENDERER_VERSION`).
702
+ *
703
+ * A plugin's mobile package renders its UI (commonly inside an isolated
704
+ * WebView), but it MUST NOT own authenticated backend access. Instead the
705
+ * native mobile host registers an `IMobileHostServices` implementation at
706
+ * boot, and the plugin performs every protected API call through it. This
707
+ * keeps the access token, the 401-refresh round-trip, session-expiry, the
708
+ * API base URL, and client headers (`X-Client-Type: mobile`, locale) in the
709
+ * host — never inside plugin/WebView code.
710
+ *
711
+ * Design constraints:
712
+ * - Framework-agnostic: no `react` / `react-native` / `axios` imports here.
713
+ * The host wires its own HTTP client (e.g. the shared axios singleton)
714
+ * into `request`.
715
+ * - Singleton: the host calls {@link setMobileHostServices} once during
716
+ * boot; the plugin calls {@link getMobileHostServices} at runtime.
717
+ * - The token is intentionally NOT a required input to plugin calls. A
718
+ * plugin may read {@link IMobileHostServices.getAccessToken} only for
719
+ * non-sensitive bootstrapping; it must never implement its own refresh.
720
+ */
721
+ /** HTTP method accepted by the host request bridge. */
722
+ type TMobileHostMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
723
+ /**
724
+ * A protected backend request the plugin asks the host to perform. The
725
+ * host prepends {@link IMobileHostServices.apiBaseUrl}, attaches the bearer
726
+ * token + client headers, and handles a single 401-refresh retry.
727
+ */
728
+ interface IMobileHostRequest {
729
+ /**
730
+ * Path relative to the host API base, e.g.
731
+ * `/cms-api/v1/plugins/<id>/published/<key>`. Absolute URLs are rejected
732
+ * by the host so a plugin cannot redirect protected calls off-origin.
733
+ */
734
+ path: string;
735
+ /** HTTP method. Defaults to `GET`. */
736
+ method?: TMobileHostMethod;
737
+ /** JSON-serialisable request body (sent as `application/json`). */
738
+ body?: unknown;
739
+ /** Extra request headers (e.g. a plugin runtime-config echo header). */
740
+ headers?: Record<string, string>;
741
+ /** Query parameters appended to the path. */
742
+ query?: Record<string, string | number | boolean>;
743
+ }
744
+ /**
745
+ * Result of a host request. `data` is the parsed response body (the SelfHelp
746
+ * API envelope `{ status, message, data, ... }` for API routes), so the
747
+ * plugin reads `response.data.data` for the inner payload. `reason` mirrors
748
+ * the backend error discriminator (e.g. `already_submitted_once`) so the
749
+ * plugin can branch on lifecycle errors without re-parsing the body.
750
+ */
751
+ interface IMobileHostResponse<TData = unknown> {
752
+ /** True for 2xx responses. */
753
+ ok: boolean;
754
+ /** HTTP status code (0 when the request never reached the server). */
755
+ status: number;
756
+ /** Parsed response body, or `null` when there is no JSON body. */
757
+ data: TData | null;
758
+ /** Backend error `reason` discriminator, when present. */
759
+ reason?: string;
760
+ /** Human-readable error message for non-ok responses. */
761
+ error?: string;
762
+ /**
763
+ * True when the call failed because the session could not be
764
+ * authenticated even after the host's refresh attempt (a 401 the host
765
+ * could not recover). The plugin should surface a "session expired"
766
+ * state rather than a generic error.
767
+ */
768
+ sessionExpired?: boolean;
769
+ }
770
+ /**
771
+ * Authenticated host services exposed to a plugin's mobile package. The
772
+ * host owns the token + refresh; the plugin only describes the request.
773
+ */
774
+ interface IMobileHostServices {
775
+ /** Resolved API base URL the host calls (e.g. `https://cms.example.com`). */
776
+ apiBaseUrl(): string;
777
+ /**
778
+ * Current access token, or `null` when unauthenticated. Exposed only for
779
+ * non-sensitive bootstrapping (e.g. deciding whether to show a login
780
+ * prompt). Plugins must route protected calls through {@link request},
781
+ * which attaches the token host-side, instead of injecting this value.
782
+ */
783
+ getAccessToken(): string | null;
784
+ /** Perform an authenticated request with host-managed 401 refresh. */
785
+ request<TData = unknown>(req: IMobileHostRequest): Promise<IMobileHostResponse<TData>>;
786
+ }
787
+ /**
788
+ * Register the host services implementation. Called once by the native
789
+ * mobile host during boot (before any plugin renders). Re-registering
790
+ * replaces the previous implementation (e.g. on a server switch).
791
+ */
792
+ declare function setMobileHostServices(services: IMobileHostServices | null): void;
793
+ /**
794
+ * Read the registered host services. Returns `null` when no host has
795
+ * registered yet — a plugin must treat that as "host too old / not ready"
796
+ * and degrade gracefully (it must never fall back to its own token logic).
797
+ */
798
+ declare function getMobileHostServices(): IMobileHostServices | null;
799
+
695
800
  /**
696
801
  * `usePluginRealtime` — universal React hook for plugin Mercure topic
697
802
  * subscription.
@@ -874,4 +979,4 @@ declare function isPluginRuntimeShimSpecifier(value: unknown): value is TPluginR
874
979
  */
875
980
  declare const PLUGIN_RUNTIME_IMPORT_MAP: Readonly<Record<TPluginRuntimeShimSpecifier, string>>;
876
981
 
877
- export { type IAdminPageDefinition, type IFieldRendererDefinition, type IMenuItemDefinition, type IMobilePluginApi, type IMobilePluginRegistration, type IPluginApi, type IPluginFeatureFlag, type IPluginFieldRendererProps, type IPluginHealthCheck, type IPluginLock, type IPluginLockEntry, type IPluginLockMigration, type IPluginLockMobileEntry, type IPluginRealtimePublisher, type IPluginRealtimeTopic, type IPluginRegistration, type IPluginRegistry, type IPluginRelease, type IRealtimeTransport, type IRegistryReleaseRef, type IRegistrySignatureBlock, type IRichTextEditorAdapter, type IRichTextEditorAdapterOptions, type IRichTextEditorValue, type IStyleDefinition, type IUsePluginRealtimeOptions, type IUsePluginRealtimeResult, MOBILE_RENDERER_VERSION, PLUGIN_API_VERSION, PLUGIN_REGISTRY_CHANNELS, PLUGIN_RUNTIME_GLOBAL_KEY, PLUGIN_RUNTIME_IMPORT_MAP, PLUGIN_RUNTIME_SHIM_BASE_PATH, PLUGIN_RUNTIME_SHIM_SPECIFIERS, type TPluginRegistryChannel, type TPluginRuntimeShimSpecifier, type TRealtimeTransportFactory, assertCmsCompatibility, assertPluginApiVersion, assertPluginVersionSemantics, buildPluginRuntimeShimPath, compareSemver, defineMobilePlugin, definePlugin, definePluginRealtimeTopic, isMobileRendererCompatible, isPluginApiCompatible, isPluginRuntimeShimSpecifier, parseSemver, satisfiesSemverRange, usePluginRealtime };
982
+ export { type IAdminPageDefinition, type IFieldRendererDefinition, type IMenuItemDefinition, type IMobileHostRequest, type IMobileHostResponse, type IMobileHostServices, type IMobilePluginApi, type IMobilePluginRegistration, type IPluginApi, type IPluginFeatureFlag, type IPluginFieldRendererProps, type IPluginHealthCheck, type IPluginLock, type IPluginLockEntry, type IPluginLockMigration, type IPluginLockMobileEntry, type IPluginRealtimePublisher, type IPluginRealtimeTopic, type IPluginRegistration, type IPluginRegistry, type IPluginRelease, type IRealtimeTransport, type IRegistryReleaseRef, type IRegistrySignatureBlock, type IRichTextEditorAdapter, type IRichTextEditorAdapterOptions, type IRichTextEditorValue, type IStyleDefinition, type IUsePluginRealtimeOptions, type IUsePluginRealtimeResult, MOBILE_RENDERER_VERSION, PLUGIN_API_VERSION, PLUGIN_REGISTRY_CHANNELS, PLUGIN_RUNTIME_GLOBAL_KEY, PLUGIN_RUNTIME_IMPORT_MAP, PLUGIN_RUNTIME_SHIM_BASE_PATH, PLUGIN_RUNTIME_SHIM_SPECIFIERS, type TMobileHostMethod, type TPluginRegistryChannel, type TPluginRuntimeShimSpecifier, type TRealtimeTransportFactory, assertCmsCompatibility, assertPluginApiVersion, assertPluginVersionSemantics, buildPluginRuntimeShimPath, compareSemver, defineMobilePlugin, definePlugin, definePluginRealtimeTopic, getMobileHostServices, isMobileRendererCompatible, isPluginApiCompatible, isPluginRuntimeShimSpecifier, parseSemver, satisfiesSemverRange, setMobileHostServices, usePluginRealtime };
@@ -35,18 +35,20 @@ __export(plugin_sdk_exports, {
35
35
  defineMobilePlugin: () => defineMobilePlugin,
36
36
  definePlugin: () => definePlugin,
37
37
  definePluginRealtimeTopic: () => definePluginRealtimeTopic,
38
+ getMobileHostServices: () => getMobileHostServices,
38
39
  isMobileRendererCompatible: () => isMobileRendererCompatible,
39
40
  isPluginApiCompatible: () => isPluginApiCompatible,
40
41
  isPluginRuntimeShimSpecifier: () => isPluginRuntimeShimSpecifier,
41
42
  parseSemver: () => parseSemver,
42
43
  satisfiesSemverRange: () => satisfiesSemverRange,
44
+ setMobileHostServices: () => setMobileHostServices,
43
45
  usePluginRealtime: () => usePluginRealtime
44
46
  });
45
47
  module.exports = __toCommonJS(plugin_sdk_exports);
46
48
 
47
49
  // src/plugin-sdk/version.ts
48
50
  var PLUGIN_API_VERSION = "0.1.0";
49
- var MOBILE_RENDERER_VERSION = "0.1.0";
51
+ var MOBILE_RENDERER_VERSION = "0.2.0";
50
52
  var SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
51
53
  function parseSemver(version) {
52
54
  const match = SEMVER_REGEX.exec(version);
@@ -363,6 +365,15 @@ function toRegistryRecord(styles) {
363
365
  return out;
364
366
  }
365
367
 
368
+ // src/plugin-sdk/host-services.ts
369
+ var registeredHostServices = null;
370
+ function setMobileHostServices(services) {
371
+ registeredHostServices = services;
372
+ }
373
+ function getMobileHostServices() {
374
+ return registeredHostServices;
375
+ }
376
+
366
377
  // src/plugin-sdk/realtime.ts
367
378
  var import_react = require("react");
368
379
  var DEFAULT_ENDPOINT = "/api/plugins/events";
@@ -548,10 +559,12 @@ var PLUGIN_RUNTIME_IMPORT_MAP = Object.freeze(
548
559
  defineMobilePlugin,
549
560
  definePlugin,
550
561
  definePluginRealtimeTopic,
562
+ getMobileHostServices,
551
563
  isMobileRendererCompatible,
552
564
  isPluginApiCompatible,
553
565
  isPluginRuntimeShimSpecifier,
554
566
  parseSemver,
555
567
  satisfiesSemverRange,
568
+ setMobileHostServices,
556
569
  usePluginRealtime
557
570
  });
@@ -1,6 +1,6 @@
1
1
  // src/plugin-sdk/version.ts
2
2
  var PLUGIN_API_VERSION = "0.1.0";
3
- var MOBILE_RENDERER_VERSION = "0.1.0";
3
+ var MOBILE_RENDERER_VERSION = "0.2.0";
4
4
  var SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
5
5
  function parseSemver(version) {
6
6
  const match = SEMVER_REGEX.exec(version);
@@ -317,6 +317,15 @@ function toRegistryRecord(styles) {
317
317
  return out;
318
318
  }
319
319
 
320
+ // src/plugin-sdk/host-services.ts
321
+ var registeredHostServices = null;
322
+ function setMobileHostServices(services) {
323
+ registeredHostServices = services;
324
+ }
325
+ function getMobileHostServices() {
326
+ return registeredHostServices;
327
+ }
328
+
320
329
  // src/plugin-sdk/realtime.ts
321
330
  import { useEffect, useRef, useState } from "react";
322
331
  var DEFAULT_ENDPOINT = "/api/plugins/events";
@@ -501,10 +510,12 @@ export {
501
510
  defineMobilePlugin,
502
511
  definePlugin,
503
512
  definePluginRealtimeTopic,
513
+ getMobileHostServices,
504
514
  isMobileRendererCompatible,
505
515
  isPluginApiCompatible,
506
516
  isPluginRuntimeShimSpecifier,
507
517
  parseSemver,
508
518
  satisfiesSemverRange,
519
+ setMobileHostServices,
509
520
  usePluginRealtime
510
521
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.15.3",
3
+ "version": "1.16.0",
4
4
  "description": "Shared TypeScript package for SelfHelp web frontend and mobile app: style registry, types, API contracts, Mantine theme tokens, condition + interpolation engines, CMS class allow-list.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,136 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Mobile host-services bridge contract (mobile renderer axis 0.2.0).
7
+ *
8
+ * The shared package only owns the *contract* + the singleton registry; the
9
+ * real 401-refresh / session-expired logic lives in the native host's
10
+ * implementation. These tests assert:
11
+ * - the singleton is null before a host registers and after it clears,
12
+ * - a registered host is returned to plugin code,
13
+ * - the documented response contract (ok / reason / sessionExpired) lets a
14
+ * plugin branch on lifecycle + refresh outcomes through a representative
15
+ * fake host that performs a single 401 -> refresh -> retry, and reports
16
+ * session-expired when the refresh itself fails,
17
+ * - `isMobileRendererCompatible` covers the bumped 0.2.0 host.
18
+ */
19
+
20
+ import { afterEach, describe, expect, it, vi } from 'vitest';
21
+
22
+ import {
23
+ type IMobileHostRequest,
24
+ type IMobileHostServices,
25
+ getMobileHostServices,
26
+ setMobileHostServices,
27
+ } from '../host-services';
28
+ import { MOBILE_RENDERER_VERSION, isMobileRendererCompatible } from '../version';
29
+
30
+ afterEach(() => {
31
+ setMobileHostServices(null);
32
+ });
33
+
34
+ describe('mobile host-services singleton', () => {
35
+ it('is null until the host registers an implementation', () => {
36
+ expect(getMobileHostServices()).toBeNull();
37
+ });
38
+
39
+ it('returns the host implementation the host registered', () => {
40
+ const services: IMobileHostServices = {
41
+ apiBaseUrl: () => 'https://cms.example.com',
42
+ getAccessToken: () => 'token-abc',
43
+ request: () => Promise.resolve({ ok: true, status: 200, data: null }),
44
+ };
45
+ setMobileHostServices(services);
46
+ expect(getMobileHostServices()).toBe(services);
47
+ expect(getMobileHostServices()?.apiBaseUrl()).toBe('https://cms.example.com');
48
+ expect(getMobileHostServices()?.getAccessToken()).toBe('token-abc');
49
+ });
50
+
51
+ it('clears back to null when the host deregisters (e.g. server switch)', () => {
52
+ setMobileHostServices({
53
+ apiBaseUrl: () => '',
54
+ getAccessToken: () => null,
55
+ request: () => Promise.resolve({ ok: true, status: 204, data: null }),
56
+ });
57
+ setMobileHostServices(null);
58
+ expect(getMobileHostServices()).toBeNull();
59
+ });
60
+ });
61
+
62
+ describe('host request contract (host owns token + refresh)', () => {
63
+ /**
64
+ * Representative host: the first protected call 401s, the host refreshes
65
+ * once and replays the request; if the refresh fails it reports
66
+ * `sessionExpired`. This mirrors the native axios interceptor so plugin
67
+ * code can be written against the contract.
68
+ */
69
+ function makeHost(options: { refreshSucceeds: boolean }): {
70
+ services: IMobileHostServices;
71
+ calls: () => number;
72
+ } {
73
+ let token = 'expired';
74
+ let attempts = 0;
75
+ const refresh = vi.fn(() => {
76
+ if (!options.refreshSucceeds) return false;
77
+ token = 'fresh';
78
+ return true;
79
+ });
80
+ const services: IMobileHostServices = {
81
+ apiBaseUrl: () => 'https://cms.example.com',
82
+ getAccessToken: () => token,
83
+ request: async <TData>(_req: IMobileHostRequest) => {
84
+ attempts++;
85
+ if (token === 'expired') {
86
+ const recovered = refresh();
87
+ if (!recovered) {
88
+ return { ok: false, status: 401, data: null, sessionExpired: true } as const;
89
+ }
90
+ attempts++;
91
+ }
92
+ return { ok: true, status: 200, data: { data: { responseId: 'R_1' } } as TData };
93
+ },
94
+ };
95
+ return { services, calls: () => attempts };
96
+ }
97
+
98
+ it('recovers a 401 with a single refresh + retry and returns the payload', async () => {
99
+ const { services, calls } = makeHost({ refreshSucceeds: true });
100
+ setMobileHostServices(services);
101
+
102
+ const res = await getMobileHostServices()!.request<{ data: { responseId: string } }>({
103
+ path: '/cms-api/v1/plugins/sh2-shp-survey-js/published/key/submit',
104
+ method: 'POST',
105
+ body: { answers: {} },
106
+ });
107
+
108
+ expect(res.ok).toBe(true);
109
+ expect(res.status).toBe(200);
110
+ expect(res.data?.data.responseId).toBe('R_1');
111
+ expect(calls()).toBe(2); // initial 401 + replay
112
+ });
113
+
114
+ it('reports sessionExpired when the refresh itself fails', async () => {
115
+ const { services } = makeHost({ refreshSucceeds: false });
116
+ setMobileHostServices(services);
117
+
118
+ const res = await getMobileHostServices()!.request({
119
+ path: '/cms-api/v1/plugins/sh2-shp-survey-js/published/key/progress',
120
+ method: 'PUT',
121
+ body: {},
122
+ });
123
+
124
+ expect(res.ok).toBe(false);
125
+ expect(res.status).toBe(401);
126
+ expect(res.sessionExpired).toBe(true);
127
+ });
128
+ });
129
+
130
+ describe('mobile renderer compatibility at the bumped version', () => {
131
+ it('advertises 0.2.0 and gates plugin compatibility.mobile ranges against it', () => {
132
+ expect(MOBILE_RENDERER_VERSION).toBe('0.2.0');
133
+ expect(isMobileRendererCompatible('^0.2.0')).toBe(true);
134
+ expect(isMobileRendererCompatible('^0.1.0')).toBe(false);
135
+ });
136
+ });
@@ -0,0 +1,115 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Mobile host-services bridge (mobile renderer contract, `MOBILE_RENDERER_VERSION`).
7
+ *
8
+ * A plugin's mobile package renders its UI (commonly inside an isolated
9
+ * WebView), but it MUST NOT own authenticated backend access. Instead the
10
+ * native mobile host registers an `IMobileHostServices` implementation at
11
+ * boot, and the plugin performs every protected API call through it. This
12
+ * keeps the access token, the 401-refresh round-trip, session-expiry, the
13
+ * API base URL, and client headers (`X-Client-Type: mobile`, locale) in the
14
+ * host — never inside plugin/WebView code.
15
+ *
16
+ * Design constraints:
17
+ * - Framework-agnostic: no `react` / `react-native` / `axios` imports here.
18
+ * The host wires its own HTTP client (e.g. the shared axios singleton)
19
+ * into `request`.
20
+ * - Singleton: the host calls {@link setMobileHostServices} once during
21
+ * boot; the plugin calls {@link getMobileHostServices} at runtime.
22
+ * - The token is intentionally NOT a required input to plugin calls. A
23
+ * plugin may read {@link IMobileHostServices.getAccessToken} only for
24
+ * non-sensitive bootstrapping; it must never implement its own refresh.
25
+ */
26
+
27
+ /** HTTP method accepted by the host request bridge. */
28
+ export type TMobileHostMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
29
+
30
+ /**
31
+ * A protected backend request the plugin asks the host to perform. The
32
+ * host prepends {@link IMobileHostServices.apiBaseUrl}, attaches the bearer
33
+ * token + client headers, and handles a single 401-refresh retry.
34
+ */
35
+ export interface IMobileHostRequest {
36
+ /**
37
+ * Path relative to the host API base, e.g.
38
+ * `/cms-api/v1/plugins/<id>/published/<key>`. Absolute URLs are rejected
39
+ * by the host so a plugin cannot redirect protected calls off-origin.
40
+ */
41
+ path: string;
42
+ /** HTTP method. Defaults to `GET`. */
43
+ method?: TMobileHostMethod;
44
+ /** JSON-serialisable request body (sent as `application/json`). */
45
+ body?: unknown;
46
+ /** Extra request headers (e.g. a plugin runtime-config echo header). */
47
+ headers?: Record<string, string>;
48
+ /** Query parameters appended to the path. */
49
+ query?: Record<string, string | number | boolean>;
50
+ }
51
+
52
+ /**
53
+ * Result of a host request. `data` is the parsed response body (the SelfHelp
54
+ * API envelope `{ status, message, data, ... }` for API routes), so the
55
+ * plugin reads `response.data.data` for the inner payload. `reason` mirrors
56
+ * the backend error discriminator (e.g. `already_submitted_once`) so the
57
+ * plugin can branch on lifecycle errors without re-parsing the body.
58
+ */
59
+ export interface IMobileHostResponse<TData = unknown> {
60
+ /** True for 2xx responses. */
61
+ ok: boolean;
62
+ /** HTTP status code (0 when the request never reached the server). */
63
+ status: number;
64
+ /** Parsed response body, or `null` when there is no JSON body. */
65
+ data: TData | null;
66
+ /** Backend error `reason` discriminator, when present. */
67
+ reason?: string;
68
+ /** Human-readable error message for non-ok responses. */
69
+ error?: string;
70
+ /**
71
+ * True when the call failed because the session could not be
72
+ * authenticated even after the host's refresh attempt (a 401 the host
73
+ * could not recover). The plugin should surface a "session expired"
74
+ * state rather than a generic error.
75
+ */
76
+ sessionExpired?: boolean;
77
+ }
78
+
79
+ /**
80
+ * Authenticated host services exposed to a plugin's mobile package. The
81
+ * host owns the token + refresh; the plugin only describes the request.
82
+ */
83
+ export interface IMobileHostServices {
84
+ /** Resolved API base URL the host calls (e.g. `https://cms.example.com`). */
85
+ apiBaseUrl(): string;
86
+ /**
87
+ * Current access token, or `null` when unauthenticated. Exposed only for
88
+ * non-sensitive bootstrapping (e.g. deciding whether to show a login
89
+ * prompt). Plugins must route protected calls through {@link request},
90
+ * which attaches the token host-side, instead of injecting this value.
91
+ */
92
+ getAccessToken(): string | null;
93
+ /** Perform an authenticated request with host-managed 401 refresh. */
94
+ request<TData = unknown>(req: IMobileHostRequest): Promise<IMobileHostResponse<TData>>;
95
+ }
96
+
97
+ let registeredHostServices: IMobileHostServices | null = null;
98
+
99
+ /**
100
+ * Register the host services implementation. Called once by the native
101
+ * mobile host during boot (before any plugin renders). Re-registering
102
+ * replaces the previous implementation (e.g. on a server switch).
103
+ */
104
+ export function setMobileHostServices(services: IMobileHostServices | null): void {
105
+ registeredHostServices = services;
106
+ }
107
+
108
+ /**
109
+ * Read the registered host services. Returns `null` when no host has
110
+ * registered yet — a plugin must treat that as "host too old / not ready"
111
+ * and degrade gracefully (it must never fall back to its own token logic).
112
+ */
113
+ export function getMobileHostServices(): IMobileHostServices | null {
114
+ return registeredHostServices;
115
+ }
@@ -88,6 +88,14 @@ export type {
88
88
 
89
89
  export { definePlugin, defineMobilePlugin, definePluginRealtimeTopic } from './define';
90
90
 
91
+ export type {
92
+ IMobileHostServices,
93
+ IMobileHostRequest,
94
+ IMobileHostResponse,
95
+ TMobileHostMethod,
96
+ } from './host-services';
97
+ export { setMobileHostServices, getMobileHostServices } from './host-services';
98
+
91
99
  export type {
92
100
  IRealtimeTransport,
93
101
  TRealtimeTransportFactory,
@@ -31,8 +31,13 @@ export const PLUGIN_API_VERSION = '0.1.0' as const;
31
31
  *
32
32
  * Bump rules mirror the SDK contract: patch = additive fix, minor = additive
33
33
  * renderer feature, major = breaking mobile renderer change.
34
+ *
35
+ * `0.2.0` adds the typed mobile host-services bridge (`IMobileHostServices` +
36
+ * `set/getMobileHostServices`) so a plugin's mobile package routes protected
37
+ * API calls through the native host (token + 401-refresh owned host-side)
38
+ * instead of injecting raw tokens — an additive renderer feature.
34
39
  */
35
- export const MOBILE_RENDERER_VERSION = '0.1.0' as const;
40
+ export const MOBILE_RENDERER_VERSION = '0.2.0' as const;
36
41
 
37
42
  export interface ISemver {
38
43
  major: number;