@selfhelp/shared 1.27.0 → 1.28.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/dist/index.js CHANGED
@@ -61,7 +61,10 @@ __export(index_exports, {
61
61
  FORM_RECORD_PREFILL_SKIP_FIELDS: () => FORM_RECORD_PREFILL_SKIP_FIELDS,
62
62
  FORM_SECTION_STYLE_NAMES: () => FORM_SECTION_STYLE_NAMES,
63
63
  FULL_RADIUS_PX: () => FULL_RADIUS_PX,
64
+ HEADER_ACL_STAMP: () => HEADER_ACL_STAMP,
64
65
  HEADER_CLIENT_TYPE: () => HEADER_CLIENT_TYPE,
66
+ HEADER_PAGE_VERSION: () => HEADER_PAGE_VERSION,
67
+ HEADER_PAGE_VIEW: () => HEADER_PAGE_VIEW,
65
68
  LINE_HEIGHT: () => LINE_HEIGHT,
66
69
  LITERAL_CLASSES: () => LITERAL_CLASSES,
67
70
  MOBILE_ICON_NAMES: () => MOBILE_ICON_NAMES,
@@ -72,6 +75,8 @@ __export(index_exports, {
72
75
  NAVIGATION_BUNDLE_VERSION: () => NAVIGATION_BUNDLE_VERSION,
73
76
  NAVIGATION_HEADER_LAYER_TOP: () => NAVIGATION_HEADER_LAYER_TOP,
74
77
  OPTION_STYLE_CONFIGS: () => OPTION_STYLE_CONFIGS,
78
+ PAGE_LOCKED_ERROR: () => PAGE_LOCKED_ERROR,
79
+ PAGE_VERSION_REQUIRED_ERROR: () => PAGE_VERSION_REQUIRED_ERROR,
75
80
  PERMISSIONS: () => PERMISSIONS,
76
81
  PREVIEW_BRIDGE_MESSAGE: () => PREVIEW_BRIDGE_MESSAGE,
77
82
  PREVIEW_PARENT_ORIGIN_PARAM: () => PREVIEW_PARENT_ORIGIN_PARAM,
@@ -82,7 +87,13 @@ __export(index_exports, {
82
87
  SPACING_PX: () => SPACING_PX,
83
88
  SPACING_TO_TAILWIND: () => SPACING_TO_TAILWIND,
84
89
  SPACING_VALUES: () => SPACING_VALUES,
90
+ STALE_PAGE_VERSION_ERROR: () => STALE_PAGE_VERSION_ERROR,
85
91
  STYLE_REGISTRY: () => STYLE_REGISTRY,
92
+ SYNC_CHANGED_MAX_DELAY_MS: () => SYNC_CHANGED_MAX_DELAY_MS,
93
+ SYNC_EVENT_NAME: () => SYNC_EVENT_NAME,
94
+ SYNC_MESSAGE_VERSION: () => SYNC_MESSAGE_VERSION,
95
+ SYNC_TAG_PATTERN: () => SYNC_TAG_PATTERN,
96
+ SYNC_VALID_UNTIL_MAX_DELAY_MS: () => SYNC_VALID_UNTIL_MAX_DELAY_MS,
86
97
  SYSTEM_ENDPOINTS: () => SYSTEM_ENDPOINTS,
87
98
  WEB_FOOTER_PRESET_OPTIONS: () => WEB_FOOTER_PRESET_OPTIONS,
88
99
  WEB_FOOTER_PRESET_VALUES: () => WEB_FOOTER_PRESET_VALUES,
@@ -180,6 +191,7 @@ __export(index_exports, {
180
191
  mergeHeaderLayers: () => mergeHeaderLayers,
181
192
  nextSortOnHeaderClick: () => nextSortOnHeaderClick,
182
193
  normalizePagesResolvePath: () => normalizePagesResolvePath,
194
+ pageDependsOn: () => pageDependsOn,
183
195
  pageUrlToMobileRoute: () => pageUrlToMobileRoute,
184
196
  parseDimensionToReactNative: () => parseDimensionToReactNative,
185
197
  parseDimensionToWeb: () => parseDimensionToWeb,
@@ -192,6 +204,8 @@ __export(index_exports, {
192
204
  parseOptionCodes: () => parseOptionCodes,
193
205
  parseOptionLabels: () => parseOptionLabels,
194
206
  parseSpacing: () => parseSpacing,
207
+ parseSyncMessage: () => parseSyncMessage,
208
+ parseSyncMessageJson: () => parseSyncMessageJson,
195
209
  pickFormListQuery: () => pickFormListQuery,
196
210
  previewKeywordFromPath: () => previewKeywordFromPath,
197
211
  radiusToPx: () => radiusToPx,
@@ -234,6 +248,7 @@ __export(index_exports, {
234
248
  splitHeaderLayers: () => splitHeaderLayers,
235
249
  stripHtmlToText: () => stripHtmlToText,
236
250
  stylePlatformToSet: () => stylePlatformToSet,
251
+ syncRefetchDelayMs: () => syncRefetchDelayMs,
237
252
  toHeroUiSemanticProps: () => toHeroUiSemanticProps,
238
253
  toMantineSemanticProps: () => toMantineSemanticProps,
239
254
  toReactNativeSemanticStyle: () => toReactNativeSemanticStyle,
@@ -721,8 +736,21 @@ var ENDPOINTS = {
721
736
  COMPARE: (tableName, recordId) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/compare`,
722
737
  RESTORE: (tableName, recordId) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/restore`,
723
738
  VERSION_FILE: (tableName, recordId, version, fieldKey) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/versions/${version}/files/${encodeURIComponent(fieldKey)}`
739
+ },
740
+ /**
741
+ * Page edit lock (live sync, C9). Route permission `admin.page.update` plus
742
+ * the update grant on the page. `LOCK` serves three methods: GET (status),
743
+ * POST (acquire or renew) and DELETE (release); `TAKE_OVER` is POST only.
744
+ * Every route answers an `IPageLockStatus`.
745
+ */
746
+ ADMIN_PAGE_LOCK: {
747
+ LOCK: (pageId) => `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock`,
748
+ TAKE_OVER: (pageId) => `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock/take-over`
724
749
  }
725
750
  };
751
+ var HEADER_ACL_STAMP = "X-Acl-Stamp";
752
+ var HEADER_PAGE_VIEW = "X-Page-View";
753
+ var HEADER_PAGE_VERSION = "X-Page-Version";
726
754
  var HEADER_CLIENT_TYPE = "X-Client-Type";
727
755
  var CLIENT_TYPE_WEB = "web";
728
756
  var CLIENT_TYPE_MOBILE = "mobile";
@@ -3255,6 +3283,52 @@ function expandedIdsForActiveTrail(items, pathname, platform) {
3255
3283
  return expanded;
3256
3284
  }
3257
3285
 
3286
+ // src/sync/types.ts
3287
+ var SYNC_EVENT_NAME = "changed";
3288
+ var SYNC_MESSAGE_VERSION = 1;
3289
+ var SYNC_TAG_PATTERN = /^(acl|navigation|global_values|page:\d+|page_draft:\d+|page_lock:\d+|table:\d+|section:\d+|asset:\d+)$/;
3290
+ var PAGE_VERSION_REQUIRED_ERROR = "page_version_required";
3291
+ var STALE_PAGE_VERSION_ERROR = "stale_page_version";
3292
+ var PAGE_LOCKED_ERROR = "page_locked";
3293
+
3294
+ // src/sync/sync.ts
3295
+ var SYNC_CHANGED_MAX_DELAY_MS = 300;
3296
+ var SYNC_VALID_UNTIL_MAX_DELAY_MS = 2e3;
3297
+ function isRecord(value) {
3298
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3299
+ }
3300
+ function parseSyncMessage(data) {
3301
+ if (!isRecord(data) || data.v !== SYNC_MESSAGE_VERSION || !Array.isArray(data.tags)) {
3302
+ return null;
3303
+ }
3304
+ const tags = [];
3305
+ for (const tag of data.tags) {
3306
+ if (typeof tag === "string" && SYNC_TAG_PATTERN.test(tag) && !tags.includes(tag)) {
3307
+ tags.push(tag);
3308
+ }
3309
+ }
3310
+ return tags.length === 0 ? null : { v: SYNC_MESSAGE_VERSION, tags };
3311
+ }
3312
+ function parseSyncMessageJson(raw) {
3313
+ try {
3314
+ return parseSyncMessage(JSON.parse(raw));
3315
+ } catch {
3316
+ return null;
3317
+ }
3318
+ }
3319
+ function pageDependsOn(sync, tags) {
3320
+ if (!sync || !Array.isArray(sync.depends_on) || sync.depends_on.length === 0) {
3321
+ return false;
3322
+ }
3323
+ return tags.some((tag) => sync.depends_on.includes(tag));
3324
+ }
3325
+ function syncRefetchDelayMs(kind, random = Math.random) {
3326
+ const max = kind === "changed" ? SYNC_CHANGED_MAX_DELAY_MS : SYNC_VALID_UNTIL_MAX_DELAY_MS;
3327
+ const r = random();
3328
+ const unit = Number.isFinite(r) ? Math.min(Math.max(r, 0), 1) : 0;
3329
+ return Math.min(max, Math.floor(unit * (max + 1)));
3330
+ }
3331
+
3258
3332
  // src/utils/spacing.ts
3259
3333
  var ALLOWED_KEYS = ["mt", "mb", "ms", "me", "pt", "pb", "ps", "pe"];
3260
3334
  function parseSpacing(raw) {
@@ -3352,7 +3426,10 @@ function transformPagesData(pages) {
3352
3426
  FORM_RECORD_PREFILL_SKIP_FIELDS,
3353
3427
  FORM_SECTION_STYLE_NAMES,
3354
3428
  FULL_RADIUS_PX,
3429
+ HEADER_ACL_STAMP,
3355
3430
  HEADER_CLIENT_TYPE,
3431
+ HEADER_PAGE_VERSION,
3432
+ HEADER_PAGE_VIEW,
3356
3433
  LINE_HEIGHT,
3357
3434
  LITERAL_CLASSES,
3358
3435
  MOBILE_ICON_NAMES,
@@ -3363,6 +3440,8 @@ function transformPagesData(pages) {
3363
3440
  NAVIGATION_BUNDLE_VERSION,
3364
3441
  NAVIGATION_HEADER_LAYER_TOP,
3365
3442
  OPTION_STYLE_CONFIGS,
3443
+ PAGE_LOCKED_ERROR,
3444
+ PAGE_VERSION_REQUIRED_ERROR,
3366
3445
  PERMISSIONS,
3367
3446
  PREVIEW_BRIDGE_MESSAGE,
3368
3447
  PREVIEW_PARENT_ORIGIN_PARAM,
@@ -3373,7 +3452,13 @@ function transformPagesData(pages) {
3373
3452
  SPACING_PX,
3374
3453
  SPACING_TO_TAILWIND,
3375
3454
  SPACING_VALUES,
3455
+ STALE_PAGE_VERSION_ERROR,
3376
3456
  STYLE_REGISTRY,
3457
+ SYNC_CHANGED_MAX_DELAY_MS,
3458
+ SYNC_EVENT_NAME,
3459
+ SYNC_MESSAGE_VERSION,
3460
+ SYNC_TAG_PATTERN,
3461
+ SYNC_VALID_UNTIL_MAX_DELAY_MS,
3377
3462
  SYSTEM_ENDPOINTS,
3378
3463
  WEB_FOOTER_PRESET_OPTIONS,
3379
3464
  WEB_FOOTER_PRESET_VALUES,
@@ -3471,6 +3556,7 @@ function transformPagesData(pages) {
3471
3556
  mergeHeaderLayers,
3472
3557
  nextSortOnHeaderClick,
3473
3558
  normalizePagesResolvePath,
3559
+ pageDependsOn,
3474
3560
  pageUrlToMobileRoute,
3475
3561
  parseDimensionToReactNative,
3476
3562
  parseDimensionToWeb,
@@ -3483,6 +3569,8 @@ function transformPagesData(pages) {
3483
3569
  parseOptionCodes,
3484
3570
  parseOptionLabels,
3485
3571
  parseSpacing,
3572
+ parseSyncMessage,
3573
+ parseSyncMessageJson,
3486
3574
  pickFormListQuery,
3487
3575
  previewKeywordFromPath,
3488
3576
  radiusToPx,
@@ -3525,6 +3613,7 @@ function transformPagesData(pages) {
3525
3613
  splitHeaderLayers,
3526
3614
  stripHtmlToText,
3527
3615
  stylePlatformToSet,
3616
+ syncRefetchDelayMs,
3528
3617
  toHeroUiSemanticProps,
3529
3618
  toMantineSemanticProps,
3530
3619
  toReactNativeSemanticStyle,
package/dist/index.mjs CHANGED
@@ -477,8 +477,21 @@ var ENDPOINTS = {
477
477
  COMPARE: (tableName, recordId) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/compare`,
478
478
  RESTORE: (tableName, recordId) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/restore`,
479
479
  VERSION_FILE: (tableName, recordId, version, fieldKey) => `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/versions/${version}/files/${encodeURIComponent(fieldKey)}`
480
+ },
481
+ /**
482
+ * Page edit lock (live sync, C9). Route permission `admin.page.update` plus
483
+ * the update grant on the page. `LOCK` serves three methods: GET (status),
484
+ * POST (acquire or renew) and DELETE (release); `TAKE_OVER` is POST only.
485
+ * Every route answers an `IPageLockStatus`.
486
+ */
487
+ ADMIN_PAGE_LOCK: {
488
+ LOCK: (pageId) => `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock`,
489
+ TAKE_OVER: (pageId) => `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock/take-over`
480
490
  }
481
491
  };
492
+ var HEADER_ACL_STAMP = "X-Acl-Stamp";
493
+ var HEADER_PAGE_VIEW = "X-Page-View";
494
+ var HEADER_PAGE_VERSION = "X-Page-Version";
482
495
  var HEADER_CLIENT_TYPE = "X-Client-Type";
483
496
  var CLIENT_TYPE_WEB = "web";
484
497
  var CLIENT_TYPE_MOBILE = "mobile";
@@ -3011,6 +3024,52 @@ function expandedIdsForActiveTrail(items, pathname, platform) {
3011
3024
  return expanded;
3012
3025
  }
3013
3026
 
3027
+ // src/sync/types.ts
3028
+ var SYNC_EVENT_NAME = "changed";
3029
+ var SYNC_MESSAGE_VERSION = 1;
3030
+ var SYNC_TAG_PATTERN = /^(acl|navigation|global_values|page:\d+|page_draft:\d+|page_lock:\d+|table:\d+|section:\d+|asset:\d+)$/;
3031
+ var PAGE_VERSION_REQUIRED_ERROR = "page_version_required";
3032
+ var STALE_PAGE_VERSION_ERROR = "stale_page_version";
3033
+ var PAGE_LOCKED_ERROR = "page_locked";
3034
+
3035
+ // src/sync/sync.ts
3036
+ var SYNC_CHANGED_MAX_DELAY_MS = 300;
3037
+ var SYNC_VALID_UNTIL_MAX_DELAY_MS = 2e3;
3038
+ function isRecord(value) {
3039
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3040
+ }
3041
+ function parseSyncMessage(data) {
3042
+ if (!isRecord(data) || data.v !== SYNC_MESSAGE_VERSION || !Array.isArray(data.tags)) {
3043
+ return null;
3044
+ }
3045
+ const tags = [];
3046
+ for (const tag of data.tags) {
3047
+ if (typeof tag === "string" && SYNC_TAG_PATTERN.test(tag) && !tags.includes(tag)) {
3048
+ tags.push(tag);
3049
+ }
3050
+ }
3051
+ return tags.length === 0 ? null : { v: SYNC_MESSAGE_VERSION, tags };
3052
+ }
3053
+ function parseSyncMessageJson(raw) {
3054
+ try {
3055
+ return parseSyncMessage(JSON.parse(raw));
3056
+ } catch {
3057
+ return null;
3058
+ }
3059
+ }
3060
+ function pageDependsOn(sync, tags) {
3061
+ if (!sync || !Array.isArray(sync.depends_on) || sync.depends_on.length === 0) {
3062
+ return false;
3063
+ }
3064
+ return tags.some((tag) => sync.depends_on.includes(tag));
3065
+ }
3066
+ function syncRefetchDelayMs(kind, random = Math.random) {
3067
+ const max = kind === "changed" ? SYNC_CHANGED_MAX_DELAY_MS : SYNC_VALID_UNTIL_MAX_DELAY_MS;
3068
+ const r = random();
3069
+ const unit = Number.isFinite(r) ? Math.min(Math.max(r, 0), 1) : 0;
3070
+ return Math.min(max, Math.floor(unit * (max + 1)));
3071
+ }
3072
+
3014
3073
  // src/utils/spacing.ts
3015
3074
  var ALLOWED_KEYS = ["mt", "mb", "ms", "me", "pt", "pb", "ps", "pe"];
3016
3075
  function parseSpacing(raw) {
@@ -3107,7 +3166,10 @@ export {
3107
3166
  FORM_RECORD_PREFILL_SKIP_FIELDS,
3108
3167
  FORM_SECTION_STYLE_NAMES,
3109
3168
  FULL_RADIUS_PX,
3169
+ HEADER_ACL_STAMP,
3110
3170
  HEADER_CLIENT_TYPE,
3171
+ HEADER_PAGE_VERSION,
3172
+ HEADER_PAGE_VIEW,
3111
3173
  LINE_HEIGHT,
3112
3174
  LITERAL_CLASSES,
3113
3175
  MOBILE_ICON_NAMES,
@@ -3118,6 +3180,8 @@ export {
3118
3180
  NAVIGATION_BUNDLE_VERSION,
3119
3181
  NAVIGATION_HEADER_LAYER_TOP,
3120
3182
  OPTION_STYLE_CONFIGS,
3183
+ PAGE_LOCKED_ERROR,
3184
+ PAGE_VERSION_REQUIRED_ERROR,
3121
3185
  PERMISSIONS,
3122
3186
  PREVIEW_BRIDGE_MESSAGE,
3123
3187
  PREVIEW_PARENT_ORIGIN_PARAM,
@@ -3128,7 +3192,13 @@ export {
3128
3192
  SPACING_PX,
3129
3193
  SPACING_TO_TAILWIND,
3130
3194
  SPACING_VALUES,
3195
+ STALE_PAGE_VERSION_ERROR,
3131
3196
  STYLE_REGISTRY,
3197
+ SYNC_CHANGED_MAX_DELAY_MS,
3198
+ SYNC_EVENT_NAME,
3199
+ SYNC_MESSAGE_VERSION,
3200
+ SYNC_TAG_PATTERN,
3201
+ SYNC_VALID_UNTIL_MAX_DELAY_MS,
3132
3202
  SYSTEM_ENDPOINTS,
3133
3203
  WEB_FOOTER_PRESET_OPTIONS,
3134
3204
  WEB_FOOTER_PRESET_VALUES,
@@ -3226,6 +3296,7 @@ export {
3226
3296
  mergeHeaderLayers,
3227
3297
  nextSortOnHeaderClick,
3228
3298
  normalizePagesResolvePath,
3299
+ pageDependsOn,
3229
3300
  pageUrlToMobileRoute,
3230
3301
  parseDimensionToReactNative,
3231
3302
  parseDimensionToWeb,
@@ -3238,6 +3309,8 @@ export {
3238
3309
  parseOptionCodes,
3239
3310
  parseOptionLabels,
3240
3311
  parseSpacing,
3312
+ parseSyncMessage,
3313
+ parseSyncMessageJson,
3241
3314
  pickFormListQuery,
3242
3315
  previewKeywordFromPath,
3243
3316
  radiusToPx,
@@ -3280,6 +3353,7 @@ export {
3280
3353
  splitHeaderLayers,
3281
3354
  stripHtmlToText,
3282
3355
  stylePlatformToSet,
3356
+ syncRefetchDelayMs,
3283
3357
  toHeroUiSemanticProps,
3284
3358
  toMantineSemanticProps,
3285
3359
  toReactNativeSemanticStyle,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.27.0",
3
+ "version": "1.28.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",
@@ -103,8 +103,28 @@ export const ENDPOINTS = {
103
103
  VERSION_FILE: (tableName: string, recordId: number, version: number, fieldKey: string): string =>
104
104
  `${API_VERSION_PREFIX}/admin/data/tables/${encodeURIComponent(tableName)}/records/${recordId}/versions/${version}/files/${encodeURIComponent(fieldKey)}`,
105
105
  },
106
+ /**
107
+ * Page edit lock (live sync, C9). Route permission `admin.page.update` plus
108
+ * the update grant on the page. `LOCK` serves three methods: GET (status),
109
+ * POST (acquire or renew) and DELETE (release); `TAKE_OVER` is POST only.
110
+ * Every route answers an `IPageLockStatus`.
111
+ */
112
+ ADMIN_PAGE_LOCK: {
113
+ LOCK: (pageId: number): string => `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock`,
114
+ TAKE_OVER: (pageId: number): string =>
115
+ `${API_VERSION_PREFIX}/admin/pages/${pageId}/lock/take-over`,
116
+ },
106
117
  } as const;
107
118
 
119
+ /** Header on every response to a signed-in caller: the access stamp (live sync, C5). */
120
+ export const HEADER_ACL_STAMP = 'X-Acl-Stamp';
121
+
122
+ /** Request header `X-Page-View: 1`: the only page fetch per visit that counts as a view (C7, F135). */
123
+ export const HEADER_PAGE_VIEW = 'X-Page-View';
124
+
125
+ /** Draft-version header: sent with every page draft write, returned on page reads and writes (C8). */
126
+ export const HEADER_PAGE_VERSION = 'X-Page-Version';
127
+
108
128
  /** Header set the backend reads to switch page-access mode + condition platform var. */
109
129
  export const HEADER_CLIENT_TYPE = 'X-Client-Type';
110
130
  export const CLIENT_TYPE_WEB = 'web';
package/src/index.ts CHANGED
@@ -24,4 +24,5 @@ export * from './cms-classes';
24
24
  export * from './assets';
25
25
  export * from './content';
26
26
  export * from './navigation';
27
+ export * from './sync';
27
28
  export * from './utils';
@@ -0,0 +1,193 @@
1
+ /*
2
+ * SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ * SPDX-License-Identifier: MPL-2.0
4
+ */
5
+
6
+ import { describe, expect, it } from 'vitest';
7
+ import {
8
+ API_VERSION_PREFIX,
9
+ ENDPOINTS,
10
+ HEADER_ACL_STAMP,
11
+ HEADER_PAGE_VERSION,
12
+ HEADER_PAGE_VIEW,
13
+ SYNC_EVENT_NAME,
14
+ pageDependsOn,
15
+ parseSyncMessage,
16
+ parseSyncMessageJson,
17
+ syncRefetchDelayMs,
18
+ type IPageLockStatus,
19
+ type ISyncBlock,
20
+ } from '../../index';
21
+
22
+ describe('parseSyncMessage (C1)', () => {
23
+ it('accepts the contract example', () => {
24
+ expect(parseSyncMessage({ v: 1, tags: ['page:12', 'navigation'] })).toEqual({
25
+ v: 1,
26
+ tags: ['page:12', 'navigation'],
27
+ });
28
+ });
29
+
30
+ it('accepts every tag kind of the contract', () => {
31
+ const tags = [
32
+ 'acl',
33
+ 'navigation',
34
+ 'global_values',
35
+ 'page:1',
36
+ 'page_draft:2',
37
+ 'page_lock:3',
38
+ 'table:4',
39
+ 'section:5',
40
+ 'asset:6',
41
+ ];
42
+ expect(parseSyncMessage({ v: 1, tags })?.tags).toEqual(tags);
43
+ });
44
+
45
+ it('ignores a message of a higher version', () => {
46
+ expect(parseSyncMessage({ v: 2, tags: ['page:12'] })).toBeNull();
47
+ expect(parseSyncMessage({ v: 0, tags: ['page:12'] })).toBeNull();
48
+ expect(parseSyncMessage({ tags: ['page:12'] })).toBeNull();
49
+ });
50
+
51
+ it('returns null for anything that is not an object with a tag list', () => {
52
+ expect(parseSyncMessage(null)).toBeNull();
53
+ expect(parseSyncMessage(undefined)).toBeNull();
54
+ expect(parseSyncMessage('{"v":1,"tags":["page:1"]}')).toBeNull();
55
+ expect(parseSyncMessage(['page:1'])).toBeNull();
56
+ expect(parseSyncMessage({ v: 1, tags: 'page:1' })).toBeNull();
57
+ expect(parseSyncMessage({ v: 1 })).toBeNull();
58
+ });
59
+
60
+ it('returns null for an empty tag list or one with no known tag', () => {
61
+ expect(parseSyncMessage({ v: 1, tags: [] })).toBeNull();
62
+ expect(parseSyncMessage({ v: 1, tags: ['foo:1', 'page:x'] })).toBeNull();
63
+ });
64
+
65
+ it('drops unknown and malformed tags and keeps the valid ones', () => {
66
+ expect(
67
+ parseSyncMessage({
68
+ v: 1,
69
+ tags: ['foo:1', 'page:12', 'page:', 'page:12x', ' table:3', 7, null, 'table:31'],
70
+ }),
71
+ ).toEqual({ v: 1, tags: ['page:12', 'table:31'] });
72
+ });
73
+
74
+ it('removes duplicate tags', () => {
75
+ expect(parseSyncMessage({ v: 1, tags: ['page:12', 'acl', 'page:12', 'acl'] })?.tags).toEqual([
76
+ 'page:12',
77
+ 'acl',
78
+ ]);
79
+ });
80
+ });
81
+
82
+ describe('parseSyncMessageJson', () => {
83
+ it('reads the raw data of a server-sent event', () => {
84
+ expect(parseSyncMessageJson('{"v":1,"tags":["table:31"]}')).toEqual({ v: 1, tags: ['table:31'] });
85
+ });
86
+
87
+ it('returns null for invalid JSON or an invalid message', () => {
88
+ expect(parseSyncMessageJson('not json')).toBeNull();
89
+ expect(parseSyncMessageJson('')).toBeNull();
90
+ expect(parseSyncMessageJson('{"v":2,"tags":["page:1"]}')).toBeNull();
91
+ });
92
+ });
93
+
94
+ describe('pageDependsOn (C6)', () => {
95
+ const sync: ISyncBlock = {
96
+ depends_on: ['page:12', 'table:31', 'global_values'],
97
+ valid_until: null,
98
+ };
99
+
100
+ it('is true when a tag is listed in depends_on', () => {
101
+ expect(pageDependsOn(sync, ['page:12'])).toBe(true);
102
+ expect(pageDependsOn(sync, ['navigation', 'table:31'])).toBe(true);
103
+ });
104
+
105
+ it('is false for a page, table or draft the payload does not name', () => {
106
+ expect(pageDependsOn(sync, ['page:13'])).toBe(false);
107
+ expect(pageDependsOn(sync, ['table:32'])).toBe(false);
108
+ expect(pageDependsOn(sync, ['page_draft:12'])).toBe(false);
109
+ });
110
+
111
+ it('matches global_values because a page payload lists it', () => {
112
+ expect(pageDependsOn(sync, ['global_values'])).toBe(true);
113
+ expect(pageDependsOn({ depends_on: ['page:1'], valid_until: null }, ['global_values'])).toBe(false);
114
+ });
115
+
116
+ it('never matches acl and navigation: those refresh every page, not a listed one', () => {
117
+ expect(pageDependsOn(sync, ['acl'])).toBe(false);
118
+ expect(pageDependsOn(sync, ['navigation'])).toBe(false);
119
+ });
120
+
121
+ it('matches page_draft only for a draft payload', () => {
122
+ const draft: ISyncBlock = { depends_on: ['page_draft:12', 'table:31'], valid_until: null };
123
+ expect(pageDependsOn(draft, ['page_draft:12'])).toBe(true);
124
+ expect(pageDependsOn(draft, ['page:12'])).toBe(false);
125
+ });
126
+
127
+ it('is false without a sync block or an empty list', () => {
128
+ expect(pageDependsOn(undefined, ['page:12'])).toBe(false);
129
+ expect(pageDependsOn(null, ['page:12'])).toBe(false);
130
+ expect(pageDependsOn({ depends_on: [], valid_until: null }, ['page:12'])).toBe(false);
131
+ expect(pageDependsOn(sync, [])).toBe(false);
132
+ });
133
+ });
134
+
135
+ describe('syncRefetchDelayMs', () => {
136
+ it('stays within 0 to 300 ms for a pushed change', () => {
137
+ expect(syncRefetchDelayMs('changed', () => 0)).toBe(0);
138
+ expect(syncRefetchDelayMs('changed', () => 0.5)).toBe(150);
139
+ expect(syncRefetchDelayMs('changed', () => 0.999999)).toBe(300);
140
+ expect(syncRefetchDelayMs('changed', () => 1)).toBe(300);
141
+ });
142
+
143
+ it('stays within 0 to 2000 ms for valid_until', () => {
144
+ expect(syncRefetchDelayMs('valid_until', () => 0)).toBe(0);
145
+ expect(syncRefetchDelayMs('valid_until', () => 0.5)).toBe(1000);
146
+ expect(syncRefetchDelayMs('valid_until', () => 1)).toBe(2000);
147
+ });
148
+
149
+ it('clamps a misbehaving random source', () => {
150
+ expect(syncRefetchDelayMs('changed', () => -3)).toBe(0);
151
+ expect(syncRefetchDelayMs('changed', () => 7)).toBe(300);
152
+ expect(syncRefetchDelayMs('changed', () => Number.NaN)).toBe(0);
153
+ });
154
+
155
+ it('uses Math.random by default and returns an integer in range', () => {
156
+ for (let i = 0; i < 50; i++) {
157
+ const ms = syncRefetchDelayMs('changed');
158
+ expect(Number.isInteger(ms)).toBe(true);
159
+ expect(ms).toBeGreaterThanOrEqual(0);
160
+ expect(ms).toBeLessThanOrEqual(300);
161
+ }
162
+ });
163
+ });
164
+
165
+ describe('sync constants and endpoints', () => {
166
+ it('names the event and the three headers as the backend does', () => {
167
+ expect(SYNC_EVENT_NAME).toBe('changed');
168
+ expect(HEADER_ACL_STAMP).toBe('X-Acl-Stamp');
169
+ expect(HEADER_PAGE_VIEW).toBe('X-Page-View');
170
+ expect(HEADER_PAGE_VERSION).toBe('X-Page-Version');
171
+ });
172
+
173
+ it('builds the four page lock routes (C9)', () => {
174
+ expect(ENDPOINTS.ADMIN_PAGE_LOCK.LOCK(12)).toBe(`${API_VERSION_PREFIX}/admin/pages/12/lock`);
175
+ expect(ENDPOINTS.ADMIN_PAGE_LOCK.TAKE_OVER(12)).toBe(
176
+ `${API_VERSION_PREFIX}/admin/pages/12/lock/take-over`,
177
+ );
178
+ });
179
+
180
+ it('types the lock status the way the contract example shows it', () => {
181
+ const status: IPageLockStatus = {
182
+ page_id: 12,
183
+ held: true,
184
+ mine: false,
185
+ holder: { id: 7, name: 'Anna Muster' },
186
+ expires_at: '2026-11-20T10:02:00Z',
187
+ idle_expires_at: '2026-11-20T10:15:00Z',
188
+ };
189
+ expect(Object.keys(status).sort()).toEqual(
190
+ ['expires_at', 'held', 'holder', 'idle_expires_at', 'mine', 'page_id'],
191
+ );
192
+ });
193
+ });
@@ -0,0 +1,6 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ export * from './types';
6
+ export * from './sync';
@@ -0,0 +1,106 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Small, pure helpers both clients use to read a change message and match it
7
+ * to what is on screen (contracts C1 and C6). They hold no state, touch no
8
+ * network and never decide access: they only compare tags the server sent
9
+ * with tags the server put into the page payload.
10
+ */
11
+ import {
12
+ SYNC_MESSAGE_VERSION,
13
+ SYNC_TAG_PATTERN,
14
+ type ISyncBlock,
15
+ type ISyncChangeMessage,
16
+ type TSyncTag,
17
+ } from './types';
18
+
19
+ /** Largest random delay before a refetch caused by a `changed` message (decision "instant"). */
20
+ export const SYNC_CHANGED_MAX_DELAY_MS = 300;
21
+
22
+ /** Largest random delay before the one refetch at a page's `valid_until`. */
23
+ export const SYNC_VALID_UNTIL_MAX_DELAY_MS = 2000;
24
+
25
+ /** Why a refetch is scheduled: a pushed change, or the page's own `valid_until`. */
26
+ export type TSyncRefetchKind = 'changed' | 'valid_until';
27
+
28
+ function isRecord(value: unknown): value is Record<string, unknown> {
29
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
30
+ }
31
+
32
+ /**
33
+ * Validates the data of a `changed` event (C1).
34
+ *
35
+ * Returns `null` when the data is not an object, `v` is not
36
+ * {@link SYNC_MESSAGE_VERSION} (a higher version is ignored by design), `tags`
37
+ * is not a list, or no known tag is left. Unknown tags are dropped and
38
+ * duplicates are removed, so `{ v: 1, tags: ['page:12', 'foo:1'] }` gives
39
+ * `{ v: 1, tags: ['page:12'] }`. A message that carries only unknown tags
40
+ * returns `null` because there is nothing a client could act on.
41
+ */
42
+ export function parseSyncMessage(data: unknown): ISyncChangeMessage | null {
43
+ if (!isRecord(data) || data.v !== SYNC_MESSAGE_VERSION || !Array.isArray(data.tags)) {
44
+ return null;
45
+ }
46
+
47
+ const tags: TSyncTag[] = [];
48
+ for (const tag of data.tags as unknown[]) {
49
+ if (typeof tag === 'string' && SYNC_TAG_PATTERN.test(tag) && !tags.includes(tag as TSyncTag)) {
50
+ tags.push(tag as TSyncTag);
51
+ }
52
+ }
53
+
54
+ return tags.length === 0 ? null : { v: SYNC_MESSAGE_VERSION, tags };
55
+ }
56
+
57
+ /**
58
+ * Same as {@link parseSyncMessage} for the raw `data` string of a server-sent
59
+ * event. Invalid JSON returns `null`.
60
+ */
61
+ export function parseSyncMessageJson(raw: string): ISyncChangeMessage | null {
62
+ try {
63
+ return parseSyncMessage(JSON.parse(raw) as unknown);
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * True when a page payload's `sync.depends_on` names any of the message's tags (C6).
71
+ *
72
+ * Only tags that a page payload can list match here: `page:<id>`,
73
+ * `page_draft:<id>`, `table:<id>` and `global_values`. The other tags are not
74
+ * page dependencies and are handled by the client on their own:
75
+ *
76
+ * - `acl` and `navigation` affect every page the caller may see, so the client
77
+ * invalidates all page queries and the navigation (it does not ask each page).
78
+ * - `page_lock:<id>`, `section:<id>` and `asset:<id>` are editor-side tags;
79
+ * the admin screens that show them refetch their own queries.
80
+ *
81
+ * A page without a `sync` block (older server, error payload) never matches.
82
+ */
83
+ export function pageDependsOn(
84
+ sync: ISyncBlock | null | undefined,
85
+ tags: readonly string[],
86
+ ): boolean {
87
+ if (!sync || !Array.isArray(sync.depends_on) || sync.depends_on.length === 0) {
88
+ return false;
89
+ }
90
+ return tags.some((tag) => sync.depends_on.includes(tag));
91
+ }
92
+
93
+ /**
94
+ * Random delay in milliseconds before a refetch: 0 to 300 for a `changed`
95
+ * message, 0 to 2000 for `valid_until`. It spreads many clients over a short
96
+ * time without making a change feel slow. `random` is injectable for tests.
97
+ */
98
+ export function syncRefetchDelayMs(
99
+ kind: TSyncRefetchKind,
100
+ random: () => number = Math.random,
101
+ ): number {
102
+ const max = kind === 'changed' ? SYNC_CHANGED_MAX_DELAY_MS : SYNC_VALID_UNTIL_MAX_DELAY_MS;
103
+ const r = random();
104
+ const unit = Number.isFinite(r) ? Math.min(Math.max(r, 0), 1) : 0;
105
+ return Math.min(max, Math.floor(unit * (max + 1)));
106
+ }