@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/README.md CHANGED
@@ -28,21 +28,21 @@ pnpm add @k8ordo/state zod
28
28
 
29
29
  <!-- peers -->
30
30
 
31
- | Package | Version | Required | Needed for |
32
- | ---------------- | ------- | -------- | ------------------------------------------------------- |
33
- | `react` | ≥19.3.0 | yes | `useAppState` |
34
- | `zod` | ^4.6.6 | yes | the schemas (`zod/mini` works, and is the lighter pick) |
35
- | `@k8ordo/router` | ^3.0.0 | optional | typed `href` paths from the app's route table |
36
- | `typescript` | ≥7.0.0 | optional | the shipped type declarations |
37
- | `@types/react` | ≥19.3.0 | optional | the shipped type declarations |
31
+ | Package | Version | Required | Needed for |
32
+ | ---------------- | ------- | -------- | ---------------------------------------------------------------------- |
33
+ | `react` | ≥19.3.0 | yes | `useAppState` |
34
+ | `zod` | ^4.6.6 | yes | the schemas (`zod/mini` works, and is the lighter pick) |
35
+ | `@k8ordo/router` | ^4.0.0 | optional | page state that stays with the page on screen while the next one loads |
36
+ | `typescript` | ≥7.0.0 | optional | the shipped type declarations |
37
+ | `@types/react` | ≥19.3.0 | optional | the shipped type declarations |
38
38
 
39
39
  <!-- /peers -->
40
40
 
41
41
  The schema ships to the browser here — the client parses and serializes with
42
42
  it — so reach for `zod/mini` unless the app already pays for classic `zod`.
43
- `@k8ordo/router` is a type-only peer: it is never loaded at runtime. Under
44
- it, `@k8ordo/framework` included, a page state keeps the values of the page
45
- on screen while the next one loads.
43
+ Under `@k8ordo/router` — `@k8ordo/framework` included — a page state keeps
44
+ the values of the page on screen while the next one loads; the two agree on
45
+ that through a global symbol, so neither imports the other.
46
46
 
47
47
  ## Quick Start
48
48
 
@@ -123,8 +123,11 @@ in `defineCookieState` instead of `defineLocalState`: in server mode,
123
123
  render, so the default never flashes.
124
124
 
125
125
  `update()` applies synchronously, batches per handler into one write (memory
126
- applies per call), and returns `{ committed, finished }` handles. `href` omits
127
- every field at its default, so every link is canonical. A value the schema
126
+ applies per call), and returns `{ committed, finished }` handles.
127
+ `href(url, values)` puts the state on the URL the router built —
128
+ `href('/products')` from `@k8ordo/router`, a Next.js `Route`, or `''` for
129
+ the page itself — rewriting only its own params and omitting every field at
130
+ its default, so every link is canonical. A value the schema
128
131
  rejects — a URL a user edited, a row an older schema wrote — falls back to its
129
132
  own default, field by field.
130
133
 
@@ -132,7 +135,7 @@ The [design guide](docs/GUIDE.md) covers the rest: the places and when each
132
135
  fits, history-entry state, cookie state the server renders (and why it is
133
136
  never a secret), migrating stored rows with `version` and `migrate`,
134
137
  batching and update handles, subscription granularity,
135
- router requirements, typed routes via `Register`, reading local state before
138
+ router requirements, building a link on the router's URL, reading local state before
136
139
  hydration with `inlineRead()`, and GET forms with `@k8ordo/form`.
137
140
 
138
141
  ## AI Agent Documentation
@@ -1,6 +1,9 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
1
  import { Versioning } from "./row/codec.mjs";
2
+ import { StateSchema } from "./schema/object.mjs";
3
3
  import { output } from "zod/v4/core";
4
+ type CookieReader = {
5
+ readonly get: (name: string) => string | undefined;
6
+ };
4
7
  /**
5
8
  * App-scope state that lives in a cookie: device-persistent and shared across
6
9
  * tabs like local state, and — unlike it — sent with every request, so a
@@ -17,18 +20,33 @@ export type CookieState<Schema extends StateSchema = StateSchema> = {
17
20
  /** The cookie the values are written under: `k8ordo-state.<key>`. */
18
21
  cookieName: string;
