@selfhelp/shared 1.15.1 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,31 @@ 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.15.2
13
+
14
+ **Live Preview bridge contract** — the `postMessage` protocol that keeps the CMS
15
+ **Live Preview** shell and its two embedded frames (web frontend +
16
+ `selfhelp-mobile-preview`) on the same page. Clicking a link in one frame reports
17
+ the navigation up to the shell, which drives the other frame to the same CMS
18
+ keyword (with a per-frame loop guard). Additive only — new module + exports — so
19
+ `^1.15.x` consumers are unaffected; the frontend (`>=0.1.35`) and mobile
20
+ (`>=0.1.14`) Live Preview adopt it.
21
+
22
+ ### Added (additive, non-breaking)
23
+
24
+ - **`types/preview-bridge.ts`** (re-exported from the root): the single source of
25
+ truth for the bridge protocol —
26
+ - message-type constants `PREVIEW_BRIDGE_MESSAGE` (`READY` / `NAVIGATED` /
27
+ `NAVIGATE`) + `TPreviewBridgeMessageType`;
28
+ - activation/origin query-param names `PREVIEW_SHELL_PARAM` (`previewShell`) and
29
+ `PREVIEW_PARENT_ORIGIN_PARAM` (`parentOrigin`);
30
+ - payload shapes `IPreviewReadyMessage`, `IPreviewNavigatedMessage`,
31
+ `IPreviewNavigateCommand`, the `TPreviewBridgeMessage` union, and
32
+ `TPreviewFrameSource`;
33
+ - runtime helpers `isPreviewBridgeMessage(value)` (defensive guard for
34
+ `event.data`) and `previewKeywordFromPath(path)` (web/mobile paths → the same
35
+ keyword sync unit). Covered by `types/__tests__/preview-bridge.test.ts`.
36
+
12
37
  ## v1.15.1
13
38
 
14
39
  Mobile preview RN/Expo provenance parity **plus the CMS-driven mobile-preview
package/dist/index.d.mts CHANGED
@@ -846,6 +846,100 @@ interface IMobilePreviewExchangeData {
846
846
  }
847
847
  type IMobilePreviewExchangeResponse = IBaseApiResponse<IMobilePreviewExchangeData>;
848
848
 
