@bygghammar/cms-platform 0.90.0-m7.1 → 0.90.0-m7.10

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +244 -0
  2. package/README.md +16 -2
  3. package/docs/EDIT-LOCKS.md +213 -0
  4. package/migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql +274 -0
  5. package/package.json +11 -3
  6. package/scripts/create-cms-site.mjs +5 -4
  7. package/scripts/sync-migrations.mjs +27 -6
  8. package/src/backoffice/ContactDetailsView.tsx +19 -5
  9. package/src/backoffice/DomainsView.tsx +152 -25
  10. package/src/backoffice/EditLock.tsx +513 -0
  11. package/src/backoffice/EmailSettingsView.tsx +99 -0
  12. package/src/backoffice/FormEditorView.tsx +531 -512
  13. package/src/backoffice/FormSettingsView.tsx +16 -4
  14. package/src/backoffice/GlobalSectionBuilderView.tsx +42 -11
  15. package/src/backoffice/NavigationView.tsx +35 -11
  16. package/src/backoffice/PageBuilderView.tsx +51 -16
  17. package/src/backoffice/RichTextEditor.tsx +50 -14
  18. package/src/backoffice/SectionEditorView.tsx +18 -6
  19. package/src/backoffice/SectionFormView.tsx +184 -31
  20. package/src/backoffice/TrackingView.tsx +247 -208
  21. package/src/backoffice/forms/VersionHistory.tsx +4 -2
  22. package/src/backoffice/inspectors/blocks.tsx +22 -1
  23. package/src/backoffice/inspectors/fields.tsx +21 -0
  24. package/src/backoffice/routes/host.ts +28 -0
  25. package/src/backoffice/routes/index.tsx +117 -15
  26. package/src/backoffice/routes/pages.tsx +10 -6
  27. package/src/backoffice/seo/PageSeoPanelView.tsx +215 -197
  28. package/src/backoffice/shell/domain-guard.ts +27 -14
  29. package/src/backoffice/shell/index.ts +5 -0
  30. package/src/backoffice/shell/use-resolved-config.tsx +67 -0
  31. package/src/backoffice/tracking-drafts.ts +150 -0
  32. package/src/blocks/components/CtaBannerBlock.tsx +18 -12
  33. package/src/blocks/components/HeroFullBlock.tsx +25 -12
  34. package/src/blocks/components/MediaSplitBlock.tsx +91 -41
  35. package/src/blocks/components/PriceTableBlock.tsx +123 -89
  36. package/src/blocks/components/RichTextBlock.tsx +26 -4
  37. package/src/blocks/index.ts +8 -0
  38. package/src/blocks/optional-content.ts +82 -0
  39. package/src/blocks/registry.tsx +1 -0
  40. package/src/blocks/types.ts +6 -0
  41. package/src/cms/edit-lock.ts +491 -0
  42. package/src/config/modules.ts +34 -10
  43. package/src/forms/FormRenderer.tsx +22 -0
  44. package/src/host/index.tsx +17 -0
  45. package/src/navigation/index.ts +29 -0
  46. package/src/popups/admin.tsx +55 -4
  47. package/src/popups/cms-bridges.ts +50 -10
  48. package/src/popups/destinations.tsx +7 -1
  49. package/src/popups/host.ts +9 -0
  50. package/src/popups/runtime.tsx +48 -14
  51. package/src/runtime/server-entry.ts +8 -2
  52. package/src/server/content-sections-core.ts +22 -5
  53. package/src/server/domains-core.ts +124 -107
  54. package/src/server/edit-lock-adapter.ts +91 -0
  55. package/src/server/edit-lock-supabase-adapter.ts +135 -0
  56. package/src/server/edit-locks-core.ts +286 -0
  57. package/src/server/forms-core.ts +37 -2
  58. package/src/server/injections-core.ts +230 -49
  59. package/src/server/page-seo-save-core.ts +27 -0
  60. package/src/server/pages-core.ts +108 -11
  61. package/src/server/provider-secrets.ts +100 -4
  62. package/src/server/schemas.ts +74 -9
  63. package/src/site/SiteHeader.tsx +11 -5
  64. package/src/site/host.ts +172 -0
  65. package/src/site/locale-domains.ts +500 -0
  66. package/src/site/routes.ts +206 -38
  67. package/src/site/site-url.ts +80 -17
  68. package/src/tracking/injections.ts +52 -9
  69. package/src/ui/Reveal.tsx +74 -9