19
22
  /**
20
- * Reads the values out of a request's cookies on the server —
21
- * `request.cookies` under `@k8ordo/framework`'s server mode, whose values arrive
22
- * percent-decoded. Absent, corrupt, or rejected fields get their defaults.
23
+ * Reads the values out of a request's cookies on the server — anything
24
+ * whose `get(name)` gives a cookie's percent-decoded value:
25
+ * `request.cookies` in a page and `cookies()` in a guard, a route.ts or a
26
+ * Server Action under `@k8ordo/framework`'s server mode,
27
+ * `{ get: (name) => store.get(name)?.value }` over Next.js's
28
+ * `cookies()`. Absent, corrupt, or rejected fields get their defaults.
23
29
  */
24
- parseCookies: (cookies: ReadonlyMap<string, string>) => output<Schema>;
30
+ parseCookies: (cookies: CookieReader) => output<Schema>;
25
31
  /**
26
- * The value to hand a server's cookie API when it writes the same cookie
27
- * (`cookies().set` from `@k8ordo/framework/server`, Next.js's): the JSON of these
28
- * values, left for that API to percent-encode, as the browser store
29
- * encodes it before writing. Unspecified fields mean their default, and
30
- * the values pass the schema first, as `update()` does.
32
+ * The same cookie written from a server, as the arguments of its cookie
33
+ * API: `cookies().set(...density.cookie({ density: 'compact' }, cookies()))`
34
+ * under `@k8ordo/framework`'s server mode. `patch` goes over the values
35
+ * `current` holds — read as `parseCookies` reads them — as `update()` lays
36
+ * it over the cookie in the browser, so the fields it leaves out keep what
37
+ * the visitor saved; the result passes the schema. The value is the JSON
38
+ * left for that API to percent-encode, and the options are the browser
39
+ * store's own attributes with `httpOnly: false`, which keeps the cookie
40
+ * readable to the browser store. A cookie whose `migrate` throws is never
41
+ * written over: this throws instead, the error as its `cause`.
31
42
  */
32
- cookieValue: (values?: Readonly<Partial<output<Schema>>>) => string;
43
+ cookie: (patch: Readonly<Partial<output<Schema>>>, current: CookieReader) => readonly [name: string, value: string, options: CookieAttributes];
44
+ };
45
+ type CookieAttributes = {
46
+ readonly path: '/';
47
+ readonly sameSite: 'lax';
48
+ readonly maxAge: number;
49
+ readonly httpOnly: false;
33
50
  };
34
- export declare const defineCookieState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => CookieState<Schema>;
51
+ export declare const defineCookieState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => CookieState<Schema>;
52
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { createRowCodec } from "./row/codec.mjs";
2
- import { cookieInitialSnapshot, cookieStoreOf, parseCookieText } from "./store/cookie-store.mjs";
2
+ import { COOKIE_ATTRIBUTES, cookieInitialSnapshot, cookieStoreOf, parseCookieText } from "./store/cookie-store.mjs";
3
+ import { resolvePatch } from "./store/core.mjs";
3
4
  import { setKind } from "./store/kind.mjs";
4
5
  // src/cookie-state.ts
5
6
  const COOKIE_NAME_PREFIX = "k8ordo-state.";
