@k8ordo/state 3.0.0 → 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
@@ -145,7 +145,8 @@ export const deckState = definePageState('deck', {
145
145
  const [{ hash, mode }, update] = useAppState(deckState);
146
146
  // /slides/intro#3 → hash === 3
147
147
  update({ hash: 4 }); // → /slides/intro#4
148
- deckState.href('/slides/intro', { hash: 4 }); // '/slides/intro#4'
148
+ deckState.href(href('/slides/:slug', { slug: 'intro' }), { hash: 4 });
149
+ // '/slides/intro#4'
149
150
  ```
150
151
 
151
152
  It follows the url slot's rules: the schema must tolerate absence, a boolean
@@ -216,9 +217,14 @@ export const prefs = defineLocalState(
216
217
  - **A newer row is left alone.** A row a newer version wrote — a tab that
217
218
  loaded the next deploy first — is salvaged without `migrate` and never
218
219
  written back, so it stays the newer tab's.
219
- - **A throwing `migrate` loses nothing.** It reads as nothing stored: the
220
- defaults show, and the row stays as it was for a fixed `migrate` to try
221
- 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.
222
228
  - **Adopting a version changes the row's shape.** A tab still running code
223
229
  from before reads `[version, values]` as nothing stored until it reloads.
224
230
  - **`inlineRead()` hands out only the current version.** Neither the schema
@@ -316,25 +322,17 @@ a layout: the pathname axis is the router's, and the search is read in the
316
322
  browser by `useAppState`, so such a server render shows the url slot's
317
323
  defaults and the live URL takes over one render after hydration.
318
324
  Static mode refuses the export: a file is the same whatever the search
319
- holds. Building links is unaffected — `href` and `search` are pure and run
320
- anywhere, including in a Server Component.
325
+ holds. Building links is unaffected — `href` is pure and runs anywhere,
326
+ including in a Server Component.
321
327
 
322
328
  `urlReader(schema)` is that reading on its own — a url schema in,
323
329
  `(input) => values` out, the codec built once — for code handed the schema
324
330
  without its definition; the framework's generated table calls it.
325
331
 
326
- `href` and `search` are pure: unspecified fields mean their default, and
327
- default values are omitted from the query, so every link is canonical and as
328
- short as it can be. `search` returns the query string alone (no `?`) when the
329
- path should stay in the caller's hands.
330
-
331
- The path `href` takes is written from the application's root, the way the
332
- route table is, and the link it returns carries Vite's `base` in front of it:
333
- under `base: '/docs/'`, `listState.href('/products', { page: 2 })` is
334
- `/docs/products?page=2`. Hand it a path, then — not what `@k8ordo/router`'s
335
- `href` returned, which carries the base already. Outside Vite (Next.js, say)
336
- there is no `import.meta.env` to read, nothing is added, and a `basePath` is
337
- 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).
338
336
 
339
337
  ## Cookie state — preferences the server renders
340
338
 
@@ -344,7 +342,10 @@ goes with every request: where the page receives the request's cookies —
344
342
  `request.cookies` in `@k8ordo/framework`'s server mode — `parseCookies` reads
345
343
  the values
346
344
  and `initialCookie` seeds the server render and the hydration render with
347
- 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").
348
349
 
349
350
  ```tsx
350
351
  // src/routes/layout.tsx — server mode
@@ -384,10 +385,14 @@ export function Shell({ initialCookie, children }: ShellProps) {
384
385
 
385
386
  - **One cookie per definition.** The values are one cookie named
386
387
  `k8ordo-state.<key>` (`cookieName`), holding the percent-encoded JSON of the
387
- declared fields. `parseCookies(cookies)` takes the request's cookies as a
388
- `ReadonlyMap<string, string>` of percent-decoded values — what
389
- `request.cookies` is — and salvages field by field like every other read:
390
- 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()`.
391
396
  - **Seed every renderer.** Like `initialUrl`, `initialCookie` seeds only the
392
397
  `useAppState` call it is passed to: a component that renders on the server
393
398
  without it shows the defaults there. Read the cookie once, high up — a
@@ -423,11 +428,8 @@ never writes the response; in server mode the framework's
423
428
  `route.ts` and Server Actions. That is where a session cookie belongs, as
424
429
  `HttpOnly`, and this package never sees it. The same `cookies()` can also
425
430
  write a cookie state, for a form that sets a preference without JavaScript,
426
- say: write `cookieName` with the value `cookieValue(values)` returns — the
427
- values pass the schema, unspecified fields mean their default — and the
428
- attributes above (`Path=/`, `SameSite=Lax`, `Max-Age=34560000`), never
429
- `HttpOnly`, or the browser store can no longer see it. Open tabs take the new
430
- values in through the `change` event.
431
+ say: `cookie(patch, current)` returns the name, the value and the options,
432
+ to spread into `set`.
431
433
 
432
434
  ```ts
433
435
  // src/lib/actions.ts
@@ -437,18 +439,41 @@ import { cookies } from '@k8ordo/framework/server';
437
439
  import { density } from '../state';
438
440
 
439
441
  export async function compact() {
440
- cookies().set(
441
- density.cookieName,
442
- density.cookieValue({ density: 'compact' }),
443
- { httpOnly: false, maxAge: 34_560_000 },
444
- );
442
+ cookies().set(...density.cookie({ density: 'compact' }, cookies()));
445
443
  }
446
444
  ```
447
445
 
448
- `cookieValue` returns the JSON unencoded: `cookies().set` percent-encodes the
449
- value on its way out (so does Next.js's), which is the one encoding
450
- `parseCookies` expects undone. Writing a `Set-Cookie` header by hand, pass
451
- 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
+ ```
452
477
 
453
478
  ## Client — subscribe and update
454
479
 
@@ -509,7 +534,7 @@ const onNext = async () => {
509
534
  ```
510
535
 
511
536
  An async action — `startTransition(async …)`, `useTransition`'s included, or
512
- `@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
513
538
  `@k8ordo/router` a url update issued while another page is still loading is a
514
539
  page change, and a page change never joins the action, so `finished` settles
515
540
  once that page is on screen rather than waiting for the action to end.
@@ -594,7 +619,7 @@ Two operations depend on the router; everything else works under any router:
594
619
 
595
620
  | operation | needs |
596
621
  | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
597
- | `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 |
598
623
  | updates that change only entry, local, session, cookie or memory values | nothing — no navigation is involved |
599
624
  | url `update()` on the client | a router that intercepts the Navigation API |
600
625
  | `parseUrl` on the server | a router that hands the page its search (`@k8ordo/framework` in server mode: `export const search`) |
@@ -613,6 +638,33 @@ and `finished` waits for it to be on screen. On a router that does not intercept
613
638
  forms for url changes there, which is this package's preferred grain anyway.
614
639
  There is deliberately no history-API fallback.
615
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
+
616
668
  A page state reads the URL of the page it renders in. Under
617
669
  `@k8ordo/router` the URL commits before the next page arrives, and the page
618
670
  being left stays on screen until it does: that page keeps the values its
@@ -628,74 +680,72 @@ Keystrokes do not belong in the URL. Let the DOM or local React state hold
628
680
  the draft and call `update()` at commit points — submit, blur, pagination —
629
681
  the same division `@k8ordo/form` draws.
630
682
 
631
- ## Typed routes
683
+ ## Links on the router's URL
632
684
 
633
- `href` keeps the path literal alive in the type
634
- (``'/products' | `/products?${string}` ``), which is what typed-route checks
635
- strip a query from and verify. To constrain paths app-wide, augment `Register`
636
- once, with the same line the `@k8ordo/router` augmentation takes:
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.
637
688
 
638
689
  ```ts
639
- // src/k8ordo.d.ts
640
- import type { routes } from './routes';
641
-
642
- declare module '@k8ordo/router' {
643
- interface Register {
644
- routes: typeof routes;
645
- }
646
- }
647
-
648
- declare module '@k8ordo/state' {
649
- interface Register {
650
- routes: typeof routes;
651
- }
652
- }
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
653
698
  ```
654
699
 
655
- `href` then checks the path it is handed against the table's linkable
656
- patterns, segment by segment: a literal segment must be spelled as the pattern
657
- spells it, a `:param` takes any one non-empty segment — a `${string}` from a
658
- template literal such as `` `/${locale}/products` `` included — and a `*`
659
- wildcard is matched but never linked. A path no pattern matches is a type
660
- error, a `/:locale` table included: `'/ja/nowhere'` is refused even though
661
- `/:locale` takes any first segment. The error lists what would be accepted —
662
- the table's linkable patterns. With a table of `/`, `/members` and
663
- `/posts/:id`, `listState.href('/membrs')` reports:
664
-
665
- ```
666
- Argument of type '"/membrs"' is not assignable to parameter of type '"/" | "/members" | "/posts/:id"'.
667
- ```
668
-
669
- The check is exported as `RegisteredPath<Path>`: `Path` when accepted, and
670
- that union of patterns when refused. Each pattern's own spelling is a path
671
- the table accepts, so the union lets nothing through that the check refuses.
672
- It goes through `NavigablePath`
673
- from `@k8ordo/router` as a type only, so the router stays an optional peer and
674
- never loads at runtime. Under `@k8ordo/framework` this is generated for you into `.k8ordo/register.gen.ts` from
675
- `routes/` when the application's own `package.json` lists `@k8ordo/state` in
676
- `dependencies` or `devDependencies` — a transitive dependency does not count.
677
- Do not hand-write it in such an application: it would duplicate the generated
678
- declaration.
679
-
680
- A router that is not `@k8ordo/router` has no table to hand over; register its
681
- path union directly under `path` — `Route` from `next`, for instance:
682
-
683
- ```ts
684
- // e.g. types/k8ordo-state.d.ts
685
- import type { Route } from 'next';
686
-
687
- declare module '@k8ordo/state' {
688
- interface Register {
689
- path: Route;
690
- }
691
- }
692
- ```
693
-
694
- When both are present, `routes` wins. Every `href` in the app now rejects a
695
- path its router does not know, and the error lists the registered union.
696
- Without the augmentation the constraint is any `/`-prefixed string, and a path
697
- without the leading `/` is reported against `` `/${string}` ``. Augment only in an application — a shared library
698
- 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.
699
749
 
700
750
  ## Reading before hydration
701
751
 
@@ -725,6 +775,14 @@ the hydrated store be the source of truth from then on. The script changes
725
775
  `<html>` before React hydrates it, so render that element with
726
776
  `suppressHydrationWarning`.
727
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
+
728
786
  ## What it guarantees
729
787
 
730
788
  **Boundary data is input, not trusted state.** A URL param a user edited, a
@@ -738,7 +796,9 @@ on a scalar field takes the first value.
738
796
 
739
797
  **Canonical URLs.** Serialization omits every field sitting at its default, so
740
798
  the same state always produces the same, shortest URL — links, bookmarks and
741
- 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.
742
802
 
743
803
  **Back means back.** Both faces of a page state live on the history entry via
744
804
  the platform, not in a parallel store, so back/forward restore them together
@@ -770,7 +830,9 @@ takes over on hydration.
770
830
  `parseCookies(request.cookies)` returned as `initialCookie` — in
771
831
  `@k8ordo/framework`'s server mode, say — and neither render shows the
772
832
  defaults. Without a request (static mode), the cookie takes over on
773
- 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.
774
836
 
775
837
  Everything else — entry, local, session, memory — renders its defaults on the
776
838
  server by construction: those places do not exist there.
@@ -783,7 +845,10 @@ are the same schema:
783
845
  ```tsx
784
846
  import { formFields } from '@k8ordo/form/server';
785
847
 
786
- 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
+ }
787
852
  ```
788
853
 
789
854
  A `z.stringbool()` field derives a checkbox whose `value` is the same spelling
@@ -797,8 +862,26 @@ and with JavaScript the submission loads it again in place. Anywhere else
797
862
  (static mode, a page that does not declare `search`) the server render
798
863
  shows the defaults, and the submitted values appear once the page hydrates.
799
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
+
800
872
  ## Testing
801
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
+
802
885
  `resetStateRegistry()` clears the provider-less store registry between tests.
803
886
  Unmount components first — mounted hooks keep their store through closures.
804
887
  Clear stored rows by the definition's `storageKey` (in its own storage area)
@@ -823,5 +906,4 @@ moved — and adds `search` to the params the page already has, in the spelling
823
906
  given (a test runner and Storybook keep params of their own there). The
824
907
  function it returns is the cleanup: it calls `resetStateRegistry()`, which
825
908
  also drops a thinned write still waiting, then puts back the URL and the
826
- entry state it found. It is not part of the main entry, so nothing of it
827
- reaches an application's bundle.
909
+ entry state it found.
package/docs/llms.txt CHANGED
@@ -29,8 +29,10 @@ 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
 
@@ -45,10 +47,20 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
45
47
  page never sees the search, and the url slot is read in the browser);
46
48
  `urlReader(schema)` is that reading for a url schema alone, the codec
47
49
  built once (what the framework's generated table calls);
48
- `href(path, values?)` builds a canonical link keeping the path literal in
49
- the type — the path written from the app's root, the link carrying Vite's
50
- `base` (`import.meta.env.BASE_URL`) in front; `search(values?)` returns the
51
- 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`.
52
64
  `defineLocalState(key, schema, versioning?)`,
53
65
  `defineSessionState(key, schema)`,
54
66
  `defineCookieState(key, schema, versioning?)` and
@@ -59,7 +71,9 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
59
71
  the schema's field-by-field salvage and is written back in the current
60
72
  version by the browser store (`parseCookies` migrates but never writes), a
61
73
  newer row is salvaged and left alone, and a throwing `migrate` reads as
62
- 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
63
77
  data, local and session state render their defaults and keep updates in
64
78
  memory until the next load; a local or session definition also exposes
65
79
  `storageKey` (the key in its storage area, `k8ordo-state:<key>`) and
@@ -68,12 +82,21 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
68
82
  (also `null` for a row of another version, when versioned) —
69
83
  unvalidated, so read only what you need with a fallback. A
70
84
  cookie definition exposes `cookieName` (`k8ordo-state.<key>`),
71
- `parseCookies(cookies)` — reads the values out of a request's
72
- percent-decoded cookies (`request.cookies` in `@k8ordo/framework`'s server mode), salvaged
73
- like any read — and `cookieValue(values?)`, the unencoded JSON a server
74
- hands its cookie API (`cookies().set`, which percent-encodes it) when it
75
- sets the same cookie (`Path=/`, `SameSite=Lax`, `Max-Age=34560000`, never
76
- `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? } |
77
100
  { initialCookie? })` (client) works on any kind and returns
78
101
  `[state, update]` — state is the flat merge of a page definition's slots;
79
102
  `initialUrl` / `initialCookie` seed the server and hydration renders with
@@ -89,10 +112,6 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
89
112
  it — rejects them with its error;
90
113
  `{ history: 'push' }` exists only on page state and takes effect only when
91
114
  a url value changes).
115
+ `@k8ordo/state/testing` is the entry for tests, kept out of the main one:
92
116
  `resetStateRegistry()` clears stores between tests, and `mountPageUrl()`
93
- from `@k8ordo/state/testing` stands in for a router there. Augment
94
- `interface Register { routes: typeof routes }` — the same line as for
95
- `@k8ordo/router` — to check each `href` path against the route table's
96
- linkable patterns segment by segment (`NavigablePath`, so a `/:locale`
97
- table no longer takes every path); a router without a table registers its own path union as
98
- `interface Register { path }` instead.
117
+ stands in for a router there.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/state",
3
- "version": "3.0.0",
3
+ "version": "4.0.0",
4
4
  "description": "Declare state by where it lives — URL search params, history-entry state, localStorage, sessionStorage, a cookie, or memory. One zod schema per boundary place and a typed box for memory, over the Navigation API.",
5
5
  "keywords": [
6
6
  "cookie",
@@ -47,25 +47,25 @@
47
47
  },
48
48
  "devDependencies": {
49
49
  "@arethetypeswrong/cli": "0.18.5",
50
- "@k8ordo/router": "^3.0.0",
50
+ "@k8ordo/router": "^4.0.0",
51
51
  "@types/react": "19.3.0",
52
52
  "@types/react-dom": "19.3.0",
53
53
  "@vitejs/plugin-basic-ssl": "2.3.0",
54
- "@vitejs/plugin-react": "6.2.1",
55
- "@vitest/browser-playwright": "5.1.0",
56
- "playwright": "1.65.0",
54
+ "@vitejs/plugin-react": "6.3.0",
55
+ "@vitest/browser-playwright": "5.1.1",
56
+ "playwright": "1.65.1",
57
57
  "publint": "0.3.25",
58
58
  "react": "19.3.1",
59
59
  "react-dom": "19.3.1",
60
60
  "typescript": "7.0.2",
61
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
62
- "vite-plus": "1.4.0",
63
- "vitest": "5.1.0",
61
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
62
+ "vite-plus": "1.7.0",
63
+ "vitest": "5.1.1",
64
64
  "vitest-browser-react": "2.3.0",
65
65
  "zod": "4.6.7"
66
66
  },
67
67
  "peerDependencies": {
68
- "@k8ordo/router": "^3.0.0",
68
+ "@k8ordo/router": "^4.0.0",
69
69
  "@types/react": ">=19.3.0",
70
70
  "react": ">=19.3.0",
71
71
  "typescript": ">=7.0.0",
package/dist/base.d.mts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * A path as the URL spells it: Vite's `base` in front, so `/products` is
3
- * `/docs/products` under `base: '/docs/'` and `/` is `/docs/`. The same rule
4
- * as `@k8ordo/router`'s `withBase` — not borrowed, because the router is an
5
- * optional peer this package only reads types from.
6
- */
7
- export declare const withBase: (path: string) => string;
package/dist/base.mjs DELETED
@@ -1,14 +0,0 @@
1
- // src/base.ts
2
- /**
3
- * A path as the URL spells it: Vite's `base` in front, so `/products` is
4
- * `/docs/products` under `base: '/docs/'` and `/` is `/docs/`. The same rule
5
- * as `@k8ordo/router`'s `withBase` — not borrowed, because the router is an
6
- * optional peer this package only reads types from.
7
- */
8
- const withBase = (path) => {
9
- const base = import.meta.env === void 0 ? "/" : import.meta.env.BASE_URL;
10
- if (!base.startsWith("/") || base === "/") return path;
11
- const prefix = base.endsWith("/") ? base.slice(0, -1) : base;
12
- return path === "/" ? `${prefix}/` : `${prefix}${path}`;
13
- };
14
- export { withBase };
@@ -1,39 +0,0 @@
1
- import { NavigablePath, NavigablePatternOf, Routes, RoutesRecord } from "@k8ordo/router";
2
- /**
3
- * The app-side hook for typed route paths. An application augments this once,
4
- * with the same line its `@k8ordo/router` augmentation uses:
5
- *
6
- * ```ts
7
- * import type { routes } from './routes';
8
- * declare module '@k8ordo/state' {
9
- * interface Register { routes: typeof routes }
10
- * }
11
- * ```
12
- *
13
- * and every `href()` in the app is checked against the table's linkable
14
- * patterns. A router that is not `@k8ordo/router` registers its path union
15
- * directly — `interface Register { path: Route }` with `Route` from `next`.
16
- * Declared as an interface — the one exception to the repository's
17
- * type-only rule — because declaration merging is the entire mechanism.
18
- */
19
- export interface Register {}
20
- type LinkablePatterns<D> = D extends Routes<infer R extends RoutesRecord> ? { [K in NavigablePatternOf<R>]: K; }[NavigablePatternOf<R>] : never;
21
- /**
22
- * `Path` when the router a `Register` shape describes accepts it, and what
23
- * that router accepts when it does not, so the type error names the
24
- * alternatives: matched against the table's linkable patterns segment by
25
- * segment when it carries `routes` (refused, the patterns themselves),
26
- * against the union as given when it carries `path` (refused, that union),
27
- * and any `/`-path when it carries neither (refused, `` `/${string}` ``). A
28
- * union of paths is accepted only when every member is. `NavigablePath` is
29
- * imported as a type only, so `@k8ordo/router` is never loaded at runtime
30
- * and stays an optional peer.
31
- */
32
- export type AcceptedPath<R, Path extends string> = R extends {
33
- routes: infer Table;
34
- } ? [Path] extends [NavigablePath<Table, Path>] ? Path : LinkablePatterns<Table> : R extends {
35
- path: infer P extends string;
36
- } ? [Path] extends [P] ? Path : P : [Path] extends [`/${string}`] ? Path : `/${string}`;
37
- /** `href()`'s path check: `Path` when the registered router accepts it. */
38
- export type RegisteredPath<Path extends string> = AcceptedPath<Register, Path>;
39
- export {};
package/dist/register.mjs DELETED
@@ -1 +0,0 @@
1
- export {};