package/CHANGELOG.md CHANGED
@@ -8,6 +8,250 @@ matches `package.json` exactly. See
8
8
  Versions 0.1.0 through 0.78.0 predate this repository and were reconstructed
9
9
  from the published npm tarballs.
10
10
 
11
+ ## 0.90.0-m7.10
12
+
13
+ - Code & tracking drafts survive a refetch. A background reload replaced the
14
+ table under the administrator's hands: a brand new profile, a duplicate made
15
+ from an existing one, and edits typed but not yet saved all disappeared
16
+ without a word. What the server sends is merged into what is on screen
17
+ instead of replacing it.
18
+ - Tracking profiles apply in global, then language, then domain order, so a
19
+ domain profile refines the language one rather than replacing it. Hostname
20
+ matching is consistent throughout: an apex and its single `www.` are the same
21
+ site everywhere the decision is made.
22
+ - GTM, GA4, Meta Pixel, TikTok Pixel, verification meta tags and raw
23
+ head / body-start / body-end code all reach the server-rendered HTML at the
24
+ position each one requires, rather than depending on a client-side step to
25
+ fire.
26
+ - Raw custom code is injected byte for byte. `$&`, `` $` ``, `$'` and `$$` in a
27
+ snippet were read as replacement patterns and rewrote the markup around them;
28
+ a profile now reaches the page exactly as it was typed.
29
+ - Tracking is excluded from the configured backoffice path, preview routes, API
30
+ routes and server-function routes, so pixels no longer fire on administrative
31
+ traffic or on responses that are not pages.
32
+ - A tracking read that fails leaves the public site standing. The page renders
33
+ without injection, the failure is reported through an injectable logger, and
34
+ it is not cached — the next request retries instead of serving a fabricated
35
+ empty configuration for the rest of the cache window. A backend that answers
36
+ with an error rather than throwing counts as a failure; treating it as "no
37
+ profiles" made a broken deployment indistinguishable from an unconfigured one.
38
+ - The tracking cache is bounded rather than growing one entry per hostname
39
+ seen, and a successful create, update or delete drops it, so a change goes
40
+ live within the TTL instead of sitting behind whatever was cached first.
41
+ - A failed audit entry or a failed log line cannot undo a write that already
42
+ happened. Both are best-effort in both directions: the mutation stands and is
43
+ reported as the success it was, rather than coming back as an error whose
44
+ obvious retry inserts a second profile. That now holds even when the
45
+ host-supplied logger is itself what throws.
46
+ - A newly created profile whose id the server cannot establish is held until the
47
+ page is reloaded. The insert may well have landed, so pressing Save again
48
+ would create a duplicate firing every pixel twice; the screen says to reload,
49
+ and saving existing profiles is unaffected.
50
+ - Languages & domains has moved out of the main sidebar into System
51
+ administration, alongside the other installation-level screens.
52
+ - Code & tracking and Languages & domains require the `admin` role, matching the
53
+ authorization their server functions already enforce. Staff without it get a
54
+ plain no-access screen instead of a form that fails on Save.
55
+ - Storing a hostname and matching a request against one are now separate
56
+ questions. Canonical output carries the exact hostname the deployment
57
+ configured; matching still folds an apex and one `www.` together. A page is no
58
+ longer canonical on two of its own addresses.
59
+ - Canonical URLs, `og:url`, hreflang, `og:locale:alternate` and both sitemaps
60
+ are built from the configured canonical hostnames.
61
+ - Rows written before the domain validator existed are ignored for matching and
62
+ for every generated URL, instead of being normalized into a plausible-looking
63
+ address. `ftp://example.com` no longer reduces to `example.com` and wins a
64
+ request for it — which had decided the locale, the tracking profiles that fire
65
+ and the backoffice hostname alike.
66
+ - In explicit domain-mapping mode a supported language with no configured domain
67
+ is left out of hreflang and sitemap alternates, instead of borrowing another
68
+ locale's origin — or the origin of the current request — and advertising a URL
69
+ this deployment may not serve.
70
+ - Single-origin multilingual sites are supported by the sitemap helpers.
71
+ `sitemapEntries` and `sitemapIndexEntries` take the public origin and emit
72
+ absolute URLs only. Previously a locale sitemap could come out carrying
73
+ relative URLs, while the sitemap index had no domain mappings from which to
74
+ build entries at all.
75
+ - Public locale-domain projections omit `isAdminDomain`. Which hostname serves
76
+ the backoffice is not something an anonymous reader needs to be told.
77
+ - `SITE_URL` is validated before it can become the authoritative admin hostname,
78
+ and as configured rather than after normalizing — normalizing strips the
79
+ scheme, so a value nobody can serve validated cleanly and was allowed to
80
+ override the database and switch off the check that stops an unreachable
81
+ admin domain being saved.
82
+ - Admin-host resolution fails open. An unusable flagged row falls through to the
83
+ next source instead of stranding the backoffice, the screen names which source
84
+ the hostname came from, and the banner refreshes when a domain is saved.
85
+ - **Host integration required after upgrading.** Nothing below is done by this
86
+ package on the host's behalf:
87
+ - expose the shared Languages & domains screen at the host's canonical
88
+ `/admin/domains` route;
89
+ - keep the old `/domains` route as a compatibility redirect where applicable;
90
+ - register `getEffectiveAdminHost` among the backoffice host functions, so
91
+ the screen can say where the backoffice actually is;
92
+ - use `siteCanonicalHost()` when passing `SITE_URL` authority, not the raw
93
+ environment value;
94
+ - pass the public origin to `sitemapEntries` and `sitemapIndexEntries` on
95
+ single-origin sites;
96
+ - pass the configured `backofficePath` into `createServerEntry`, or tracking
97
+ will be injected into the backoffice;
98
+ - split public-safe locale-domain reads from authenticated admin reads; and
99
+ - ensure the tracking-create server function returns the newly created
100
+ profile id, which the screen now requires before it will treat a create as
101
+ complete.
102
+ - No database migration is included in this release, and no database data is
103
+ changed by it.
104
+ - Not included and not yet verified: Voyara's own integration is not part of
105
+ this package release, and neither staging nor production has been verified
106
+ with `0.90.0-m7.10`.
107
+
108
+ ## 0.90.0-m7.9
109
+
110
+ - The email settings screen says where provider credentials actually go. An
111
+ administrator told only that "passwords are stored as server secrets" does the
112
+ one thing the sentence was meant to prevent and pastes the password into the
113
+ CMS field in front of them, so the screen names the configuration file, the
114
+ environment-variable names and the secret-name convention for that
115
+ installation instead. It stays value-free: no secret is read, returned or
116
+ rendered, and hosts supply their own deployment root through
117
+ `secretsLocation` — including `/`, which stays absolute.
118
+ - Optional block content whose localized value is empty is no longer rendered.
119
+ A heading or paragraph written in one locale and left blank in another used to
120
+ leave its empty markup behind in the locale that had nothing to say.
121
+ - Nested navigation items are editable. Only top-level entries could be changed,
122
+ so fixing a typo in a child link meant deleting it and building it again.
123
+ - Rich text holds up at length, and a block chooses how it appears. Each block
124
+ carries its own reveal mode; `Reveal` still defaults to `fade`, so every
125
+ already-published page looks exactly as it did.
126
+ - Cooperative editing locks stop two administrators overwriting each other. A
127
+ lock is taken when an editor opens a resource, renewed while it stays open and
128
+ released when it closes, and a second editor is told who holds it instead of
129
+ silently losing the earlier write. Pages, global sections, shared content,
130
+ navigation, contact details, forms, form defaults, form history and page SEO
131
+ are covered, and the refusal is enforced in the server cores — not only by
132
+ disabling controls in the interface.
133
+ - The lock's session token is private and the session match is exact.
134
+ `session_id` is never returned by any read: authenticated callers hold column
135
+ grants that omit it, the JSON shape drops it, and the administrator listing
136
+ returns a redacted row. A write against a live lock succeeds only for the
137
+ exact, non-empty session that holds it. Empty or malformed lock responses fail
138
+ closed rather than reading as "free", a stale asynchronous reply cannot revive
139
+ a lock that was already released, reopening an editor can no longer let its
140
+ own release overtake its next acquire, and a duplicated browser tab is given
141
+ its own session identity — Web Locks where the browser provides them, a
142
+ best-effort BroadcastChannel fallback where it does not.
143
+ - Lock storage is a host port, not a provider. `editLockActionCore` and
144
+ `assertEditable` reach the database only through `EditLockAdapter`
145
+ (`@bygghammar/cms-platform/server/edit-lock-adapter`) — five methods covering
146
+ acquire, status, release, list and the staff check — so an application on
147
+ ordinary PostgreSQL implements it with the SQL it already writes, with no
148
+ PostgREST client and no `supabase` object to imitate. Hosts that already build
149
+ `{ supabase: { rpc }, userId, claims }` for their other cores keep passing
150
+ exactly that: `createSupabaseEditLockAdapter` is applied for them
151
+ automatically and nothing on an existing host changes.
152
+ - Locks require a migration and host wiring, and change nothing until both are
153
+ done. `migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql`
154
+ creates the table and its functions; `docs/EDIT-LOCKS.md` is the host
155
+ contract: one authenticated server endpoint through `editLockActionCore`, one
156
+ `EditLockProvider` built with `createEditLockApi`, the non-empty
157
+ `editSessionId` forwarded to every protected write, `pageKey` passed to
158
+ `PageSeoPanelView`, and the `edit_locked:` message prefix preserved across the
159
+ host's own transport. Until then every screen behaves exactly as it did before
160
+ locks existed.
161
+ - The lock is a cooperative server preflight, not a transaction-atomic write
162
+ fence. The check and the mutation are separate statements, so a host needing
163
+ strict exclusion must put both in one transaction or RPC. Full-document exits
164
+ deliberately let the lock lapse by TTL — 120 seconds by default — rather than
165
+ race a reload against its own release.
166
+ - Verified on PostgreSQL 16 and 17: the migration applies in a single
167
+ transaction against a throwaway container carrying a host's real role,
168
+ authentication and user objects; the grants, the RLS policy and the
169
+ `SECURITY DEFINER` `search_path` come out as written; twenty simultaneous
170
+ acquires of one resource leave exactly one holder and no errors; and a
171
+ shadowing `pg_temp` object cannot reach inside a definer body.
172
+ - Not verified in this release: the migration has not been applied to any real
173
+ staging or production database, and the two-user real-browser lock behaviour
174
+ has not been exercised against a live host. Both remain required before
175
+ production use.
176
+
177
+ ## 0.90.0-m7.8
178
+
179
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.8`. `m7.6` and `m7.7` were
180
+ tagged and never published: two defects in the release workflow stopped them
181
+ after every gate had passed. The form-identity work they were meant to carry
182
+ is unchanged and ships here.
183
+ - The release workflow gets both corrections, proven in lightweight-popup:
184
+ the redundant post-checkout `git fetch` is gone (checkout already brings
185
+ every branch, and its credentials are removed on the way out), and
186
+ `npm pack`'s destination is created before it is packed into, with the same
187
+ directory carried to the tarball verification rather than spelled twice.
188
+ - `ops/verify-release-tag.mjs` checks `refs/remotes/origin/main` is present
189
+ before asking `merge-base` about it, so a checkout that fetched too little no
190
+ longer reports itself as a tag on an unmerged branch.
191
+
192
+ ## 0.90.0-m7.6
193
+
194
+ - A form submitted from inside a popup now says so. `FormRenderer` and
195
+ `ManagedForm` take an opaque `context` that is merged into the submission,
196
+ and the popup module fills it with `{ popupKey }` — the form system keeps
197
+ knowing nothing about the features that use it. Without this the request was
198
+ indistinguishable from the same form filled on an ordinary page, so the
199
+ server stored an ordinary entry and every delivery configured on the popup
200
+ silently did nothing.
201
+ - `HostSubmitFormInput` gains `popupKey?: string`, the only popup-shaped value
202
+ the browser sends. Destination, endpoint, signing secret and which fields may
203
+ leave are all read on the server from the popup's stored configuration.
204
+ - Drafts and the builder preview carry no context, so a part-filled form and an
205
+ editor checking a layout cannot fire a campaign's webhook.
206
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.6`, which is where the
207
+ identity comes from.
208
+
209
+ ## 0.90.0-m7.5
210
+
211
+ - `BackofficeHost.pages.fns.listPages` is declared. It was what
212
+ `cmsPageDirectory` had always looked for, read through an index cast because
213
+ the contract did not name it — so a site could not register it without a type
214
+ error, and every site that had not silently got a picker with nothing in it.
215
+ The top-level lookup stays for anyone who registered it there anyway.
216
+
217
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.5`. In `m7.4` an advanced
218
+ path rule could not be typed: the row was reclassified after the first
219
+ keystroke and disappeared. No change here beyond the floor — a site pairing
220
+ this with `m7.4` would get a picker whose rules field does not work.
221
+
222
+ ## 0.90.0-m7.4
223
+
224
+ - `cmsPageDirectory` takes the site's routing engine and asks it for each
225
+ page's public path, instead of assuming the page key is the path. The home
226
+ page is why: its key is `home` and its address is `/`, so the popup page
227
+ picker would have offered an address that matches nothing.
228
+ - The Popups screen supplies that resolver from the `usePageUrl` hook the
229
+ backoffice already registers — no new host field, no second pages query. The
230
+ hook is called from its own component so it stays unconditional while the
231
+ page group remains optional.
232
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.4`, which is where the
233
+ page picker itself lives.
234
+
235
+ ## 0.90.0-m7.3
236
+
237
+ - Popup exclusions are derived from the configured `backofficePath`, so a site
238
+ that mounts its office at `/admin` or `/cms/backoffice` is covered without
239
+ naming it twice. Both the tree and its landing page are excluded: `/admin/**`
240
+ does not match `/admin`.
241
+ - `registerPopupPublicHost` accepts `excludedPaths` for a site's own private
242
+ routes — a checkout, a members' area. The CMS adds to that list and never
243
+ replaces it, and drops duplicates rather than repeating a path.
244
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.3`, whose defaults no
245
+ longer name anyone's backoffice.
246
+
247
+ ## 0.90.0-m7.2
248
+
249
+ - `backofficePaths` gains `popups` and `popupDestinations`, and both popup
250
+ mount points supply them to the package's navigation. The destinations screen
251
+ was reachable only by typing its address.
252
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.2`, which is where the
253
+ navigation itself lives.
254
+
11
255
  ## 0.90.0-m7.1
