@k8ordo/state 2.3.1 → 4.0.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/docs/GUIDE.md CHANGED
@@ -18,6 +18,7 @@ treats it as simply present.
18
18
  | --------------------------- | ------------------- | ------------------------ | --------------------- | ---------------------------------------------- |
19
19
  | `definePageState` — `url` | searchParams | back/forward, sharing | anyone given the URL | reads, where the router passes the search |
20
20
  | `definePageState` — `entry` | history entry state | back/forward, reload | that tab's entry | — |
21
+ | `definePageState` — `hash` | the URL's fragment | back/forward, sharing | anyone given the URL | — |
21
22
  | `defineLocalState` | localStorage | until deleted | every tab, one device | — |
22
23
  | `defineSessionState` | sessionStorage | reload, until tab closes | that tab | — |
23
24
  | `defineCookieState` | a cookie | 400 days from last write | every tab, one device | reads, where the page receives request cookies |
@@ -25,7 +26,7 @@ treats it as simply present.
25
26
 
26
27
  `url` and `entry` are the two faces of one history entry — one visible and
27
28
  shareable, one hidden — which is why they share a definition and update
28
- atomically. Web Storage, cookies and memory are app-scope, not page-scope,
29
+ atomically. `hash` is the rest of that entry's URL, and travels with them. Web Storage, cookies and memory are app-scope, not page-scope,
29
30
  which is why they are their own kinds: the grouping difference is real, so
30
31
  the API makes it visible. sessionStorage is localStorage's per-tab twin,
31
32
  built the same way: it survives a reload of the tab — unlike memory — and
@@ -130,6 +131,48 @@ Web Storage and the cookie hold, so keep those fields to what JSON
130
131
  represents: a `z.date()` shows its `Date` after the write and falls back to
131
132
  its default on the next load.
132
133
 
134
+ ## The fragment — one value
135
+
136
+ A fragment is one string, so `hash` takes one schema for one value, not an
137
+ object of fields, and that value is the field `hash` of the state:
138
+
139
+ ```tsx
140
+ export const deckState = definePageState('deck', {
141
+ url: z.object({ mode: z._default(z.enum(['view', 'present']), 'view') }),
142
+ hash: z._default(z.coerce.number().check(z.int(), z.gte(1)), 1),
143
+ });
144
+
145
+ const [{ hash, mode }, update] = useAppState(deckState);
146
+ // /slides/intro#3 → hash === 3
147
+ update({ hash: 4 }); // → /slides/intro#4
148
+ deckState.href(href('/slides/:slug', { slug: 'intro' }), { hash: 4 });
149
+ // '/slides/intro#4'
150
+ ```
151
+
152
+ It follows the url slot's rules: the schema must tolerate absence, a boolean
153
+ is `z.stringbool()`, the default is written as no fragment at all, `replace`
154
+ is the default and `{ history: 'push' }` adds an entry, and a run of writes is
155
+ thinned out. The value is percent-encoded on the way out, so any string is one
156
+ value. What differs:
157
+
158
+ - **A fragment the schema rejects is not this state's.** The browser gives a
159
+ fragment a meaning of its own — the element with that id — so `#main`
160
+ under the schema above reads as the default, `1`, and stays in the URL:
161
+ writing the default changes nothing, and a write to `url` or `entry` keeps
162
+ it. A visitor following an in-page link moves the value back to its
163
+ default the same way. Only a value other than the default replaces it.
164
+ - **The name is taken.** A `url` or `entry` field named `hash` beside a
165
+ `hash` slot is refused when the definition is made, and by the types.
166
+ - **The server never sees it.** A fragment is not sent, so the server render
167
+ and the hydration render show the default, in every mode; there is no
168
+ `parseHash`.
169
+ - **Setting a fragment needs no router.** It is a move within the document,
170
+ which the browser makes on its own, without scrolling unless an element
171
+ has that id. Going back to the default drops the fragment, and that is a
172
+ navigation the platform loads a document for unless something intercepts
173
+ it — `@k8ordo/router` does. A router that leaves every `hashChange` to the
174
+ browser reloads the page there in WebKit, which flags that move too.
175
+
133
176
  ## When a stored shape changes
134
177
 
135
178
  A localStorage row or a cookie outlives the code that wrote it. On its own, a