849
+ /**
850
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
851
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
852
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
853
+ * web image).
854
+ *
855
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
856
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
857
+ * "navigate to keyword" command down from the shell, so clicking a link in one
858
+ * frame keeps the other frame on the same page. The shell prevents sync loops
859
+ * with a per-frame "expected keyword" guard (it ignores the echo of a command it
860
+ * just sent). See the frontend `LivePreview` shell + `PreviewShellBridge` and the
861
+ * mobile `PreviewSyncBridge`.
862
+ *
863
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
864
+ * activation/origin query-param names, the payload shapes, and the runtime type
865
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
866
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
867
+ *
868
+ * Security: messages are validated by `event.origin` on both ends (the shell
869
+ * allow-lists its own origin for the web frame and the mobile origin for the
870
+ * mobile frame; each frame trusts only the shell origin it was handed via
871
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
872
+ */
873
+ /** Which embedded preview frame a bridge message refers to. */
874
+ type TPreviewFrameSource = 'web' | 'mobile';
875
+ /**
876
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
877
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
878
+ * so a real visitor never posts navigation messages.
879
+ */
880
+ declare const PREVIEW_SHELL_PARAM = "previewShell";
881
+ /**
882
+ * Query param carrying the shell's `window.location.origin` so a (possibly
883
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
884
+ */
885
+ declare const PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
886
+ /**
887
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
888
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
889
+ */
890
+ declare const PREVIEW_BRIDGE_MESSAGE: {
891
+ /** frame → shell: the bridge mounted and is ready to sync. */
892
+ readonly READY: "selfhelp-preview:ready";
893
+ /** frame → shell: the frame navigated to a new in-app location. */
894
+ readonly NAVIGATED: "selfhelp-preview:navigated";
895
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
896
+ readonly NAVIGATE: "selfhelp-preview:navigate";
897
+ };
898
+ type TPreviewBridgeMessageType = (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
899
+ /** frame → shell: emitted once when the bridge mounts. */
900
+ interface IPreviewReadyMessage {
901
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
902
+ source: TPreviewFrameSource;
903
+ }
904
+ /**
905
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
906
+ * the current page (the cross-platform sync unit), or `null` for home / a
907
+ * non-CMS location. `locale` is the frame's active locale when known — a
908
+ * read-only toolbar indicator; locales are NOT cross-synced.
909
+ */
910
+ interface IPreviewNavigatedMessage {
911
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
912
+ source: TPreviewFrameSource;
913
+ keyword: string | null;
914
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
915
+ href: string;
916
+ locale?: string | null;
917
+ }
918
+ /**
919
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
920
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
921
+ * state and the embedded dev client are preserved.
922
+ */
923
+ interface IPreviewNavigateCommand {
924
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
925
+ keyword: string | null;
926
+ }
927
+ /** Every message that can cross the preview bridge, in either direction. */
928
+ type TPreviewBridgeMessage = IPreviewReadyMessage | IPreviewNavigatedMessage | IPreviewNavigateCommand;
929
+ /**
930
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
931
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
932
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
933
+ */
934
+ declare function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage;
935
+ /**
936
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
937
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
938
+ * Shared so the web and mobile bridges derive identical keywords from their
939
+ * respective routers.
940
+ */
941
+ declare function previewKeywordFromPath(path: string | null | undefined): string | null;
942
+
849
943
  /**
850
944
  * Cross-repo SelfHelp distribution contracts: registry index + release metadata
851
945
  * (core / frontend / scheduler / worker / plugin), security advisories,
@@ -1894,4 +1988,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1894
1988
  */
1895
1989
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1896
1990
 
1897
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
1991
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IPreviewNavigateCommand, type IPreviewNavigatedMessage, type IPreviewReadyMessage, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, PREVIEW_BRIDGE_MESSAGE, PREVIEW_PARENT_ORIGIN_PARAM, PREVIEW_SHELL_PARAM, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, type TPreviewBridgeMessage, type TPreviewBridgeMessageType, type TPreviewFrameSource, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, isPreviewBridgeMessage, parseInlineRich, parseSpacing, previewKeywordFromPath, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.d.ts CHANGED
@@ -846,6 +846,100 @@ interface IMobilePreviewExchangeData {
846
846
  }
847
847
  type IMobilePreviewExchangeResponse = IBaseApiResponse<IMobilePreviewExchangeData>;
848
848
 
849
+ /**
850
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
851
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
852
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
853
+ * web image).
854
+ *
855
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
856
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
857
+ * "navigate to keyword" command down from the shell, so clicking a link in one
858
+ * frame keeps the other frame on the same page. The shell prevents sync loops
859
+ * with a per-frame "expected keyword" guard (it ignores the echo of a command it
860
+ * just sent). See the frontend `LivePreview` shell + `PreviewShellBridge` and the
861
+ * mobile `PreviewSyncBridge`.
862
+ *
863
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
864
+ * activation/origin query-param names, the payload shapes, and the runtime type
865
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
866
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
867
+ *
868
+ * Security: messages are validated by `event.origin` on both ends (the shell
869
+ * allow-lists its own origin for the web frame and the mobile origin for the
870
+ * mobile frame; each frame trusts only the shell origin it was handed via
871
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
872
+ */
873
+ /** Which embedded preview frame a bridge message refers to. */
874
+ type TPreviewFrameSource = 'web' | 'mobile';
875
+ /**
876
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
877
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
878
+ * so a real visitor never posts navigation messages.
879
+ */
880
+ declare const PREVIEW_SHELL_PARAM = "previewShell";
881
+ /**
882
+ * Query param carrying the shell's `window.location.origin` so a (possibly
883
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
884
+ */
885
+ declare const PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
886
+ /**
887
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
888
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
889
+ */
890
+ declare const PREVIEW_BRIDGE_MESSAGE: {
891
+ /** frame → shell: the bridge mounted and is ready to sync. */
892
+ readonly READY: "selfhelp-preview:ready";
893
+ /** frame → shell: the frame navigated to a new in-app location. */
894
+ readonly NAVIGATED: "selfhelp-preview:navigated";
895
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
896
+ readonly NAVIGATE: "selfhelp-preview:navigate";
897
+ };
898
+ type TPreviewBridgeMessageType = (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
899
+ /** frame → shell: emitted once when the bridge mounts. */
900
+ interface IPreviewReadyMessage {
901
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
902
+ source: TPreviewFrameSource;
903
+ }
904
+ /**
905
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
906
+ * the current page (the cross-platform sync unit), or `null` for home / a
907
+ * non-CMS location. `locale` is the frame's active locale when known — a
908
+ * read-only toolbar indicator; locales are NOT cross-synced.
909
+ */
910
+ interface IPreviewNavigatedMessage {
911
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
912
+ source: TPreviewFrameSource;
913
+ keyword: string | null;
914
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
915
+ href: string;
916
+ locale?: string | null;
917
+ }
918
+ /**
919
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
920
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
921
+ * state and the embedded dev client are preserved.
922
+ */
923
+ interface IPreviewNavigateCommand {
924
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
925
+ keyword: string | null;
926
+ }
927
+ /** Every message that can cross the preview bridge, in either direction. */
928
+ type TPreviewBridgeMessage = IPreviewReadyMessage | IPreviewNavigatedMessage | IPreviewNavigateCommand;
929
+ /**
930
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
931
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
932
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
933
+ */
934
+ declare function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage;
935
+ /**
936
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
937
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
938
+ * Shared so the web and mobile bridges derive identical keywords from their
939
+ * respective routers.
940
+ */
941
+ declare function previewKeywordFromPath(path: string | null | undefined): string | null;
942
+
849
943
  /**
850
944
  * Cross-repo SelfHelp distribution contracts: registry index + release metadata
851
945
  * (core / frontend / scheduler / worker / plugin), security advisories,
@@ -1894,4 +1988,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1894
1988
  */
1895
1989
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1896
1990
 
1897
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
1991
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IPreviewNavigateCommand, type IPreviewNavigatedMessage, type IPreviewReadyMessage, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, PREVIEW_BRIDGE_MESSAGE, PREVIEW_PARENT_ORIGIN_PARAM, PREVIEW_SHELL_PARAM, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, type TPreviewBridgeMessage, type TPreviewBridgeMessageType, type TPreviewFrameSource, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, isPreviewBridgeMessage, parseInlineRich, parseSpacing, previewKeywordFromPath, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.js CHANGED
@@ -49,6 +49,9 @@ __export(index_exports, {
49
49
  LITERAL_CLASSES: () => LITERAL_CLASSES,
50
50
  MOBILE_PREVIEW_ENDPOINTS: () => MOBILE_PREVIEW_ENDPOINTS,
51
51
  PERMISSIONS: () => PERMISSIONS,
52
+ PREVIEW_BRIDGE_MESSAGE: () => PREVIEW_BRIDGE_MESSAGE,
53
+ PREVIEW_PARENT_ORIGIN_PARAM: () => PREVIEW_PARENT_ORIGIN_PARAM,
54
+ PREVIEW_SHELL_PARAM: () => PREVIEW_SHELL_PARAM,
52
55
  RADIUS_PX: () => RADIUS_PX,
53
56
  RELEASE_CHANNELS: () => RELEASE_CHANNELS,
54
57
  SIZE_VALUES: () => SIZE_VALUES,
@@ -75,6 +78,7 @@ __export(index_exports, {
75
78
  gridSpanToReactNativeColumn: () => gridSpanToReactNativeColumn,
76
79
  hasInlineFormatting: () => hasInlineFormatting,
77
80
  isKnownStyleName: () => isKnownStyleName,
81
+ isPreviewBridgeMessage: () => isPreviewBridgeMessage,
78
82
  isRegisteredStyleName: () => isRegisteredStyleName,
79
83
  isStyleAllowedOnPage: () => isStyleAllowedOnPage,
80
84
  isStylePlacementAllowed: () => isStylePlacementAllowed,
@@ -94,6 +98,7 @@ __export(index_exports, {
94
98
  parseDimensionToWeb: () => parseDimensionToWeb,
95
99
  parseInlineRich: () => parseInlineRich,
96
100
  parseSpacing: () => parseSpacing,
101
+ previewKeywordFromPath: () => previewKeywordFromPath,
97
102
  radiusToPx: () => radiusToPx,
98
103
  replaceCalcedValues: () => replaceCalcedValues,
99
104
  resolveAssetSources: () => resolveAssetSources,
@@ -211,6 +216,43 @@ var MOBILE_PREVIEW_ENDPOINTS = {
211
216
  EXCHANGE: `${MOBILE_PREVIEW_PREFIX}/mobile-preview/session/exchange`
212
217
  };
213
218
 
219
+ // src/types/preview-bridge.ts
220
+ var PREVIEW_SHELL_PARAM = "previewShell";
221
+ var PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
222
+ var PREVIEW_BRIDGE_MESSAGE = {
223
+ /** frame → shell: the bridge mounted and is ready to sync. */
224
+ READY: "selfhelp-preview:ready",
225
+ /** frame → shell: the frame navigated to a new in-app location. */
226
+ NAVIGATED: "selfhelp-preview:navigated",
227
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
228
+ NAVIGATE: "selfhelp-preview:navigate"
229
+ };
230
+ function isPreviewBridgeMessage(value) {
231
+ if (typeof value !== "object" || value === null) return false;
232
+ const record = value;
233
+ switch (record.type) {
234
+ case PREVIEW_BRIDGE_MESSAGE.READY:
235
+ return record.source === "web" || record.source === "mobile";
236
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
237
+ return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string";
238
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
239
+ return typeof record.keyword === "string" || record.keyword === null;
240
+ default:
241
+ return false;
242
+ }
243
+ }
244
+ function previewKeywordFromPath(path) {
245
+ if (!path) return null;
246
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? "";
247
+ const trimmed = withoutQuery.replace(/^\/+/, "").replace(/\/+$/, "");
248
+ if (trimmed === "") return null;
249
+ try {
250
+ return decodeURIComponent(trimmed);
251
+ } catch {
252
+ return trimmed;
253
+ }
254
+ }
255
+
214
256
  // src/types/distribution.ts
215
257
  var RELEASE_CHANNELS = ["stable", "beta", "nightly", "test"];
216
258
 
@@ -1543,6 +1585,9 @@ function transformPagesData(pages) {
1543
1585
  LITERAL_CLASSES,
1544
1586
  MOBILE_PREVIEW_ENDPOINTS,
1545
1587
  PERMISSIONS,
1588
+ PREVIEW_BRIDGE_MESSAGE,
1589
+ PREVIEW_PARENT_ORIGIN_PARAM,
1590
+ PREVIEW_SHELL_PARAM,
1546
1591
  RADIUS_PX,
1547
1592
  RELEASE_CHANNELS,
1548
1593
  SIZE_VALUES,
@@ -1569,6 +1614,7 @@ function transformPagesData(pages) {
1569
1614
  gridSpanToReactNativeColumn,
1570
1615
  hasInlineFormatting,
1571
1616
  isKnownStyleName,
1617
+ isPreviewBridgeMessage,
1572
1618
  isRegisteredStyleName,
1573
1619
  isStyleAllowedOnPage,
1574
1620
  isStylePlacementAllowed,
@@ -1588,6 +1634,7 @@ function transformPagesData(pages) {
1588
1634
  parseDimensionToWeb,
1589
1635
  parseInlineRich,
1590
1636
  parseSpacing,
1637
+ previewKeywordFromPath,
1591
1638
  radiusToPx,
1592
1639
  replaceCalcedValues,
1593
1640
  resolveAssetSources,
package/dist/index.mjs CHANGED
@@ -90,6 +90,43 @@ var MOBILE_PREVIEW_ENDPOINTS = {
90
90
  EXCHANGE: `${MOBILE_PREVIEW_PREFIX}/mobile-preview/session/exchange`
91
91
  };
92
92
 
93
+ // src/types/preview-bridge.ts
94
+ var PREVIEW_SHELL_PARAM = "previewShell";
95
+ var PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
96
+ var PREVIEW_BRIDGE_MESSAGE = {
97
+ /** frame → shell: the bridge mounted and is ready to sync. */
98
+ READY: "selfhelp-preview:ready",
99
+ /** frame → shell: the frame navigated to a new in-app location. */
100
+ NAVIGATED: "selfhelp-preview:navigated",
101
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
102
+ NAVIGATE: "selfhelp-preview:navigate"
103
+ };
104
+ function isPreviewBridgeMessage(value) {
105
+ if (typeof value !== "object" || value === null) return false;
106
+ const record = value;
107
+ switch (record.type) {
108
+ case PREVIEW_BRIDGE_MESSAGE.READY:
109
+ return record.source === "web" || record.source === "mobile";
110
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
111
+ return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string";
112
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
113
+ return typeof record.keyword === "string" || record.keyword === null;
114
+ default:
115
+ return false;
116
+ }
117
+ }
118
+ function previewKeywordFromPath(path) {
119
+ if (!path) return null;
120
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? "";
121
+ const trimmed = withoutQuery.replace(/^\/+/, "").replace(/\/+$/, "");
122
+ if (trimmed === "") return null;
123
+ try {
124
+ return decodeURIComponent(trimmed);
125
+ } catch {
126
+ return trimmed;
127
+ }
128
+ }
129
+
93
130
  // src/types/distribution.ts
94
131
  var RELEASE_CHANNELS = ["stable", "beta", "nightly", "test"];
95
132
 
@@ -1421,6 +1458,9 @@ export {
1421
1458
  LITERAL_CLASSES,
1422
1459
  MOBILE_PREVIEW_ENDPOINTS,
1423
1460
  PERMISSIONS,
1461
+ PREVIEW_BRIDGE_MESSAGE,
1462
+ PREVIEW_PARENT_ORIGIN_PARAM,
1463
+ PREVIEW_SHELL_PARAM,
1424
1464
  RADIUS_PX,
1425
1465
  RELEASE_CHANNELS,
1426
1466
  SIZE_VALUES,
@@ -1447,6 +1487,7 @@ export {
1447
1487
  gridSpanToReactNativeColumn,
1448
1488
  hasInlineFormatting,
1449
1489
  isKnownStyleName,
1490
+ isPreviewBridgeMessage,
1450
1491
  isRegisteredStyleName,
1451
1492
  isStyleAllowedOnPage,
1452
1493
  isStylePlacementAllowed,
@@ -1466,6 +1507,7 @@ export {
1466
1507
  parseDimensionToWeb,
1467
1508
  parseInlineRich,
1468
1509
  parseSpacing,
1510
+ previewKeywordFromPath,
1469
1511
  radiusToPx,
1470
1512
  replaceCalcedValues,
1471
1513
  resolveAssetSources,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.15.1",
3
+ "version": "1.15.2",
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,100 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Live Preview bridge contract tests.
7
+ *
8
+ * The shell and both frame bridges trust `isPreviewBridgeMessage` to narrow
9
+ * arbitrary cross-frame `postMessage` data, and derive the cross-platform sync
10
+ * unit with `previewKeywordFromPath`. These lock both: a malformed/foreign
11
+ * message must be rejected, a well-formed one in either direction accepted, and
12
+ * web/mobile paths must reduce to the same keyword (so sync can't drift).
13
+ */
14
+ import { describe, expect, it } from 'vitest';
15
+ import {
16
+ PREVIEW_BRIDGE_MESSAGE,
17
+ isPreviewBridgeMessage,
18
+ previewKeywordFromPath,
19
+ type TPreviewBridgeMessage,
20
+ } from '../preview-bridge';
21
+
22
+ describe('isPreviewBridgeMessage', () => {
23
+ it('accepts a frame->shell navigated message (the user clicked a link)', () => {
24
+ const msg: TPreviewBridgeMessage = {
25
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
26
+ source: 'web',
27
+ keyword: 'impressum',
28
+ href: '/impressum?previewShell=1',
29
+ locale: 'de-CH',
30
+ };
31
+ expect(isPreviewBridgeMessage(msg)).toBe(true);
32
+ });
33
+
34
+ it('accepts a navigated message for home (keyword null) and a ready message', () => {
35
+ expect(
36
+ isPreviewBridgeMessage({
37
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
38
+ source: 'mobile',
39
+ keyword: null,
40
+ href: '/',
41
+ }),
42
+ ).toBe(true);
43
+ expect(
44
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.READY, source: 'mobile' }),
45
+ ).toBe(true);
46
+ });
47
+
48
+ it('accepts a shell->frame navigate command (keyword or null)', () => {
49
+ expect(
50
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: 'team' }),
51
+ ).toBe(true);
52
+ expect(
53
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: null }),
54
+ ).toBe(true);
55
+ });
56
+
57
+ it('rejects foreign / malformed messages so cross-frame noise is ignored', () => {
58
+ expect(isPreviewBridgeMessage(null)).toBe(false);
59
+ expect(isPreviewBridgeMessage('selfhelp-preview:navigate')).toBe(false);
60
+ expect(isPreviewBridgeMessage({ type: 'webpack:hot-update' })).toBe(false);
61
+ // wrong source
62
+ expect(
63
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.READY, source: 'desktop' }),
64
+ ).toBe(false);
65
+ // navigated without href
66
+ expect(
67
+ isPreviewBridgeMessage({
68
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
69
+ source: 'web',
70
+ keyword: 'x',
71
+ }),
72
+ ).toBe(false);
73
+ // navigate with a non-string keyword
74
+ expect(
75
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: 5 }),
76
+ ).toBe(false);
77
+ });
78
+ });
79
+
80
+ describe('previewKeywordFromPath', () => {
81
+ it('reduces web and mobile paths to the same keyword (no drift)', () => {
82
+ expect(previewKeywordFromPath('/impressum')).toBe('impressum');
83
+ expect(previewKeywordFromPath('impressum')).toBe('impressum');
84
+ expect(previewKeywordFromPath('/impressum/')).toBe('impressum');
85
+ expect(previewKeywordFromPath('/impressum?previewShell=1')).toBe('impressum');
86
+ expect(previewKeywordFromPath('/impressum#section')).toBe('impressum');
87
+ });
88
+
89
+ it('treats home / empty as null (the shared "home" sentinel)', () => {
90
+ expect(previewKeywordFromPath('/')).toBeNull();
91
+ expect(previewKeywordFromPath('')).toBeNull();
92
+ expect(previewKeywordFromPath(null)).toBeNull();
93
+ expect(previewKeywordFromPath(undefined)).toBeNull();
94
+ });
95
+
96
+ it('keeps multi-segment keywords and decodes percent-encoding', () => {
97
+ expect(previewKeywordFromPath('/projects/alpha')).toBe('projects/alpha');
98
+ expect(previewKeywordFromPath('/caf%C3%A9')).toBe('café');
99
+ });
100
+ });
@@ -15,6 +15,7 @@ export * from './styles/unknown';
15
15
  export * from './pages';
16
16
  export * from './auth';
17
17
  export * from './api';
18
+ export * from './preview-bridge';
18
19
  export * from './distribution';
19
20
  export * from './mantine/common';
20
21
  export * from './mobile-adapters';
@@ -0,0 +1,139 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
7
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
8
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
9
+ * web image).
10
+ *
11
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
12
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
13
+ * "navigate to keyword" command down from the shell, so clicking a link in one
14
+ * frame keeps the other frame on the same page. The shell prevents sync loops
15
+ * with a per-frame "expected keyword" guard (it ignores the echo of a command it
16
+ * just sent). See the frontend `LivePreview` shell + `PreviewShellBridge` and the
17
+ * mobile `PreviewSyncBridge`.
18
+ *
19
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
20
+ * activation/origin query-param names, the payload shapes, and the runtime type
21
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
22
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
23
+ *
24
+ * Security: messages are validated by `event.origin` on both ends (the shell
25
+ * allow-lists its own origin for the web frame and the mobile origin for the
26
+ * mobile frame; each frame trusts only the shell origin it was handed via
27
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
28
+ */
29
+
30
+ /** Which embedded preview frame a bridge message refers to. */
31
+ export type TPreviewFrameSource = 'web' | 'mobile';
32
+
33
+ /**
34
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
35
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
36
+ * so a real visitor never posts navigation messages.
37
+ */
38
+ export const PREVIEW_SHELL_PARAM = 'previewShell';
39
+
40
+ /**
41
+ * Query param carrying the shell's `window.location.origin` so a (possibly
42
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
43
+ */
44
+ export const PREVIEW_PARENT_ORIGIN_PARAM = 'parentOrigin';
45
+
46
+ /**
47
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
48
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
49
+ */
50
+ export const PREVIEW_BRIDGE_MESSAGE = {
51
+ /** frame → shell: the bridge mounted and is ready to sync. */
52
+ READY: 'selfhelp-preview:ready',
53
+ /** frame → shell: the frame navigated to a new in-app location. */
54
+ NAVIGATED: 'selfhelp-preview:navigated',
55
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
56
+ NAVIGATE: 'selfhelp-preview:navigate',
57
+ } as const;
58
+
59
+ export type TPreviewBridgeMessageType =
60
+ (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
61
+
62
+ /** frame → shell: emitted once when the bridge mounts. */
63
+ export interface IPreviewReadyMessage {
64
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
65
+ source: TPreviewFrameSource;
66
+ }
67
+
68
+ /**
69
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
70
+ * the current page (the cross-platform sync unit), or `null` for home / a
71
+ * non-CMS location. `locale` is the frame's active locale when known — a
72
+ * read-only toolbar indicator; locales are NOT cross-synced.
73
+ */
74
+ export interface IPreviewNavigatedMessage {
75
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
76
+ source: TPreviewFrameSource;
77
+ keyword: string | null;
78
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
79
+ href: string;
80
+ locale?: string | null;
81
+ }
82
+
83
+ /**
84
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
85
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
86
+ * state and the embedded dev client are preserved.
87
+ */
88
+ export interface IPreviewNavigateCommand {
89
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
90
+ keyword: string | null;
91
+ }
92
+
93
+ /** Every message that can cross the preview bridge, in either direction. */
94
+ export type TPreviewBridgeMessage =
95
+ | IPreviewReadyMessage
96
+ | IPreviewNavigatedMessage
97
+ | IPreviewNavigateCommand;
98
+
99
+ /**
100
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
101
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
102
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
103
+ */
104
+ export function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage {
105
+ if (typeof value !== 'object' || value === null) return false;
106
+ const record = value as Record<string, unknown>;
107
+ switch (record.type) {
108
+ case PREVIEW_BRIDGE_MESSAGE.READY:
109
+ return record.source === 'web' || record.source === 'mobile';
110
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
111
+ return (
112
+ (record.source === 'web' || record.source === 'mobile') &&
113
+ (typeof record.keyword === 'string' || record.keyword === null) &&
114
+ typeof record.href === 'string'
115
+ );
116
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
117
+ return typeof record.keyword === 'string' || record.keyword === null;
118
+ default:
119
+ return false;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
125
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
126
+ * Shared so the web and mobile bridges derive identical keywords from their
127
+ * respective routers.
128
+ */
129
+ export function previewKeywordFromPath(path: string | null | undefined): string | null {
130
+ if (!path) return null;
131
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? '';
132
+ const trimmed = withoutQuery.replace(/^\/+/, '').replace(/\/+$/, '');
133
+ if (trimmed === '') return null;
134
+ try {
135
+ return decodeURIComponent(trimmed);
136
+ } catch {
137
+ return trimmed;
138
+ }
139
+ }