12
256
 
13
257
  First version published to npm rather than vendored as a tarball. Same code as
package/README.md CHANGED
@@ -25,6 +25,14 @@ apply the canonical schema with `bunx cms-platform-migrations`, import
25
25
  `theme.css`, register host components / platform data / translations, wrap the
26
26
  server cores and mount the shared backoffice views.
27
27
 
28
+ ## Editing locks
29
+
30
+ `docs/EDIT-LOCKS.md` is what a host wires so two administrators cannot
31
+ overwrite each other: run the migration, expose one server endpoint through
32
+ `editLockActionCore`, mount `EditLockProvider` with `createEditLockApi`, and
33
+ forward `editSessionId` to the saves. Until that is done every screen behaves
34
+ exactly as it did before locks existed.
35
+
28
36
  ## Compatibility policy
29
37
 
30
38
  - `CHANGELOG.md` records every release; read it before upgrading.
@@ -119,8 +127,14 @@ bun run check # typecheck + tests + package verification
119
127
 
120
128
  The package ships TypeScript sources; there is no build output. Every change
121
129
  goes through a pull request, and every release is triggered by pushing a
122
- `vX.Y.Z` tag that matches `package.json`, which publishes to npm from GitHub
123
- Actions using the repository secret `NPM_TOKEN`. Never publish manually.
130
+ `vX.Y.Z` tag that matches `package.json`. That tag runs
131
+ `.github/workflows/publish.yml`, which publishes to npm using **Trusted
132
+ Publishing**: GitHub mints a short-lived OIDC token scoped to that single
133
+ workflow run, and npm exchanges it for publish rights through the package's
134
+ Trusted Publisher configuration. No long-lived npm credential takes part — no
135
+ `NPM_TOKEN`, no `NODE_AUTH_TOKEN`, no OTP. [RELEASING.md](./RELEASING.md) is
136
+ what the workflow checks and the npm settings it has to match. Never publish
137
+ manually.
124
138
 