@@ -8,13 +9,34 @@ const defineCookieState = (key, schema, versioning) => {
8
9
  const cookieName = `${COOKIE_NAME_PREFIX}${key}`;
9
10
  if (!TOKEN.test(cookieName)) throw new TypeError(`"${key}" cannot name a cookie — use letters, digits and !#$%&'*+-.^_\`|~`);
10
11
  const codec = createRowCodec(schema, "cookie", key, versioning);
12
+ const readRow = (cookies) => codec.read(parseCookieText(cookies.get(cookieName)));
11
13
  const def = {
12
14
  kind: "cookie",
13
15
  key,
14
16
  schema,
15
17
  cookieName,
16
- parseCookies: (cookies) => codec.read(parseCookieText(cookies.get(cookieName))).values,
17
- cookieValue: (values) => JSON.stringify(codec.row(codec.salvage(values ?? {})))
18
+ parseCookies: (cookies) => {
19
+ const row = readRow(cookies);
20
+ if (row.failed) console.error(`parseCookies: the migrate of "${key}" threw on the cookie ${cookieName}, which reads as nothing stored and is left as it is`, row.error);
21
+ return row.values;
22
+ },
23
+ cookie: (patch, current) => {
24
+ const row = readRow(current);
25
+ if (row.failed) throw new Error(`cookie: the migrate of "${key}" threw on the cookie ${cookieName}, which is left as it is rather than written over`, { cause: row.error });
26
+ const resolved = resolvePatch(patch, row.values, codec.keys, key);
27
+ const values = codec.salvage({
28
+ ...row.values,
29
+ ...resolved
30
+ });
31
+ return [
32
+ cookieName,
33
+ JSON.stringify(codec.row(values)),
34
+ {
35
+ ...COOKIE_ATTRIBUTES,
36
+ httpOnly: false
37
+ }
38
+ ];
39
+ }
18
40
  };
19
41
  setKind(def, {
20
42
  store: () => cookieStoreOf(def, codec),
package/dist/index.d.mts CHANGED
@@ -1,13 +1,11 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
- import { Versioning } from "./row/codec.mjs";
3
- import { CookieState, defineCookieState } from "./cookie-state.mjs";
4
- import { Register, RegisteredPath } from "./register.mjs";
5
- import { UrlInput } from "./url/codec.mjs";
6
1
  import { OutputOf, PageState, definePageState, urlReader } from "./page-state.mjs";
7
2
  import { LocalState, SessionState, defineLocalState, defineSessionState } from "./storage-state.mjs";
3
+ import { CookieState, defineCookieState } from "./cookie-state.mjs";
8
4
  import { MemoryState, defineMemoryState } from "./memory-state.mjs";
5
+ import { AnyState, useAppState } from "./use-app-state.mjs";
9
6
  import { UpdateHandle } from "./store/core.mjs";
10
7
  import { UpdateOptions } from "./store/page-store.mjs";
11
- import { AnyState, useAppState } from "./use-app-state.mjs";
12
- import { resetStateRegistry } from "./store/registry.mjs";
13
- export { type AnyState, type CookieState, type LocalState, type MemoryState, type OutputOf, type PageState, type Register, type RegisteredPath, type SessionState, type StateSchema, type UpdateHandle, type UpdateOptions, type UrlInput, type Versioning, defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, resetStateRegistry, urlReader, useAppState };
8
+ import { StateSchema } from "./schema/object.mjs";
9
+ import { Versioning } from "./row/codec.mjs";
10
+ import { UrlInput } from "./url/codec.mjs";
11
+ export { type AnyState, type CookieState, type LocalState, type MemoryState, type OutputOf, type PageState, type SessionState, type StateSchema, type UpdateHandle, type UpdateOptions, type UrlInput, type Versioning, defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, urlReader, useAppState };
package/dist/index.mjs CHANGED
@@ -1,7 +1,6 @@
1
- import { resetStateRegistry } from "./store/registry.mjs";
2
- import { defineCookieState } from "./cookie-state.mjs";
3
1
  import { definePageState, urlReader } from "./page-state.mjs";
4
2
  import { defineLocalState, defineSessionState } from "./storage-state.mjs";
3
+ import { defineCookieState } from "./cookie-state.mjs";
5
4
  import { defineMemoryState } from "./memory-state.mjs";
6
5
  import { useAppState } from "./use-app-state.mjs";
7
- export { defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, resetStateRegistry, urlReader, useAppState };
6
+ export { defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, urlReader, useAppState };
@@ -1,7 +1,6 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
1
  import { StoredCodec } from "./entry/codec.mjs";
3
2
  import { HashCodec } from "./hash/codec.mjs";
4
- import { RegisteredPath } from "./register.mjs";
3
+ import { StateSchema } from "./schema/object.mjs";
5
4
  import { UrlCodec, UrlInput } from "./url/codec.mjs";
6
5
  import { $ZodType, output } from "zod/v4/core";
7
6
  export type OutputOf<Schema> = Schema extends StateSchema ? output<Schema> : Record<never, never>;
@@ -22,15 +21,20 @@ export type PageState<Url extends StateSchema | undefined = StateSchema | undefi
22
21
  /** Reads the url slot on the server. Absent params get their defaults. */
23
22
  parseUrl: (input: UrlInput) => OutputOf<Url>;
24
23
  /**
25
- * Builds a link. Unspecified fields mean their default and defaults are
26
- * omitted from the query and the fragment, so canonical URLs stay short.
27
- * The path is in the table's terms and the URL carries Vite's `base` in
28
- * front of it; the path literal survives in the type, which is what lets
29
- * typed-route checks pass.
24
+ * Puts this state on a URL: the destination as the router built it —
25
+ * `@k8ordo/router`'s `href()`, a Next.js `Route` — or `''` for the page
26
+ * itself. Only this definition's url params are rewritten, in their
27
+ * canonical form: unspecified fields mean their default, and defaults are
28
+ * omitted. The URL's other params stay. With a hash slot the fragment is
29
+ * the value's (none at the default); without one the URL's own fragment
30
+ * stays. Nothing is added to the path — a `base` is the router's, and its
31
+ * `href()` has put it there — and the URL literal survives in the type,
32
+ * which is what typed-route checks read. When the URL handed in already
33
+ * carries this definition's params or a fragment, the type is an
34
+ * approximation: those params are rewritten, and the query goes in before
35
+ * the fragment.
30
36
  */
31
- href: <Path extends string>(path: RegisteredPath<Path>, values?: Readonly<Partial<OutputOf<Url> & HashOf<Hash>>>) => Path | `${Path}?${string}` | (Hash extends $ZodType ? `${Path}#${string}` : never);
32
- /** The query string alone (no `?`), for handrolled URL composition. */
33
- search: (values?: Readonly<Partial<OutputOf<Url>>>) => string;
37
+ href: <U extends string>(url: U, values?: Readonly<Partial<OutputOf<Url> & HashOf<Hash>>>) => U | `${U}?${string}` | (Hash extends $ZodType ? `${U}#${string}` : never);
34
38
  };
35
39
  type SharedKeys<Url, Entry> = Extract<keyof OutputOf<Url>, keyof OutputOf<Entry>> & string;
36
40
  type NamedHash<Url, Entry> = Extract<keyof OutputOf<Url> | keyof OutputOf<Entry>, 'hash'>;
@@ -1,10 +1,10 @@
1
- import { withBase } from "./base.mjs";
2
1
  import { createStoredCodec } from "./entry/codec.mjs";
3
- import { setKind } from "./store/kind.mjs";
4
- import { createUrlCodec } from "./url/codec.mjs";
5
2
  import { createHashCodec } from "./hash/codec.mjs";
3
+ import { setKind } from "./store/kind.mjs";
6
4
  import { pageInitialSnapshot, pageStoreOf } from "./store/page-store.mjs";
5
+ import { createUrlCodec } from "./url/codec.mjs";
7
6
  // src/page-state.ts
7
+ const keyOf = (pair) => new URLSearchParams(pair).keys().next().value ?? "";
8
8
  function definePageState(key, config) {
9
9
  const url = config.url === void 0 ? null : createUrlCodec(config.url);
10
10
  const entry = config.entry === void 0 ? null : createStoredCodec(config.entry, "entry");
@@ -13,7 +13,7 @@ function definePageState(key, config) {
13
13
  if (hash !== null && (url?.keys.includes("hash") === true || entry?.keys.includes("hash") === true)) throw new TypeError(`"${key}" declares hash beside a url or entry field named hash — the hash value takes that name in the state`);
14
14
  const shared = url === null || entry === null ? [] : url.keys.filter((field) => entry.keys.includes(field));
15
15
  if (shared.length > 0) throw new TypeError(`"${key}" declares in both url and entry: ${shared.join(", ")}`);
16
- const search = (values) => url === null ? "" : url.search(values ?? {});
16
+ const ownKeys = new Set(url?.keys);
17
17
  const def = {
18
18
  kind: "page",
19
19
  key,
@@ -21,12 +21,17 @@ function definePageState(key, config) {
21
21
  entry: config.entry,
22
22
  hash: config.hash,
23
23
  parseUrl: (input) => url === null ? {} : url.parse(input),
24
- search,
25
- href: (path, values) => {
26
- const query = search(values);
27
- const link = withBase(path);
28
- const located = query === "" ? link : `${link}?${query}`;
29
- const fragment = hash === null ? "" : hash.fragment(values?.hash);
24
+ href: (destination, values = {}) => {
25
+ const hashAt = destination.indexOf("#");
26
+ const beforeHash = hashAt === -1 ? destination : destination.slice(0, hashAt);
27
+ const queryAt = beforeHash.indexOf("?");
28
+ const path = queryAt === -1 ? beforeHash : beforeHash.slice(0, queryAt);
29
+ const kept = (queryAt === -1 ? "" : beforeHash.slice(queryAt + 1)).split("&").filter((pair) => pair !== "" && !ownKeys.has(keyOf(pair)));
30
+ const own = url === null ? "" : url.search(values);
31
+ const query = [...kept, ...own === "" ? [] : [own]].join("&");
32
+ const located = query === "" ? path : `${path}?${query}`;
33
+ if (hash === null) return hashAt === -1 ? located : `${located}${destination.slice(hashAt)}`;
34
+ const fragment = hash.fragment(values.hash);
30
35
  return fragment === "" ? located : `${located}#${fragment}`;
31
36
  }
32
37
  };
@@ -1,5 +1,5 @@
1
- import { StateSchema, StateValues } from "../schema/object.mjs";
2
1
  import { StoredCodec } from "../entry/codec.mjs";
2
+ import { StateSchema, StateValues } from "../schema/object.mjs";
3
3
  import { input } from "zod/v4/core";
4
4
  /**
5
5
  * How a local or cookie state reads rows an older version of its schema
@@ -18,8 +18,10 @@ export type Versioning<Schema extends StateSchema = StateSchema> = {
18
18
  * written before the definition declared a version. The result passes the
19
19
  * schema field by field like any read, so its keys are the schema's but its
20
20
  * values may be anything: map what you can, hand old values over as they
21
- * are, and leave the rest out. A throw reads as nothing stored and leaves
22
- * the row as it was.
21
+ * are, and leave the rest out. A throw reads as nothing stored and is
22
+ * reported — `reportError` in the browser, `console.error` from
23
+ * `parseCookies` — and the row stays as it was, through an `update()` too,
24
+ * for a fixed `migrate` to read.
23
25
  */
24
26
  migrate: (old: Readonly<Record<string, unknown>>, fromVersion: number) => { readonly [Key in keyof input<Schema>]?: unknown; };
25
27
  };
@@ -29,15 +31,18 @@ export type Versioning<Schema extends StateSchema = StateSchema> = {
29
31
  * never what an unversioned row holds (the values are always an object), so
30
32
  * the two never read as each other.
31
33
  */
34
+ export type RowRead = {
35
+ values: StateValues;
36
+ stale: boolean;
37
+ failed: false;
38
+ } | {
39
+ values: StateValues;
40
+ stale: false;
41
+ failed: true;
42
+ error: unknown;
43
+ };
32
44
  export type RowCodec = Omit<StoredCodec, 'parse'> & {
33
- /**
34
- * The values in a parsed row. `stale` when the row was written by an older
35
- * version and migrated here, so the caller writes it back.
36
- */
37
- read: (row: unknown) => {
38
- values: StateValues;
39
- stale: boolean;
40
- };
45
+ read: (row: unknown) => RowRead;
41
46
  /** The JSON-ready row for these values. */
42
47
  row: (values: Readonly<StateValues>) => unknown;
43
48
  /** The version rows are written with, `undefined` when unversioned. */
@@ -1,5 +1,5 @@
1
- import { isRecord } from "../schema/object.mjs";
2
1
  import { createStoredCodec } from "../entry/codec.mjs";
2
+ import { isRecord } from "../schema/object.mjs";
3
3
  // src/row/codec.ts
4
4
  const envelopeOf = (row) => {
5
5
  if (isRecord(row)) return {
@@ -18,7 +18,8 @@ const createRowCodec = (schema, slot, key, versioning) => {
18
18
  ...stored,
19
19
  read: (row) => ({
20
20
  values: stored.parse(row),
21
- stale: false
21
+ stale: false,
22
+ failed: false
22
23
  }),
23
24
  row: (values) => values,
24
25
  version: void 0
@@ -29,24 +30,29 @@ const createRowCodec = (schema, slot, key, versioning) => {
29
30
  const envelope = envelopeOf(row);
30
31
  if (envelope === null) return {
31
32
  values: stored.parse(void 0),
32
- stale: false
33
+ stale: false,
34
+ failed: false
33
35
  };
34
36
  if (envelope.fromVersion >= version) return {
35
37
  values: stored.parse(envelope.values),
36
- stale: false
38
+ stale: false,
39
+ failed: false
37
40
  };
38
41
  let migrated;
39
42
  try {
40
43
  migrated = migrate(envelope.values, envelope.fromVersion);
41
- } catch {
44
+ } catch (error) {
42
45
  return {
43
46
  values: stored.parse(void 0),
44
- stale: false
47
+ stale: false,
48
+ failed: true,
49
+ error
45
50
  };
46
51
  }
47
52
  return {
48
53
  values: stored.parse(migrated),
49
- stale: true
54
+ stale: true,
55
+ failed: false
50
56
  };
51
57
  };
52
58
  return {
@@ -1,5 +1,5 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
1
  import { Versioning } from "./row/codec.mjs";
2
+ import { StateSchema } from "./schema/object.mjs";
3
3
  type StorageState<Kind extends 'local' | 'session', Schema extends StateSchema> = {
4
4
  kind: Kind;
5
5
  /** Identity of this state: the storage key and the store registry slot. */
@@ -1,7 +1,12 @@
1
- import { StateValues } from "../schema/object.mjs";
2
- import { RowCodec } from "../row/codec.mjs";
3
1
  import { CookieState } from "../cookie-state.mjs";
2
+ import { RowCodec } from "../row/codec.mjs";
3
+ import { StateValues } from "../schema/object.mjs";
4
4
  import { Store } from "./core.mjs";
5
+ export declare const COOKIE_ATTRIBUTES: {
6
+ readonly path: '/';
7
+ readonly sameSite: 'lax';
8
+ readonly maxAge: number;
9
+ };
5
10
  export declare const parseCookieText: (text: string | undefined) => unknown;
6
11
  export declare const cookieStoreOf: (def: CookieState, codec: RowCodec) => Store;
7
12
  /**
@@ -1,7 +1,11 @@
1
1
  import { createHandle, createStoreCore, resolvePatch } from "./core.mjs";
2
2
  import { getOrCreateStore } from "./registry.mjs";
3
3
  // src/store/cookie-store.ts
4
- const MAX_AGE = 3456e4;
4
+ const COOKIE_ATTRIBUTES = {
5
+ path: "/",
6
+ sameSite: "lax",
7
+ maxAge: 3456e4
8
+ };
5
9
  const rawCookie = (name) => {
6
10
  for (const part of document.cookie.split(";")) {
7
11
  const at = part.indexOf("=");
@@ -26,8 +30,19 @@ const decoded = (raw) => {
26
30
  };
27
31
  const createCookieStore = (def, codec) => {
28
32
  const { cookieName } = def;
29
- const readRow = () => codec.read(parseCookieText(decoded(rawCookie(cookieName))));
30
- const read = () => readRow().values;
33
+ const readRow = () => {
34
+ const text = rawCookie(cookieName);
35
+ return {
36
+ ...codec.read(parseCookieText(decoded(text))),
37
+ text
38
+ };
39
+ };
40
+ let reported = null;
41
+ const reportFailed = (text, error) => {
42
+ if (text === reported) return;
43
+ reported = text;
44
+ reportError(error);
45
+ };
31
46
  let pending = null;
32
47
  let handle = null;
33
48
  let writing = 0;
@@ -38,7 +53,12 @@ const createCookieStore = (def, codec) => {
38
53
  return;
39
54
  }
40
55
  missed = false;
41
- const { values: fresh, stale } = readRow();
56
+ const row = readRow();
57
+ if (row.failed) {
58
+ reportFailed(row.text, row.error);
59
+ return;
60
+ }
61
+ const { values: fresh, stale } = row;
42
62
  if (stale) writeBack();
43
63
  core.applyNext(pending === null ? fresh : {
44
64
  ...fresh,
@@ -51,16 +71,21 @@ const createCookieStore = (def, codec) => {
51
71
  cookieStore.addEventListener("change", onChange);
52
72
  const write = async (patch, current) => {
53
73
  try {
74
+ const row = readRow();
75
+ if (row.failed) {
76
+ writing -= 1;
77
+ if (missed) sync();
78
+ current.fail(row.error);
79
+ return;
80
+ }
54
81
  const target = codec.salvage({
55
- ...read(),
82
+ ...row.values,
56
83
  ...patch
57
84
  });
58
85
  const init = {
59
86
  name: cookieName,
60
87
  value: encodeURIComponent(JSON.stringify(codec.row(target))),
61
- path: "/",
62
- sameSite: "lax",
63
- maxAge: MAX_AGE
88
+ ...COOKIE_ATTRIBUTES
64
89
  };
65
90
  await cookieStore.set(init);
66
91
  } catch (error) {
@@ -91,6 +116,7 @@ const createCookieStore = (def, codec) => {
91
116
  const first = readRow();
92
117
  const core = createStoreCore(codec.keys, first.values);
93
118
  if (first.stale) writeBack();
119
+ if (first.failed) reportFailed(first.text, first.error);
94
120
  const update = (patch) => {
95
121
  const resolved = resolvePatch(patch, core.snapshot(), codec.keys, def.key);
96
122
  if (pending === null) {
@@ -130,4 +156,4 @@ const cookieInitialSnapshot = (codec, initialCookie) => {
130
156
  }
131
157
  return base;
132
158
  };
133
- export { cookieInitialSnapshot, cookieStoreOf, parseCookieText };
159
+ export { COOKIE_ATTRIBUTES, cookieInitialSnapshot, cookieStoreOf, parseCookieText };
@@ -1,5 +1,5 @@
1
- import { StateValues } from "../schema/object.mjs";
2
1
  import { MemoryState } from "../memory-state.mjs";
2
+ import { StateValues } from "../schema/object.mjs";
3
3
  import { Store } from "./core.mjs";
4
4
  export declare const memoryStoreOf: (def: MemoryState) => Store;
5
5
  /** SSR renders the initial values — static, so no cross-request concern. */
@@ -1,5 +1,5 @@
1
- import { StateValues } from "../schema/object.mjs";
2
1
  import { PageInternals, PageState } from "../page-state.mjs";
2
+ import { StateValues } from "../schema/object.mjs";
3
3
  import { Store } from "./core.mjs";
4
4
  export type UpdateOptions = {
5
5
  /**
@@ -23,7 +23,7 @@ const readLive = (def, page) => {
23
23
  /**
24
24
  * The URL's pathname as the router compares a tree's: a trailing slash is
25
25
  * not another page. `@k8ordo/router`'s `normalizePathname`, spelled again —
26
- * the router is a peer this package only reads types from.
26
+ * this package never imports the router.
27
27
  */
28
28
  const livePathname = () => {
29
29
  const { pathname } = location;
@@ -1,5 +1,5 @@
1
- import { StateValues } from "../schema/object.mjs";
2
1
  import { RowCodec } from "../row/codec.mjs";
2
+ import { StateValues } from "../schema/object.mjs";
3
3
  import { LocalState, SessionState } from "../storage-state.mjs";
4
4
  import { Store } from "./core.mjs";
5
5
  /** What a store reads off a local or a session definition. */
@@ -27,9 +27,17 @@ const createStorageStore = (def, codec, storage) => {
27
27
  } catch {
28
28
  row = void 0;
29
29
  }
30
- return codec.read(row);
30
+ return {
31
+ ...codec.read(row),
32
+ text
33
+ };
34
+ };
35
+ let reported;
36
+ const reportFailed = (text, error) => {
37
+ if (text === reported) return;
38
+ reported = text;
39
+ reportError(error);
31
40
  };
32
- const read = () => readRow().values;
33
41
  const upgrade = () => {
34
42
  queueMicrotask(() => {
35
43
  try {
@@ -42,10 +50,14 @@ const createStorageStore = (def, codec, storage) => {
42
50
  try {
43
51
  first = readRow();
44
52
  } catch {
45
- first = codec.read(void 0);
53
+ first = {
54
+ ...codec.read(void 0),
55
+ text: null
56
+ };
46
57
  }
47
58
  const core = createStoreCore(codec.keys, first.values);
48
59
  if (first.stale) upgrade();
60
+ if (first.failed) reportFailed(first.text, first.error);
49
61
  let pending = null;
50
62
  let handle = null;
51
63
  const onStorage = (event) => {
@@ -57,6 +69,10 @@ const createStorageStore = (def, codec, storage) => {
57
69
  } catch {
58
70
  return;
59
71
  }
72
+ if (row.failed) {
73
+ reportFailed(row.text, row.error);
74
+ return;
75
+ }
60
76
  const { values: fresh, stale } = row;
61
77
  if (stale) upgrade();
62
78
  core.applyNext(pending === null ? fresh : {
@@ -71,8 +87,13 @@ const createStorageStore = (def, codec, storage) => {
71
87
  pending = null;
72
88
  handle = null;
73
89
  try {
90
+ const row = readRow();
91
+ if (row.failed) {
92
+ current.fail(row.error);
93
+ return;
94
+ }
74
95
  const target = codec.salvage({
75
- ...read(),
96
+ ...row.values,
76
97
  ...patch
77
98
  });
78
99
  const values = {};
@@ -1,3 +1,4 @@
1
+ import { resetStateRegistry } from "./store/registry.mjs";
1
2
  export type PageUrl = {
2
3
  /** Params to add to the search the page already has, as written. */
3
4
  search?: string;
@@ -15,4 +16,5 @@ export type PageUrl = {
15
16
  * waiting, and the URL and entry state found are put back. Unmount what was
16
17
  * rendered first, as for `resetStateRegistry()`.
17
18
  */
18
- export declare const mountPageUrl: ({ search, hash }?: PageUrl) => (() => void);
19
+ export declare const mountPageUrl: ({ search, hash }?: PageUrl) => (() => void);
20
+ export { resetStateRegistry };
package/dist/testing.mjs CHANGED
@@ -43,4 +43,4 @@ const mountPageUrl = ({ search, hash } = {}) => {
43
43
  navigation.removeEventListener("navigate", interceptAsRouter);
44
44
  };
45
45
  };
46
- export { mountPageUrl };
46
+ export { mountPageUrl, resetStateRegistry };
@@ -1,8 +1,8 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
1
  import { CookieState } from "./cookie-state.mjs";
2
+ import { MemoryState } from "./memory-state.mjs";
3
3
  import { HashOf, OutputOf, PageState } from "./page-state.mjs";
4
+ import { StateSchema } from "./schema/object.mjs";
4
5
  import { LocalState, SessionState } from "./storage-state.mjs";
5
- import { MemoryState } from "./memory-state.mjs";
6
6
  import { UpdateHandle } from "./store/core.mjs";
7
7
  import { UpdateOptions } from "./store/page-store.mjs";
8
8
  import { output } from "zod/v4/core";
@@ -19,16 +19,17 @@ type OptionsFor<Def> = Def extends {
19
19
  * the hydration render; without it those two renders see the defaults,
20
20
  * which flashes once the live URL takes over. The entry slot has no
21
21
  * server-side source, so it always starts from defaults there.
22
+ * `undefined` is the same as leaving it out.
22
23
  */
23
- initialUrl?: Readonly<UrlStateOf<Def>>;
24
+ initialUrl?: Readonly<UrlStateOf<Def>> | undefined;
24
25
  } : Def extends CookieState<infer Schema> ? {
25
26
  /**
26
27
  * What `parseCookies(request.cookies)` returned on the server, passed
27
28
  * down as a prop. It seeds SSR and the hydration render; without it
28
29
  * those two renders see the defaults, which flashes once the cookie
29
- * is read in the browser.
30
+ * is read in the browser. `undefined` is the same as leaving it out.
30
31
  */
31
- initialCookie?: Readonly<output<Schema>>;
32
+ initialCookie?: Readonly<output<Schema>> | undefined;
32
33
  } : never;
33
34
  export declare function useAppState<Def extends AnyState>(def: Def, options?: OptionsFor<Def>): [StateOf<Def>, UpdateFn<Def>];
34
35
  export declare function useAppState<Def extends AnyState, const Key extends Extract<keyof StateOf<Def>, string>>(def: Def, keys: readonly Key[], options?: OptionsFor<Def>): [Pick<StateOf<Def>, Key>, UpdateFn<Def>];