@@ -174,9 +217,14 @@ export const prefs = defineLocalState(
174
217
  - **A newer row is left alone.** A row a newer version wrote — a tab that
175
218
  loaded the next deploy first — is salvaged without `migrate` and never
176
219
  written back, so it stays the newer tab's.
177
- - **A throwing `migrate` loses nothing.** It reads as nothing stored: the
178
- defaults show, and the row stays as it was for a fixed `migrate` to try
179
- again.
220
+ - **A throwing `migrate` loses nothing, and says so.** It reads as nothing
221
+ stored: the defaults show, and the error is reported — handed to
222
+ `reportError` in the browser, so `window`'s `error` event and error
223
+ monitoring see it, and logged with the key by `parseCookies` on the
224
+ server. The row stays as it was for a fixed `migrate` to try again: an
225
+ `update()` writes nothing over it and rejects its handle with the same
226
+ error, while the value it set stays in memory until the next load, and a
227
+ server's `cookie()` throws instead of returning a value to write.
180
228
  - **Adopting a version changes the row's shape.** A tab still running code
181
229
  from before reads `[version, values]` as nothing stored until it reloads.
182
230
  - **`inlineRead()` hands out only the current version.** Neither the schema
@@ -274,25 +322,17 @@ a layout: the pathname axis is the router's, and the search is read in the
274
322
  browser by `useAppState`, so such a server render shows the url slot's
275
323
  defaults and the live URL takes over one render after hydration.
276
324
  Static mode refuses the export: a file is the same whatever the search
277
- holds. Building links is unaffected — `href` and `search` are pure and run
278
- anywhere, including in a Server Component.
325
+ holds. Building links is unaffected — `href` is pure and runs anywhere,
326
+ including in a Server Component.
279
327
 
280
328
  `urlReader(schema)` is that reading on its own — a url schema in,
281
329
  `(input) => values` out, the codec built once — for code handed the schema
282
330
  without its definition; the framework's generated table calls it.
283
331
 
284
- `href` and `search` are pure: unspecified fields mean their default, and
285
- default values are omitted from the query, so every link is canonical and as
286
- short as it can be. `search` returns the query string alone (no `?`) when the
287
- path should stay in the caller's hands.
288
-
289
- The path `href` takes is written from the application's root, the way the
290
- route table is, and the link it returns carries Vite's `base` in front of it:
291
- under `base: '/docs/'`, `listState.href('/products', { page: 2 })` is
292
- `/docs/products?page=2`. Hand it a path, then — not what `@k8ordo/router`'s
293
- `href` returned, which carries the base already. Outside Vite (Next.js, say)
294
- there is no `import.meta.env` to read, nothing is added, and a `basePath` is
295
- the framework's own `<Link>`'s to add.
332
+ `href` is pure: unspecified fields mean their default, and default values are
333
+ omitted from the query, so every link is canonical and as short as it can be.
334
+ What it is handed is the URL the router built, not a path of its own — see
335
+ [Links on the router's URL](#links-on-the-routers-url).
296
336
 
297
337
  ## Cookie state — preferences the server renders
298
338
 
@@ -302,7 +342,10 @@ goes with every request: where the page receives the request's cookies —
302
342
  `request.cookies` in `@k8ordo/framework`'s server mode — `parseCookies` reads
303
343
  the values
304
344
  and `initialCookie` seeds the server render and the hydration render with
305
- them, so the default never flashes.
345
+ them, so the default never flashes. Which preference belongs in a cookie,
346
+ which in local state and which in neither (the language) is set out once,
347
+ in `@k8ordo/framework`'s guide
348
+ (`node_modules/@k8ordo/framework/docs/GUIDE.md`, "Preferences").
306
349
 
307
350
  ```tsx
308
351
  // src/routes/layout.tsx — server mode
@@ -342,10 +385,14 @@ export function Shell({ initialCookie, children }: ShellProps) {
342
385
 
343
386
  - **One cookie per definition.** The values are one cookie named
344
387
  `k8ordo-state.<key>` (`cookieName`), holding the percent-encoded JSON of the
345
- declared fields. `parseCookies(cookies)` takes the request's cookies as a
346
- `ReadonlyMap<string, string>` of percent-decoded values — what
347
- `request.cookies` is — and salvages field by field like every other read:
348
- absent, corrupt or rejected values land on their defaults.
388
+ declared fields. `parseCookies(cookies)` takes anything whose `get(name)`
389
+ returns a cookie's percent-decoded value — `request.cookies` in a page,
390
+ and in server mode `cookies()` in a guard, a route.ts or a Server Action
391
+ too — and salvages field by field like every other read: absent, corrupt
392
+ or rejected values land on their defaults. Next.js's `cookies()` gets a
393
+ `{ name, value }` object, so hand it over as
394
+ `density.parseCookies({ get: (name) => store.get(name)?.value })`, where
395
+ `store` is `await cookies()`.
349
396
  - **Seed every renderer.** Like `initialUrl`, `initialCookie` seeds only the
350
397
  `useAppState` call it is passed to: a component that renders on the server
351
398
  without it shows the defaults there. Read the cookie once, high up — a
@@ -381,11 +428,8 @@ never writes the response; in server mode the framework's
381
428
  `route.ts` and Server Actions. That is where a session cookie belongs, as
382
429
  `HttpOnly`, and this package never sees it. The same `cookies()` can also
383
430
  write a cookie state, for a form that sets a preference without JavaScript,
384
- say: write `cookieName` with the value `cookieValue(values)` returns — the
385
- values pass the schema, unspecified fields mean their default — and the
386
- attributes above (`Path=/`, `SameSite=Lax`, `Max-Age=34560000`), never
387
- `HttpOnly`, or the browser store can no longer see it. Open tabs take the new
388
- values in through the `change` event.
431
+ say: `cookie(patch, current)` returns the name, the value and the options,
432
+ to spread into `set`.
389
433
 
390
434
  ```ts
391
435
  // src/lib/actions.ts
@@ -395,18 +439,41 @@ import { cookies } from '@k8ordo/framework/server';
395
439
  import { density } from '../state';
396
440
 
397
441
  export async function compact() {
398
- cookies().set(
399
- density.cookieName,
400
- density.cookieValue({ density: 'compact' }),
401
- { httpOnly: false, maxAge: 34_560_000 },
402
- );
442
+ cookies().set(...density.cookie({ density: 'compact' }, cookies()));
403
443
  }
404
444
  ```
405
445
 
406
- `cookieValue` returns the JSON unencoded: `cookies().set` percent-encodes the
407
- value on its way out (so does Next.js's), which is the one encoding
408
- `parseCookies` expects undone. Writing a `Set-Cookie` header by hand, pass
409
- the value through `encodeURIComponent` yourself — once.
446
+ - **It writes what `update()` would.** `patch` goes over the values the
447
+ request's cookie holds — `current` is read the way `parseCookies` reads
448
+ it — so a field the patch leaves out keeps what the visitor saved, and the
449
+ result passes the schema. A field the definition does not declare throws,
450
+ as it does in `update()`. To go back to every default, delete the cookie:
451
+ `cookies().delete(density.cookieName)`.
452
+ - **The options are the browser store's attributes.** `Path=/`,
453
+ `SameSite=Lax`, a `Max-Age` of 400 days, and `httpOnly: false`: an
454
+ `HttpOnly` cookie is one the browser store can no longer see. Open tabs
455
+ take the new values in through the `change` event.
456
+ - **The value is the JSON, unencoded.** `cookies().set` percent-encodes it on
457
+ its way out (so does Next.js's), which is the one encoding `parseCookies`
458
+ expects undone. Writing a `Set-Cookie` header by hand, pass the value
459
+ through `encodeURIComponent` yourself — once.
460
+ - **A cookie `migrate` cannot read is never written over.** `cookie()` throws,
461
+ naming the key, with `migrate`'s error as its `cause` — the refusal a
462
+ browser `update()` makes ([When a stored shape changes](#when-a-stored-shape-changes)).
463
+
464
+ Under Next.js, hand `current` over as `parseCookies` takes it:
465
+
466
+ ```ts
467
+ const store = await cookies();
468
+ store.set(
469
+ ...density.cookie(
470
+ { density: 'compact' },
471
+ {
472
+ get: (name) => store.get(name)?.value,
473
+ },
474
+ ),
475
+ );
476
+ ```
410
477
 
411
478
  ## Client — subscribe and update
412
479
 
@@ -467,7 +534,7 @@ const onNext = async () => {
467
534
  ```
468
535
 
469
536
  An async action — `startTransition(async …)`, `useTransition`'s included, or
470
- `@k8ordo/ui`'s `Button` `onAction` — can await it the same way. Under
537
+ `@k8ordo/ui`'s `Button` `action` — can await it the same way. Under
471
538
  `@k8ordo/router` a url update issued while another page is still loading is a
472
539
  page change, and a page change never joins the action, so `finished` settles
473
540
  once that page is on screen rather than waiting for the action to end.
@@ -499,7 +566,7 @@ with that error while the rendered value stays.
499
566
  - **`replace` by default.** An update refines the current entry. Pass
500
567
  `{ history: 'push' }` only for updates the back button should undo — the
501
568
  option exists only on page state, the one kind with a navigation behind it,
502
- and takes effect only when a url value changes: an entry-only write
569
+ and takes effect only when a url or hash value changes: an entry-only write
503
570
  rewrites the current entry in place.
504
571
  - **One handler, one write.** Several `update()` calls on a page, local,
505
572
  session or cookie state made synchronously in one event handler collapse
@@ -510,6 +577,20 @@ with that error while the rendered value stays.
510
577
  cookie state still write their row (creating one if none was stored).
511
578
  Memory has nothing to batch: each call applies on the spot and returns its
512
579
  own settled handle.
580
+ - **A run of url writes is thinned out.** A slider that updates a url field
581
+ on every input would navigate on every input, and WebKit refuses a
582
+ document's navigations past 200 in ten seconds, rejecting the rest with a
583
+ `QuotaExceededError`. So a `replace` that changes a url value within 100 ms
584
+ of the last url write waits for the rest of that time, and the updates made
585
+ meanwhile join it: one navigation carries the latest values, and they all
586
+ share its handle, whose `committed` settles when that navigation is in the
587
+ URL. The value on screen never waits — every `update()` still applies
588
+ synchronously. A `push` is an entry of its own and is never held back; it
589
+ takes what was waiting with it. An update still waiting when the page is
590
+ left — the URL's pathname moves — is not written, since it would land on
591
+ the next page's URL, and its handle rejects with an `AbortError`. Entry,
592
+ local, session, cookie and memory writes are not thinned; a hash write is a
593
+ navigation and is.
513
594
  - **Functional form.** `update((current) => ({ page: current.page + 1 }))`
514
595
  reads the batched state, not the committed one.
515
596
  - **Shared ground stays shared.** A page state rewrites only its own params
@@ -538,7 +619,7 @@ Two operations depend on the router; everything else works under any router:
538
619
 
539
620
  | operation | needs |
540
621
  | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
541
- | `href` / `search` links, GET forms | nothing — the router or the browser handles the click or the submission |
622
+ | `href` links, GET forms | nothing — the router or the browser handles the click or the submission |
542
623
  | updates that change only entry, local, session, cookie or memory values | nothing — no navigation is involved |
543
624
  | url `update()` on the client | a router that intercepts the Navigation API |
544
625
  | `parseUrl` on the server | a router that hands the page its search (`@k8ordo/framework` in server mode: `export const search`) |
@@ -557,6 +638,33 @@ and `finished` waits for it to be on screen. On a router that does not intercept
557
638
  forms for url changes there, which is this package's preferred grain anyway.
558
639
  There is deliberately no history-API fallback.
559
640
 
641
+ **Turning a page keeps the position.** A navigation that keeps the pathname
642
+ moves neither the scroll position nor the focus — a fragment in the URL does
643
+ not scroll either — so a pager below a long list, a button calling `update()`
644
+ or a link to `?page=2` alike, leaves the reader at the bottom of the new
645
+ page. Move the focus to the results once `finished` settles: the scroll
646
+ follows the focus, and keyboard and screen-reader users hear where the new
647
+ page starts. `tabIndex={-1}` lets the heading take focus without entering
648
+ the tab order.
649
+
650
+ ```tsx
651
+ const [{ page }, update] = useAppState(listState, ['page']);
652
+ const results = useRef<HTMLHeadingElement>(null);
653
+
654
+ const turn = async (next: number) => {
655
+ await update({ page: next }, { history: 'push' }).finished;
656
+ results.current?.focus();
657
+ };
658
+
659
+ <h2 ref={results} tabIndex={-1}>
660
+ Results
661
+ </h2>;
662
+ // … the list …
663
+ <button type="button" onClick={() => void turn(page + 1)}>
664
+ Next page
665
+ </button>;
666
+ ```
667
+
560
668
  A page state reads the URL of the page it renders in. Under
561
669
  `@k8ordo/router` the URL commits before the next page arrives, and the page
562
670
  being left stays on screen until it does: that page keeps the values its
@@ -572,74 +680,72 @@ Keystrokes do not belong in the URL. Let the DOM or local React state hold
572
680
  the draft and call `update()` at commit points — submit, blur, pagination —
573
681
  the same division `@k8ordo/form` draws.
574
682
 
575
- ## Typed routes
576
-
577
- `href` keeps the path literal alive in the type
578
- (``'/products' | `/products?${string}` ``), which is what typed-route checks
579
- strip a query from and verify. To constrain paths app-wide, augment `Register`
580
- once, with the same line the `@k8ordo/router` augmentation takes:
581
-
582
- ```ts
583
- // src/k8ordo.d.ts
584
- import type { routes } from './routes';
585
-
586
- declare module '@k8ordo/router' {
587
- interface Register {
588
- routes: typeof routes;
589
- }
590
- }
591
-
592
- declare module '@k8ordo/state' {
593
- interface Register {
594
- routes: typeof routes;
595
- }
596
- }
597
- ```
683
+ ## Links on the router's URL
598
684
 
599
- `href` then checks the path it is handed against the table's linkable
600
- patterns, segment by segment: a literal segment must be spelled as the pattern
601
- spells it, a `:param` takes any one non-empty segment — a `${string}` from a
602
- template literal such as `` `/${locale}/products` `` included — and a `*`
603
- wildcard is matched but never linked. A path no pattern matches is a type
604
- error, a `/:locale` table included: `'/ja/nowhere'` is refused even though
605
- `/:locale` takes any first segment. The error lists what would be accepted —
606
- the table's linkable patterns. With a table of `/`, `/members` and
607
- `/posts/:id`, `listState.href('/membrs')` reports:
608
-
609
- ```
610
- Argument of type '"/membrs"' is not assignable to parameter of type '"/" | "/members" | "/posts/:id"'.
611
- ```
612
-
613
- The check is exported as `RegisteredPath<Path>`: `Path` when accepted, and
614
- that union of patterns when refused. Each pattern's own spelling is a path
615
- the table accepts, so the union lets nothing through that the check refuses.
616
- It goes through `NavigablePath`
617
- from `@k8ordo/router` as a type only, so the router stays an optional peer and
618
- never loads at runtime. Under `@k8ordo/framework` this is generated for you into `.k8ordo/register.gen.ts` from
619
- `routes/` when the application's own `package.json` lists `@k8ordo/state` in
620
- `dependencies` or `devDependencies` — a transitive dependency does not count.
621
- Do not hand-write it in such an application: it would duplicate the generated
622
- declaration.
623
-
624
- A router that is not `@k8ordo/router` has no table to hand over; register its
625
- path union directly under `path` — `Route` from `next`, for instance:
685
+ `href(url, values?)` puts this state on a URL the router built:
686
+ `@k8ordo/router`'s `href()` (re-exported by `@k8ordo/framework`), a Next.js
687
+ `Route`, or `''` for the page itself.
626
688
 
627
689
  ```ts
628
- // e.g. types/k8ordo-state.d.ts
629
- import type { Route } from 'next';
630
-
631
- declare module '@k8ordo/state' {
632
- interface Register {
633
- path: Route;
634
- }
635
- }
690
+ import { href } from '@k8ordo/router';
691
+
692
+ listState.href(href('/products'), { q: 'lamp', page: 2 });
693
+ // '/products?q=lamp&page=2'
694
+ productState.href(href('/products/:id', { id }), { hash: 'reviews' });
695
+ // '/products/42#reviews'
696
+ listState.href('', { page: 2 });
697
+ // '?page=2' — the page itself
636
698
  ```
637
699
 
638
- When both are present, `routes` wins. Every `href` in the app now rejects a
639
- path its router does not know, and the error lists the registered union.
640
- Without the augmentation the constraint is any `/`-prefixed string, and a path
641
- without the leading `/` is reported against `` `/${string}` ``. Augment only in an application — a shared library
642
- augmenting `Register` leaks the constraint to every consumer.
700
+ - **Only its own params move.** The params of the URL handed in that this
701
+ definition does not declare stay, in their spelling, and this definition's
702
+ params follow them in their canonical form — the rule a url `update()`
703
+ follows (_Shared ground stays shared_).
704
+ - **The fragment is the hash slot's.** With a `hash` slot the fragment is the
705
+ value's — none at the default — whatever the URL had; without one, the
706
+ URL's own fragment stays.
707
+ - **Nothing is added to the path.** The pathname and a base are the router's:
708
+ `@k8ordo/router`'s `href()` has put Vite's `base` in front already, so the
709
+ result is the URL the browser needs. A router that adds no base leaves
710
+ spelling one to the application, as it does for every other link.
711
+ - **The pattern is checked where the URL is built.** The router's `href()`
712
+ checks the pattern and its params against the route table — a rest param,
713
+ `href('/files/:path+', { path })`, included — before the URL reaches this
714
+ package, which has nothing to register. `href` is typed as the URL it was
715
+ given, or that URL followed by `?…` or `#…`, so a literal survives in the
716
+ type: under Next.js, `listState.href('/products', values)` is still
717
+ checked by typed routes where `<Link href>` takes it. When the URL handed
718
+ in already carries this definition's params or a fragment, that type is an
719
+ approximation: those params are rewritten, and the query goes in before
720
+ the fragment.
721
+ - **The page itself is `''`.** `listState.href('', values)` is a link
722
+ relative to the page, `?page=2`, which replaces the page's whole search the
723
+ way the browser resolves it — for display, or for a link that keeps
724
+ nothing else of the search.
725
+
726
+ ## One way per URL
727
+
728
+ Each thing an application does with a URL has one spelling, the same under
729
+ `@k8ordo/router`, `@k8ordo/state` and `@k8ordo/framework`:
730
+
731
+ | to | write |
732
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------- |
733
+ | link to a page | `href(pattern, params)` |
734
+ | link to a page with its state | `def.href(href(pattern, params), values)` |
735
+ | link to the page itself with other state | `def.href('', values)` |
736
+ | ask which page is showing | `matchPath(pattern, pathname)` in a Server Component, `useMatch(pattern)` in a client |
737
+ | change the page from code | `navigation.navigate(href(pattern, params))`, the link's own URL |
738
+ | change the state | `update(values)` |
739
+ | move a page for good | `redirect.ts`, its `to` a table pattern (`@k8ordo/framework`) |
740
+ | redirect from a Server Action, a `guard.ts` or a `route.ts` | `redirect(href(pattern, params))` (`@k8ordo/framework/server`) |
741
+ | show the page on screen in another locale | `withBase(locales.localize(pathname, locale))` |
742
+
743
+ The last row is the one URL built from a pathname rather than a pattern: the
744
+ page showing may be any page. Nothing else compares or combines `pathname` and
745
+ `href()` — `pathname` is in the table's terms and `href()` carries Vite's
746
+ `base`. In a `[locale]` application, import `href` only from the module that
747
+ binds the locale (`export const href = bindParams(…)`): the router's own
748
+ `href` has the same name and type-checks too.
643
749
 
644
750
  ## Reading before hydration
645
751
 
@@ -669,6 +775,14 @@ the hydrated store be the source of truth from then on. The script changes
669
775
  `<html>` before React hydrates it, so render that element with
670
776
  `suppressHydrationWarning`.
671
777
 
778
+ Under `@k8ordo/framework`, render the script from a small `'use client'`
779
+ component that takes the page's nonce, rather than straight in the root
780
+ layout, whose `<script>` text would ride every page's payload; its
781
+ reference on Content Security Policy
782
+ (`node_modules/@k8ordo/framework/docs/references/csp.md`, "A script of the
783
+ application's that runs before the first paint") shows it under both
784
+ modes.
785
+
672
786
  ## What it guarantees
673
787
 
674
788
  **Boundary data is input, not trusted state.** A URL param a user edited, a
@@ -682,7 +796,9 @@ on a scalar field takes the first value.
682
796
 
683
797
  **Canonical URLs.** Serialization omits every field sitting at its default, so
684
798
  the same state always produces the same, shortest URL — links, bookmarks and
685
- caches agree.
799
+ caches agree. That holds for the URLs `href` and `update()` write, and only
800
+ for those: a GET form submits every named field (below), and the page does
801
+ not rewrite the URL it arrives at.
686
802
 
687
803
  **Back means back.** Both faces of a page state live on the history entry via
688
804
  the platform, not in a parallel store, so back/forward restore them together
@@ -714,7 +830,9 @@ takes over on hydration.
714
830
  `parseCookies(request.cookies)` returned as `initialCookie` — in
715
831
  `@k8ordo/framework`'s server mode, say — and neither render shows the
716
832
  defaults. Without a request (static mode), the cookie takes over on
717
- hydration.
833
+ hydration. Either option may be `undefined`, which is the same as leaving
834
+ it out, so a component shared by a page that has the value and one that
835
+ does not passes its prop straight through.
718
836
 
719
837
  Everything else — entry, local, session, memory — renders its defaults on the
720
838
  server by construction: those places do not exist there.
@@ -727,7 +845,10 @@ are the same schema:
727
845
  ```tsx
728
846
  import { formFields } from '@k8ordo/form/server';
729
847
 
730
- const filterFields = formFields(listState.url); // one schema, both jobs
848
+ export default function ListPage() {
849
+ // one schema, both jobs
850
+ return <FilterForm fields={formFields(listState.url)} />;
851
+ }
731
852
  ```
732
853
 
733
854
  A `z.stringbool()` field derives a checkbox whose `value` is the same spelling
@@ -741,14 +862,48 @@ and with JavaScript the submission loads it again in place. Anywhere else
741
862
  (static mode, a page that does not declare `search`) the server render
742
863
  shows the defaults, and the submitted values appear once the page hydrates.
743
864
 
865
+ The URL a GET form writes is not the canonical one. The browser submits every
866
+ named field, so an empty search box arrives as `q=` and a field left at its
867
+ default as `min=0`: the values read back are the same, but the URL is longer
868
+ than what `href` builds for that state, and nothing rewrites it — a
869
+ rewrite would cost a navigation on every submission. Show or share the
870
+ canonical form with `listState.href('', values)`.
871
+
744
872
  ## Testing
745
873
 
874
+ Both helpers come from `@k8ordo/state/testing`, an entry of its own, so
875
+ nothing of them reaches an application's bundle.
876
+
877
+ ```ts
878
+ import { resetStateRegistry } from '@k8ordo/state/testing';
879
+
880
+ afterEach(() => {
881
+ resetStateRegistry();
882
+ });
883
+ ```
884
+
746
885
  `resetStateRegistry()` clears the provider-less store registry between tests.
747
886
  Unmount components first — mounted hooks keep their store through closures.
748
887
  Clear stored rows by the definition's `storageKey` (in its own storage area)
749
888
  or `cookieName` (`await cookieStore.delete(def.cookieName)`); the Cookie
750
889
  Store API's `change` event fires in the same tab too, so a test that writes
751
890
  the cookie itself stands in for another tab.
752
- When testing url updates, intercept the `navigate` event in the test itself
753
- (as a router would); an unintercepted `navigation.navigate()` is a
754
- cross-document load.
891
+ A test of url or hash updates needs a router: an unintercepted
892
+ `navigation.navigate()` is a cross-document load that takes the test runner
893
+ with it. `mountPageUrl()` from `@k8ordo/state/testing` stands in for one and
894
+ gives the page the URL the test starts from:
895
+
896
+ ```ts
897
+ import { mountPageUrl } from '@k8ordo/state/testing';
898
+
899
+ // Vitest runs what beforeEach returns after the test; so does Storybook
900
+ beforeEach(() => mountPageUrl({ search: 'q=css', hash: '3' }));
901
+ ```
902
+
903
+ It intercepts as `@k8ordo/router` does — a move to a fragment within the
904
+ document is left to the browser, and neither the viewport nor the focus is
905
+ moved — and adds `search` to the params the page already has, in the spelling
906
+ given (a test runner and Storybook keep params of their own there). The
907
+ function it returns is the cleanup: it calls `resetStateRegistry()`, which
908
+ also drops a thinned write still waiting, then puts back the URL and the
909
+ entry state it found.
package/docs/llms.txt CHANGED
@@ -29,13 +29,17 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
29
29
  server, cookie state the server renders (and how it relates to cookies the
30
30
  server writes), updating on the client,
31
31
  batching and update handles, subscription granularity, router
32
- requirements, typed routes via `Register`, reading local state before
33
- hydration, and pairing with `@k8ordo/form` for GET forms.
32
+ requirements and turning a page, links on the URL the router built, the
33
+ one way to write each URL (a table shared with `@k8ordo/router` and
34
+ `@k8ordo/framework`), reading local state before hydration, and pairing
35
+ with `@k8ordo/form` for GET forms (whose URL is not the canonical one).
34
36
 
35
37
  ## Entry point
36
38
 
37
- - `@k8ordo/state` — `definePageState(key, { url?, entry? })` returns a pure
38
- definition usable from server and client: `parseUrl(searchParams)` reads
39
+ - `@k8ordo/state` — `definePageState(key, { url?, entry?, hash? })` returns a pure
40
+ definition usable from server and client (`hash` is one schema for one
41
+ value, the URL's fragment, read as the field `hash`; a fragment it rejects
42
+ is an anchor and is left alone): `parseUrl(searchParams)` reads
39
43
  the url slot typed with defaults applied and invalid values salvaged
40
44
  (wherever the router hands a page its search — in `@k8ordo/framework`'s
41
45
  server mode a page that exports `search = listState.url` receives the slot parsed as
@@ -43,10 +47,20 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
43
47
  page never sees the search, and the url slot is read in the browser);
44
48
  `urlReader(schema)` is that reading for a url schema alone, the codec
45
49
  built once (what the framework's generated table calls);
46
- `href(path, values?)` builds a canonical link keeping the path literal in
47
- the type — the path written from the app's root, the link carrying Vite's
48
- `base` (`import.meta.env.BASE_URL`) in front; `search(values?)` returns the
49
- query string alone.
50
+ `href(url, values?)` puts the state on the URL the router built —
51
+ `@k8ordo/router`'s `href()` (`listState.href(href('/products'), { page: 2 })`),
52
+ a Next.js `Route`, or `''` for the page itself (`?page=2`) — rewriting only
53
+ this definition's url params in canonical form (defaults omitted) and
54
+ keeping the URL's other params; with a hash slot it sets the fragment from
55
+ `values.hash` (none at the default), without one it keeps the URL's own;
56
+ it adds no base (the router's `href()` has) and keeps the URL literal in
57
+ the type, so the pattern is checked by the router — a rest param too,
58
+ `href('/files/:path+', { path })` — and a typed route by `<Link>`. There
59
+ is no `search()` and no `Register` here. Only `href` and `update()` write
60
+ the canonical URL; a GET form submits every named field (`q=`, `min=0`).
61
+ A same-pathname navigation keeps the scroll and the focus (a fragment
62
+ too), so a pager moves focus to the results heading (`tabIndex={-1}`)
63
+ after `update(…).finished`.
50
64
  `defineLocalState(key, schema, versioning?)`,
51
65
  `defineSessionState(key, schema)`,
52
66
  `defineCookieState(key, schema, versioning?)` and
@@ -57,7 +71,9 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
57
71
  the schema's field-by-field salvage and is written back in the current
58
72
  version by the browser store (`parseCookies` migrates but never writes), a
59
73
  newer row is salvaged and left alone, and a throwing `migrate` reads as
60
- nothing stored without touching the row; where the browser blocks site
74
+ nothing stored, is reported (`reportError` in the browser, `console.error`
75
+ with the key from `parseCookies`) and leaves the row alone — an `update()`
76
+ writes nothing over it and rejects its handle with the error; where the browser blocks site
61
77
  data, local and session state render their defaults and keep updates in
62
78
  memory until the next load; a local or session definition also exposes
63
79
  `storageKey` (the key in its storage area, `k8ordo-state:<key>`) and
@@ -66,12 +82,21 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
66
82
  (also `null` for a row of another version, when versioned) —
67
83
  unvalidated, so read only what you need with a fallback. A
68
84
  cookie definition exposes `cookieName` (`k8ordo-state.<key>`),
69
- `parseCookies(cookies)` — reads the values out of a request's
70
- percent-decoded cookies (`request.cookies` in `@k8ordo/framework`'s server mode), salvaged
71
- like any read — and `cookieValue(values?)`, the unencoded JSON a server
72
- hands its cookie API (`cookies().set`, which percent-encodes it) when it
73
- sets the same cookie (`Path=/`, `SameSite=Lax`, `Max-Age=34560000`, never
74
- `HttpOnly`). `useAppState(definition, keys?, { initialUrl? } |
85
+ `parseCookies(cookies)` — reads the values out of anything whose
86
+ `get(name)` returns a request's cookie percent-decoded (`request.cookies`
87
+ in a page and `cookies()` in a guard, a route.ts or a Server Action under
88
+ `@k8ordo/framework`'s server mode, `{ get: (name) => store.get(name)?.value }`
89
+ over Next.js's `cookies()`), salvaged like any read — and
90
+ `cookie(patch, current)`, which writes the same cookie from a server as
91
+ `readonly [name, value, options]` to spread into its cookie API
92
+ (`cookies().set(...density.cookie({ density: 'compact' }, cookies()))`):
93
+ `patch` goes over the values `current` holds, read as `parseCookies` reads
94
+ them, as `update()` lays it over the cookie in the browser, the result
95
+ passes the schema, the value is the unencoded JSON (`cookies().set`
96
+ percent-encodes it), the options are `{ path: '/', sameSite: 'lax',
97
+ maxAge: 34560000, httpOnly: false }`, and a cookie whose `migrate` throws
98
+ makes it throw rather than be written over.
99
+ `useAppState(definition, keys?, { initialUrl? } |
75
100
  { initialCookie? })` (client) works on any kind and returns
76
101
  `[state, update]` — state is the flat merge of a page definition's slots;
77
102
  `initialUrl` / `initialCookie` seed the server and hydration renders with
@@ -87,9 +112,6 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
87
112
  it — rejects them with its error;
88
113
  `{ history: 'push' }` exists only on page state and takes effect only when
89
114
  a url value changes).
90
- `resetStateRegistry()` clears stores between tests. Augment
91
- `interface Register { routes: typeof routes }` — the same line as for
92
- `@k8ordo/router` — to check each `href` path against the route table's
93
- linkable patterns segment by segment (`NavigablePath`, so a `/:locale`
94
- table no longer takes every path); a router without a table registers its own path union as
95
- `interface Register { path }` instead.
115
+ `@k8ordo/state/testing` is the entry for tests, kept out of the main one:
116
+ `resetStateRegistry()` clears stores between tests, and `mountPageUrl()`
117
+ stands in for a router there.