125
139
  See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full workflow and changelog
126
140
  conventions. Consumers install an explicit released version such as
@@ -0,0 +1,213 @@
1
+ # Editing locks: what a host has to wire
2
+
3
+ Two administrators opening the same page used to be a silent race — whoever
4
+ saved last won, and the other one's work disappeared without a message. The
5
+ lock makes that a refusal instead: the second person sees who has the page and
6
+ cannot type into it, and the server refuses the write even if they try.
7
+
8
+ The package supplies all of it except three connections only the host can make.
9
+ Until they are made every screen behaves exactly as it did before locks
10
+ existed, which is what lets an installation upgrade the package first and the
11
+ database afterwards.
12
+
13
+ ## 1. Run the migration
14
+
15
+ `migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql` creates
16
+ `public.cms_edit_locks` and five functions. It is safe to run more than once.
17
+ It is ordinary PostgreSQL — a table, an index, grants, one RLS policy and four
18
+ `SECURITY DEFINER` functions with a pinned `search_path`. A host that stores
19
+ locks some other way can skip it and supply its own adapter instead; see
20
+ [Storage](#storage).
21
+
22
+ Until it runs, `assertEditable` sees "no such function" and lets every write
23
+ through — an upgrade cannot break saving. After it runs, the server checks are
24
+ available; the provider and save-path forwarding below are still required for
25
+ per-tab UI locking.
26
+
27
+ ## 2. One server endpoint
28
+
29
+ Every lock call goes through `editLockActionCore`, so the host writes one
30
+ server function rather than five:
31
+
32
+ ```ts
33
+ import { editLockActionCore, isEditLockAction } from "@bygghammar/cms-platform/server/edit-locks-core";
34
+ import { editLockSchemas } from "@bygghammar/cms-platform/server/schemas";
35
+
36
+ export const editLock = serverFn(async ({ data }) => {
37
+ if (!isEditLockAction(data.action)) throw new Error("Unknown lock action");
38
+ const input = editLockSchemas.acquire.parse(data);
39
+ return editLockActionCore(await authContext(), data.action, input);
40
+ });
41
+ ```
42
+
43
+ `authContext()` returns the lock storage for the signed-in user — see
44
+ [Storage](#storage) for what that is. The lock functions run as that user, so
45
+ `is_staff` and RLS apply exactly as they do everywhere else.
46
+
47
+ ## 3. One provider in the browser
48
+
49
+ ```tsx
50
+ import { useMemo } from "react";
51
+ import { createEditLockApi, EditLockProvider } from "@bygghammar/cms-platform/backoffice/EditLock";
52
+
53
+ const lockApi = useMemo(
54
+ () => createEditLockApi(
55
+ (action, input) => editLock({ data: { action, ...input } }),
56
+ { canSteal: isSuperadmin },
57
+ ),
58
+ [editLock, isSuperadmin],
59
+ );
60
+
61
+ <EditLockProvider api={lockApi}>{backoffice}</EditLockProvider>
62
+ ```
63
+
64
+ Mount it once, around the backoffice. Every editing screen finds it by itself.
65
+ Keep the API object stable with `useMemo`: its identity controls the editors'
66
+ acquire/release effects, so rebuilding it during each render would repeatedly
67
+ release and reacquire their locks.
68
+
69
+ `canSteal` only decides whether the take-over button is *offered*; the database
70
+ function refuses anyone but a superadmin regardless, so offering it to an
71
+ ordinary editor produces a button that always fails.
72
+
73
+ Leave the api `null` — or mount no provider at all — and every screen reports
74
+ "not enforced" and behaves as before.
75
+
76
+ ## 4. Pass the session id on to the saves
77
+
78
+ The provider is what shows the banner. The session id is what makes the server
79
+ able to tell *this* editor's save from someone else's, and it travels with the
80
+ save, not with the lock.
81
+
82
+ Each screen already puts `lock.sessionId` into the deps it calls. The host's
83
+ job is to forward it to the matching core:
84
+
85
+ | Screen | Host dep | Core | Resource |
86
+ | --- | --- | --- | --- |
87
+ | `PageBuilderView` | `save`, `rename`, `schedule`, `cancelPublication`, `restoreVersion` | `savePageVersionCore`, `renamePageCore`, `schedulePageVersionCore`, `cancelPagePublicationCore`, `restorePageVersionCore` | `page` / page id |
88
+ | `GlobalSectionBuilderView` | `save`, `rename`, `setKind` | `saveGlobalSectionVersionCore`, `renameGlobalSectionCore`, `setGlobalSectionKindCore` | `global_section` / section id |
89
+ | `SectionEditorView`, `NavigationView`, `ContactDetailsView` | `save` | `saveContentSectionCore` | `content_section` / section key |
90
+ | `FormEditorView` | `saveForm`; pass `editSessionId` into its host `VersionHistory` too | `saveFormCore`, `restoreFormVersionCore` | `form` / form id |
91
+ | `FormSettingsView` | `saveDefaults`; forward the whole `data` object, or destructure its `editSessionId` into the core's third argument | `saveFormDefaultsCore` | `form_defaults` / `form_settings` |
92
+ | `PageSeoPanelView` | `onSave(form, editSessionId)`, `onReset(editSessionId)` | `savePageSeoCore`, `deletePageSeoOverrideCore` | `page_seo` / `pageKey` |
93
+
94
+ The cores and schemas accept `editSessionId` as an optional field so an
95
+ unwired/unmigrated host keeps its old behaviour while no lock exists. Once a
96
+ resource has a live lock, every protected write requires the matching session
97
+ id, including writes by another tab of the same user. Forward it on every path
98
+ in the table; omission is not a bypass.
99
+
100
+ `PageSeoPanelView` additionally needs `pageKey`. Without it the SEO panel has
101
+ no resource to lock and stays unlocked, even with everything else wired.
102
+
103
+ ## Storage
104
+
105
+ `editLockActionCore` and `assertEditable` never touch a database themselves.
106
+ Every read and write goes through `EditLockAdapter`
107
+ (`@bygghammar/cms-platform/server/edit-lock-adapter`), five methods over the
108
+ domain operations and nothing else:
109
+
110
+ ```ts
111
+ type EditLockAdapter = {
112
+ assertStaff(): Promise<void>;
113
+ acquire(input: EditLockRef & { sessionId: string; ttlSeconds: number; steal: boolean }): Promise<EditLockState>;
114
+ status(input: EditLockRef & { sessionId: string | null }): Promise<EditLockState>;
115
+ release(input: EditLockRef & { sessionId: string }): Promise<boolean>;
116
+ list(): Promise<EditLockRow[]>;
117
+ };
118
+ ```
119
+
120
+ The context a core takes is `{ editLocks: <adapter> }`. Nothing in the contract
121
+ names a driver, a client library or a wire format, so a self-hosted application
122
+ on ordinary PostgreSQL implements it with the SQL it already writes:
123
+
124
+ ```ts
125
+ import type { EditLockAdapter } from "@bygghammar/cms-platform/server/edit-lock-adapter";
126
+ import { EditLockNotInstalledError } from "@bygghammar/cms-platform/server/edit-lock-adapter";
127
+ import { asEditLockState } from "@bygghammar/cms-platform/cms/edit-lock";
128
+
129
+ const MISSING = new Set(["42883", "42P01"]); // no such function, no such table
130
+
131
+ export function editLockStorage(pool: Pool, userId: string): EditLockAdapter {
132
+ const query = async (text: string, values: unknown[]) => {
133
+ try {
134
+ return await pool.query(text, values);
135
+ } catch (error) {
136
+ if (MISSING.has(error.code)) throw new EditLockNotInstalledError();
137
+ throw error;
138
+ }
139
+ };
140
+ return {
141
+ async acquire(input) {
142
+ const { rows } = await query(
143
+ "SELECT public.cms_acquire_edit_lock($1, $2, $3, $4, $5) AS state",
144
+ [input.resourceType, input.resourceId, input.sessionId, input.ttlSeconds, input.steal],
145
+ );
146
+ return asEditLockState(rows[0]?.state);
147
+ },
148
+ // status, release, list and assertStaff in the same shape
149
+ };
150
+ }
151
+ ```
152
+
153
+ Two rules an adapter has to honour, whatever it is built on:
154
+
155
+ - **`acquire` must be one atomic statement.** Two editors opening the same page
156
+ at the same instant have to contend on a single unique index so exactly one
157
+ wins. Read-then-write leaves a window in which both do.
158
+ - **`sessionId` is a bearer token.** It goes in and is never returned. Knowing
159
+ another tab's session id is enough to save as its holder, so no read may
160
+ include it — not `status`, not `list`.
161
+
162
+ Whether the storage runs on a stored function, plain SQL in the adapter, or a
163
+ service of its own is the host's decision. A PostgREST-shaped host that already
164
+ builds `{ supabase: { rpc }, userId, claims }` for its other cores can keep
165
+ passing exactly that: `createSupabaseEditLockAdapter` is applied for it
166
+ automatically, and the migration's functions are the storage.
167
+
168
+ ## What the server does with it
169
+
170
+ `assertEditable` sits before each protected write. A write from another session
171
+ throws `EditLockedError`. On the server it has `error.code === "edit_locked"` and
172
+ `error.state`. TanStack Start serializes only an Error's message, so the message
173
+ also begins with `edit_locked:` and `isEditLockedError()` recognises either
174
+ form after transport. Do not replace that failure with a success response.
175
+
176
+ This is a cooperative preflight lock, not a transaction-wide database fence.
177
+ Expiry, a new acquisition, a superadmin steal, or an explicit release could
178
+ land between the status preflight and a later PostgREST mutation. Strict
179
+ transactional exclusion would require each mutation and its lock check in one
180
+ database RPC, or a fencing token checked by the write itself.
181
+
182
+ The per-tab session id is a bearer value and is never returned by a lock
183
+ status/acquire response. Authenticated staff have column-level read access to
184
+ the operational lock fields but not `session_id`; the administrative list RPC
185
+ omits that column. This prevents a blocked browser from reading the
186
+ holder's token and replaying it in a save.
187
+
188
+ Modern browsers also hold an exclusive Web Lock for that bearer value before
189
+ the first server acquire. This detects a duplicated tab even when the original
190
+ is frozen. Browsers without Web Locks fall back to a short BroadcastChannel
191
+ handshake. That fallback is best-effort because a frozen source tab can answer
192
+ too late; without either primitive there is no duplicate-tab signal at all.
193
+ Multi-user locking remains enforced in either case.
194
+
195
+ ## Choosing the lifetime
196
+
197
+ A lock lasts 120 seconds by default and is renewed every 40. A browser that
198
+ crashes therefore frees the page about two minutes later, with no cleanup job
199
+ anywhere. Pass `ttlSeconds` to `createEditLockApi` to change it; the database
200
+ clamps to 15–3600 whatever it is told.
201
+
202
+ Leaving an editor through client-side navigation releases immediately. Closing
203
+ or reloading the whole document relies on the TTL: firing a release from the
204
+ old document can arrive after the reload has already reacquired with the same
205
+ session and delete its new lock. A restored/backgrounded page stays fenced
206
+ until its catch-up renewal confirms it still holds the resource.
207
+
208
+ ## Recovering a stuck lock
209
+
210
+ `listEditLocksCore` returns every live lock, and `steal` takes one — superadmin
211
+ only, enforced in the database. Neither is needed for the feature to work; they
212
+ are for the afternoon somebody's laptop dies mid-edit and two minutes is too
213
+ long to wait.