foldkit-mirror 0.6.3 → 0.8.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
@@ -1,7 +1,7 @@
1
1
  # `foldkit-mirror`
2
2
 
3
- Keeps part of a Foldkit Model represented somewhere else — usually the URL or a
4
- key-value store — **without making that representation the owner of the state**.
3
+ Keeps part of a Foldkit Model represented somewhere else — usually the URL, a
4
+ key-value store or a cookie — **without making that representation the owner of the state**.
5
5
 
6
6
  A filter can become `?filter=active`; a draft can survive a reload; a collapsed
7
7
  sidebar can be remembered. In every case the Model remains authoritative and
@@ -14,9 +14,9 @@ Model slice
14
14
  |
15
15
  | encode when it changes
16
16
  v
17
- URL / KeyValueStore
17
+ URL / KeyValueStore / cookie
18
18
 
19
- URL / KeyValueStore
19
+ URL / KeyValueStore / cookie
20
20
  |
21
21
  | decode on navigation / cold load
22
22
  v
@@ -54,6 +54,7 @@ Remote
54
54
  | --- | --- | --- |
55
55
  | Filter, sort, page, search text, open panel | local Model | URL via `Mirror.url` |
56
56
  | Preference, draft, collapsed sidebar | local Model | `KeyValueStore` via `Mirror.kv` |
57
+ | A cart or preference the server renders, or a page without scripts keeps | local Model | a cookie via `Mirror.cookie` |
57
58
  | Shared/offline edits that must converge | Sync/Durable | not Mirror |
58
59
  | Server-derived facts | server / Remote | not Mirror |
59
60
 
@@ -81,7 +82,7 @@ history.pushState / replaceState
81
82
  UrlChanged
82
83
  |
83
84
  v
84
- Filters.reduce(model, url)
85
+ Filters.urlChanged(model, url)
85
86
  |
86
87
  v
87
88
  Model
@@ -187,7 +188,7 @@ const Filters = Mirror.url(App, {
187
188
 
188
189
  With the default values, the URL stays clean. If the Model becomes:
189
190
 
190
- ```ts
191
+ ```ts sketch
191
192
  {
192
193
  filter: 'active',
193
194
  page: 2,
@@ -208,7 +209,7 @@ Navigation comes back through the application's normal URL Message:
208
209
  ```ts
209
210
  function update(model: Model, message: Message) {
210
211
  return Match.value(message).pipe(
211
- Match.tag('UrlChanged', ({ url }) => ({ model: Filters.reduce(model, url) })),
212
+ Match.tag('UrlChanged', ({ url }) => ({ model: Filters.urlChanged(model, url) })),
212
213
  Match.orElse(() => ({ model })),
213
214
  )
214
215
  }
@@ -234,13 +235,18 @@ That is the entire URL loop:
234
235
 
235
236
  ```text
236
237
  Model -> subscription -> URL
237
- URL -> UrlChanged -> reduce -> Model
238
+ URL -> UrlChanged -> urlChanged -> Model
238
239
  ```
239
240
 
241
+ `reduce` reads a starting URL; `urlChanged` reads one that arrives later.
240
242
  The loop closes without a second render: the mirror's own write comes back
241
- as a `UrlChanged` whose keys hold what the Model already holds, and `reduce`
242
- then returns the Model it was given. It does the same for a navigation that
243
- leaves its keys alone, and `Prefs.reduce` for a restore that finds nothing new.
243
+ as a `UrlChanged`, and `urlChanged` returns the Model it was given. It does
244
+ so for every write still to come back, not only the last, because under load
245
+ an echo can land after newer keystrokes, even after the next write, and
246
+ reading it would put the older text back. It also returns the Model for a
247
+ navigation that leaves its keys as it last read or wrote them (a path change,
248
+ another mirror's write), and `Prefs.reduce` does for a restore that finds
249
+ nothing new.
244
250
 
245
251
  ## Plug the URL into `makeApplication` with `Mirror.routing`
246
252
 
@@ -343,7 +349,7 @@ its variant:
343
349
  function update(model: Model, message: Message): Return {
344
350
  return Message.match(message, {
345
351
  GotPrefsMessage: ({ message }) => foldPrefs(model, message),
346
- UrlChanged: ({ url }) => ({ model: Filters.reduce(model, url) }),
352
+ UrlChanged: ({ url }) => ({ model: Filters.urlChanged(model, url) }),
347
353
  })
348
354
  }
349
355
  ```
@@ -370,7 +376,7 @@ const Message = defineMessageUnion({ ...Mirror.messages, UrlChanged: { url: Url
370
376
  function update(model: Model, message: Message): Return {
371
377
  if (Mirror.reduces(message)) return { model: Prefs.reduce(model, message) }
372
378
  return Match.value(message).pipe(
373
- Match.tag('UrlChanged', ({ url }) => ({ model: Filters.reduce(model, url) })),
379
+ Match.tag('UrlChanged', ({ url }) => ({ model: Filters.urlChanged(model, url) })),
374
380
  Match.orElse(() => ({ model })),
375
381
  )
376
382
  }
@@ -398,6 +404,86 @@ The important part is what did **not** change: `sidebar` and `draft` are still
398
404
  ordinary Model fields. The key-value store is merely how those fields are
399
405
  remembered between sessions.
400
406
 
407
+ ## Keep what a server renders in a cookie with `Mirror.cookie`
408
+
409
+ A key-value store lives in the browser, so a server rendering the page cannot
410
+ read it, and a page that works without JavaScript has no store at all. A
411
+ cookie travels with every request: the server reads it for the first render,
412
+ a form posted without scripts can set it in the answer, and the scripted page
413
+ writes it as the Model changes. This extends the Model with `cart`, a list of
414
+ names:
415
+
416
+ ```ts
417
+ const Cart = Mirror.cookie(App, {
418
+ name: 'cart',
419
+ fields: [App.model.cart],
420
+ })
421
+ ```
422
+
423
+ The cookie is named `cart` and holds the mirror's keys form-encoded
424
+ (`cart=cart=%5B%22acme.dev%22%5D`), so no character of the slice can end the
425
+ value or the header. Its three seams:
426
+
427
+ <!-- docs-check
428
+ import { Option } from 'effect'
429
+ declare const request: Request
430
+ declare const reached: Model
431
+ -->
432
+
433
+ ```ts
434
+ // On the server, before the first render: the request's cookie into the Model.
435
+ const opened = Mirror.bootstrap(initial, Cart.bootstrap(Cart.keysOf(request.headers.get('cookie'))))
436
+
437
+ // In a server's answer that changed the slice: `reached` is the Model a form
438
+ // posted without scripts reached through `update`.
439
+ const setCookie: Option.Option<string> = Cart.setCookie(reached, request)
440
+ ```
441
+
442
+ In the browser, `Cart.wiring()` (or `Cart.subscriptions`) writes
443
+ `document.cookie` whenever the encoded slice changes, at once by default. It
444
+ reads nothing at startup: the server's render already holds the slice, and a
445
+ page with no server reads it with `Cart.bootstrap(Cart.keysOf(document.cookie))`
446
+ in its `init`.
447
+
448
+ What each call does, and does not do:
449
+
450
+ - `keysOf(header)` picks the mirror's cookie out of a `Cookie` header and its
451
+ own keys out of that cookie. A cookie whose `name=value` is past `maxBytes`
452
+ (4096 by default) is read as holding nothing. It decodes nothing.
453
+ - `bootstrap(keys)` decodes each key through its codec, the field's Schema: a
454
+ key that does not decode leaves its field at the initial value, and
455
+ `Cart.decode(keys).issues` names it.
456
+ - `setCookie(model, request)` is the `Set-Cookie` value for the slice of
457
+ `model`, or one that clears the cookie when the slice is at its defaults.
458
+ It sets nothing itself; the answer's headers carry it. It is `None` when
459
+ the slice encodes past `maxBytes`, and the browser keeps what it held; a
460
+ browser write past it is skipped and reported as `CookieTooLarge`.
461
+
462
+ A cookie is the visitor's to edit. Decoding proves its shape, not its truth:
463
+ a cart that names a domain is not a price for it, so the server checks again
464
+ what it would not take from a form (domains-plus prices every name in its
465
+ cart cookie again). A cookie may keep less than its field: domains-plus's
466
+ cart codec (`keys: { cart: { codec } }`) writes the cart's names alone and
467
+ refuses to decode them, since a name holds no price, and its server reads
468
+ the names from `keysOf` and prices them. The browser writes the cookie, so it is never
469
+ `HttpOnly`; keep nothing secret in it.
470
+
471
+ The attributes default to `Path=/`, `SameSite=Lax`, a `Max-Age` of 365 days,
472
+ and `Secure` on an https page or for an https request; `attributes` changes
473
+ any of them, and a name, path or domain a header could not carry is refused
474
+ when the mirror is declared. **Behind a proxy that terminates TLS** (nginx,
475
+ Fly, Render) the server sees an http request, so `secure: 'auto'` leaves
476
+ `Secure` off every cookie the server sets: set `secure: true` in production
477
+ there, as here:
478
+
479
+ ```ts
480
+ const Theme = Mirror.cookie(App, {
481
+ name: 'theme',
482
+ fields: [App.model.theme],
483
+ attributes: { sameSite: 'Strict', maxAge: '30 days', secure: true },
484
+ })
485
+ ```
486
+
401
487
  ## Restore before the first render with bootstrap
402
488
 
403
489
  A key-value mirror normally restores asynchronously: `restore` reads the store
@@ -464,7 +550,7 @@ const url = wiring.url(url => Message.UrlChanged({ url }))
464
550
  ```
465
551
 
466
552
  `Filters.wiring('UrlChanged')` routes the application's URL Message into
467
- `Filters.reduce` and reads the URL at startup; `Prefs.wiring()` routes its own
553
+ `Filters.urlChanged` and reads the URL at startup; `Prefs.wiring()` routes its own
468
554
  `MirrorRestored` into `Prefs.reduce` and runs `Prefs.restore` at startup. Both
469
555
  tags are shared: two key-value mirrors each read only their own
470
556
  `MirrorRestored`, several URL mirrors each read their keys from one
@@ -519,7 +605,7 @@ Changing only the filter yields:
519
605
 
520
606
  A key that should remain explicit can opt in:
521
607
 
522
- ```ts
608
+ ```ts sketch
523
609
  keys: {
524
610
  page: { keep: true },
525
611
  }
@@ -541,7 +627,7 @@ other -> JSON
541
627
 
542
628
  Override a field when a friendlier representation is useful:
543
629
 
544
- ```ts
630
+ ```ts sketch
545
631
  keys: {
546
632
  tags: {
547
633
  codec: TagsAsCommaSeparatedText,
@@ -667,8 +753,9 @@ Writes are throttled so rapidly changing local state does not hammer the externa
667
753
  representation:
668
754
 
669
755
  ```text
670
- URL mirror default: 50 ms
671
- KV mirror default: 250 ms
756
+ URL mirror default: 50 ms
757
+ KV mirror default: 250 ms
758
+ cookie mirror default: 0 ms
672
759
  ```
673
760
 
674
761
  A newer slice supersedes a pending write through Foldkit's dependency restart
@@ -677,7 +764,7 @@ behavior.
677
764
  A key-value mirror stores one versioned JSON document under its configured key.
678
765
  It may also be scoped to a user or tenant:
679
766
 
680
- ```ts
767
+ ```ts sketch
681
768
  Mirror.kv(App, {
682
769
  key: 'todo/prefs',
683
770
  scope: principal.userId,
@@ -692,8 +779,27 @@ application's saved state writes an importer for that shape, or stores under a
692
779
  new key and version, rather than letting the old document fail to decode and
693
780
  calling the clean start a migration.
694
781
 
695
- Store failures are absorbed and logged rather than failing the application. A
696
- slice back at all defaults removes the stored document.
782
+ Store failures are absorbed rather than failing the application. A slice back
783
+ at all defaults removes the stored document.
784
+
785
+ ### Diagnostics
786
+
787
+ What a key-value or cookie mirror absorbs, it reports as a typed diagnostic through
788
+ `Diagnostics.Reporter` (`foldkit-surface`'s channel), which by default is
789
+ Effect's log, the browser's console:
790
+
791
+ | `_tag` | `level` | When |
792
+ | --- | --- | --- |
793
+ | `StoreUnread` | `warning` | The store failed a read: the mirror restored nothing. |
794
+ | `StoreUnwritten` | `warning` | The store failed a write, or the removal of a discarded document. |
795
+ | `StoreMalformed` | `warning` | The key held a document no mirror writes (not JSON, or not its shape): something else writes that key. Another version or scope is a mirror's own, discarded with no report. |
796
+ | `CookieTooLarge` | `warning` | A cookie mirror's slice encoded past its `maxBytes`, so the browser write was skipped and the cookie keeps what it held. Carries `name`, `bytes` and `maxBytes`. |
797
+
798
+ Each key-value diagnostic carries its `key`, and the store's `error` or the `reason`. Send them
799
+ elsewhere with `Layer.succeed(Diagnostics.Reporter, report)` in the runtime's
800
+ resources; in a test, provide `Diagnostics.collect().report` and assert on
801
+ `reported`. A URL key that does not decode is not reported: it is what the
802
+ reader typed, and `mirror.decode(keys).issues` names it.
697
803
 
698
804
  ## Contracts and `Module`
699
805
 
@@ -767,6 +873,8 @@ this kernel.
767
873
  owners; cold-load precedence follows the URL -> KV -> initial rule above.
768
874
  - A URL mirror only touches the keys it owns. It composes with a Foldkit
769
875
  router's `route.query(schema)` when they use different keys.
876
+ - A cookie is sent with every request to its path, and browsers keep about
877
+ 4 KB of one: mirror a few small fields there, not a document.
770
878
  - Mirror stores have no durable operation log, conflict resolution, or
771
879
  multi-device synchronization.
772
880
 
package/dist/index.d.mts CHANGED
@@ -1,13 +1,47 @@
1
- import { Duration, Effect, Schema } from "effect";
1
+ import { Duration, Effect, Option, Schema } from "effect";
2
2
  import { KeyValueStore } from "effect/persistence";
3
3
  import { Command } from "foldkit/command";
4
4
  import * as Navigation from "foldkit/navigation";
5
5
  import { EntryWithoutKeepAlive } from "foldkit/subscription";
6
- import { Contract, FieldRef, Wiring, WritableProjection } from "foldkit-surface";
6
+ import { Contract, Diagnostic, FieldRef, RefTypeId, Wiring, WritableProjection } from "foldkit-surface";
7
7
  import { RoutingConfig } from "foldkit/runtime";
8
8
  import * as Update from "foldkit/update";
9
9
  import { Url } from "foldkit/url";
10
- //#region src/index.d.ts
10
+ /** The store failed to read the mirror's document: the slice restored nothing. */
11
+ interface StoreUnread extends Diagnostic {
12
+ readonly _tag: 'StoreUnread';
13
+ readonly key: string;
14
+ readonly error: KeyValueStore.KeyValueStoreError;
15
+ }
16
+ /** The store failed to write (or remove) the mirror's document: the slice was not kept. */
17
+ interface StoreUnwritten extends Diagnostic {
18
+ readonly _tag: 'StoreUnwritten';
19
+ readonly key: string;
20
+ readonly error: KeyValueStore.KeyValueStoreError;
21
+ }
22
+ /**
23
+ * The document under the mirror's key is not one a mirror writes (not JSON,
24
+ * or not its shape), so it was discarded: something else writes that key.
25
+ * Another version or scope is a mirror's own and is discarded with no report.
26
+ */
27
+ interface StoreMalformed extends Diagnostic {
28
+ readonly _tag: 'StoreMalformed';
29
+ readonly key: string;
30
+ /** Why it did not decode. */
31
+ readonly reason: string;
32
+ }
33
+ /**
34
+ * A cookie mirror's slice encoded past its `maxBytes`, so it was not written:
35
+ * the browser would drop it, and the cookie keeps what it held.
36
+ */
37
+ interface CookieTooLarge extends Diagnostic {
38
+ readonly _tag: 'CookieTooLarge';
39
+ readonly name: string;
40
+ readonly bytes: number;
41
+ readonly maxBytes: number;
42
+ }
43
+ /** Every diagnostic a mirror reports. */
44
+ type MirrorDiagnostic = StoreUnread | StoreUnwritten | StoreMalformed | CookieTooLarge;
11
45
  /** The keys a mirror holds in a store, as the store holds them: strings. */
12
46
  export type Encoded = Readonly<Record<string, string>>;
13
47
  /** The read entry's dependencies: the encoded slice, as a Struct so Foldkit can compare it. */
@@ -39,6 +73,23 @@ declare const kvStore: (options: {
39
73
  readonly key: string;
40
74
  readonly scope?: string | undefined;
41
75
  }) => MirrorStore<KeyValueStore.KeyValueStore>;
76
+ /** `Mirror.cookie`'s attributes; each default is what a cookie the browser writes needs. */
77
+ export interface CookieAttributes {
78
+ /** Default `/`, so every page sends it. */
79
+ readonly path?: string | undefined;
80
+ /** Default none: the host that set it, and no other. */
81
+ readonly domain?: string | undefined;
82
+ /** Default `Lax`: sent on a navigation and a same-site post, never a cross-site post. */
83
+ readonly sameSite?: 'Strict' | 'Lax' | 'None' | undefined;
84
+ /**
85
+ * Default `auto`: `Secure` on an https page, or for an https request on the
86
+ * server. Behind a proxy that terminates TLS the server's request is http,
87
+ * so a cookie it sets has no `Secure`: set `true` in production there.
88
+ */
89
+ readonly secure?: boolean | 'auto' | undefined;
90
+ /** How long the browser keeps it; default 365 days. */
91
+ readonly maxAge?: Duration.Input | undefined;
92
+ }
42
93
  /** An in-memory store that records its writes, for tests and for a mirror with no host. */
43
94
  export interface MemoryStore extends MirrorStore {
44
95
  /** What the store holds now. */
@@ -79,7 +130,7 @@ type TypeOf<S> = S extends {
79
130
  */
80
131
  export type Slice = WritableProjection<any, any> | readonly FieldRef<any, any, string>[];
81
132
  /** The Struct fields of a slice. */
82
- export type SliceFields<S extends Slice> = S extends WritableProjection<any, infer Fields> ? Fields : S extends readonly FieldRef<any, any, string>[] ? { readonly [R in S[number] as R['key']]: R['Schema']; } : never;
133
+ export type SliceFields<S extends Slice> = S extends WritableProjection<any, infer Fields> ? Fields : S extends readonly FieldRef<any, any, string>[] ? { readonly [R in S[number] as R[typeof RefTypeId]['key']]: R[typeof RefTypeId]['Schema']; } : never;
83
134
  /** The Model a slice is of. */
84
135
  export type SliceRoot<S extends Slice> = S extends WritableProjection<infer Root, any> ? Root : S extends readonly FieldRef<infer Root, any, string>[] ? Root : never;
85
136
  /** The value a slice reads. */
@@ -120,6 +171,17 @@ export interface KvMirrorConfig<S extends Slice, Name extends string = string> e
120
171
  /** A user, a tenant: a document of another scope is discarded rather than restored. */
121
172
  readonly scope?: string | undefined;
122
173
  }
174
+ export interface CookieMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<S, Name> {
175
+ /** The cookie's name, a token (`cart`); also the mirror's name. */
176
+ readonly name: Name;
177
+ readonly attributes?: CookieAttributes | undefined;
178
+ /**
179
+ * The most the cookie's `name=value` may hold, in bytes; default 4096, what
180
+ * every browser keeps. A slice encoded past it is not written, and a cookie
181
+ * past it is read as holding nothing.
182
+ */
183
+ readonly maxBytes?: number | undefined;
184
+ }
123
185
  /** One key that failed to decode; the field keeps its initial value. */
124
186
  export interface DecodeIssue {
125
187
  readonly key: string;
@@ -148,7 +210,7 @@ export type Bootstrap<AppModel> = (model: AppModel) => AppModel;
148
210
  * `Mirror.url` and `Mirror.kv` add the `reduce` their store calls for.
149
211
  */
150
212
  export interface Mirror<AppModel, Value extends Record<string, unknown>, R = never, Name extends string = string> {
151
- readonly kind: 'url' | 'kv' | 'memory';
213
+ readonly kind: 'url' | 'kv' | 'cookie' | 'memory';
152
214
  readonly name: Name;
153
215
  /** Store key per field. */
154
216
  readonly keys: Readonly<Record<keyof Value & string, string>>;
@@ -190,11 +252,22 @@ export interface Mirror<AppModel, Value extends Record<string, unknown>, R = nev
190
252
  /** A slice kept in the URL. */
191
253
  export interface UrlMirror<AppModel, Value extends Record<string, unknown>, Name extends string = string> extends Mirror<AppModel, Value, never, Name> {
192
254
  readonly kind: 'url';
193
- /** The Model with the URL's keys (a Foldkit `Url` or an href) as the whole slice: `fromKeys`. */
255
+ /**
256
+ * The Model with the URL's keys (a Foldkit `Url` or an href) as the whole
257
+ * slice: `fromKeys`. For the starting URL; a later one is `urlChanged`'s.
258
+ */
194
259
  readonly reduce: (model: AppModel, url: Url | string) => AppModel;
260
+ /**
261
+ * The Model after a `UrlChanged`: `reduce`, unless the URL is the echo of
262
+ * one of this mirror's writes or leaves its keys as it last read or wrote
263
+ * them (a path change, another mirror's write), when the Model is returned
264
+ * as it is. An echo can land after newer edits, and reading it would undo
265
+ * them.
266
+ */
267
+ readonly urlChanged: (model: AppModel, url: Url | string) => AppModel;
195
268
  /**
196
269
  * How this mirror joins an assembly: it routes the application's URL Message
197
- * (a variant with a `url` field, tagged `tag`) into `reduce`, reads the URL at
270
+ * (a variant with a `url` field, tagged `tag`) into `urlChanged`, reads the URL at
198
271
  * startup, and brings its Subscriptions and contract. Several URL mirrors share
199
272
  * the URL Message.
200
273
  */
@@ -262,6 +335,36 @@ export interface KvMirror<AppModel, Value extends Record<string, unknown>, Name
262
335
  */
263
336
  readonly wiring: () => KvMirrorWiring<AppModel>;
264
337
  }
338
+ /**
339
+ * A slice kept in one cookie, which the server reads for a render and the
340
+ * browser writes when the slice changes. A cookie is the visitor's to edit:
341
+ * `keysOf` and `decode` check its shape, and what the application trusts
342
+ * (a price, a permission) it checks again.
343
+ */
344
+ export interface CookieMirror<AppModel, Value extends Record<string, unknown>, Name extends string = string> extends Mirror<AppModel, Value, never, Name> {
345
+ readonly kind: 'cookie';
346
+ /**
347
+ * The mirror's keys a `Cookie` header holds (`request.headers.get('cookie')`,
348
+ * or `document.cookie`), for `bootstrap` or `decode`: only the keys it owns,
349
+ * and none from a cookie past `maxBytes`.
350
+ */
351
+ readonly keysOf: (cookieHeader: string | null) => Encoded;
352
+ /**
353
+ * The `Set-Cookie` value keeping the slice of `model`, for a server's answer
354
+ * (a form posted without scripts): it clears the cookie when the slice is at
355
+ * its defaults, and `Secure` is `auto`'s for `request.url`. `None` when the
356
+ * slice encodes past `maxBytes`: the browser keeps the cookie it holds.
357
+ */
358
+ readonly setCookie: (model: AppModel, request: {
359
+ readonly url: string;
360
+ }) => Option.Option<string>;
361
+ /**
362
+ * How this mirror joins an assembly: its Subscription, which writes the
363
+ * cookie, and its contract. It reads nothing at startup; `bootstrap` does,
364
+ * from the request's cookie on the server or `document.cookie` in a browser.
365
+ */
366
+ readonly wiring: () => Wiring<AppModel, never>;
367
+ }
265
368
  /** An application a mirror is declared over: its identity token, and its initial Model when it has one. */
266
369
  export interface MirrorApp<AppModel> {
267
370
  readonly owner: object;
@@ -351,8 +454,9 @@ export declare const Mirror: {
351
454
  * URL mirrors plugged into `Runtime.makeApplication`: spread the result into
352
455
  * its config. `init` reads the starting URL into the Model the application's
353
456
  * `init` returns; `update` reads a `urlChanged` Message's URL into the Model
354
- * before the application's `update` sees it, so a route handler finds the
355
- * slices already read. `routing` is the application's own, passed through.
457
+ * (each mirror's `urlChanged`, so an echo changes nothing) before the
458
+ * application's `update` sees it, so a route handler finds the slices
459
+ * already read. `routing` is the application's own, passed through.
356
460
  *
357
461
  * @example
358
462
  * ```ts
@@ -384,9 +488,16 @@ export declare const Mirror: {
384
488
  * `restore` Command whose `MirrorRestored` `reduce` applies.
385
489
  */
386
490
  kv: <S extends Slice, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, config: KvMirrorConfig<S, Name>) => KvMirror<SliceRoot<S>, SliceValue<S>, Name>;
491
+ /**
492
+ * A slice kept in one cookie named `name`, its keys form-encoded in the
493
+ * value: written from the browser when it changes, read by the server
494
+ * (`keysOf` the request's `Cookie` header, then `bootstrap`) so the first
495
+ * render holds it, and set by a server's answer with `setCookie`. A browser
496
+ * writes it, so it is never `HttpOnly`: keep nothing secret in it.
497
+ */
498
+ cookie: <S extends Slice, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, config: CookieMirrorConfig<S, Name>) => CookieMirror<SliceRoot<S>, SliceValue<S>, Name>;
387
499
  /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`, bootstrapped with `bootstrap`. */
388
500
  make: <S extends Slice, R, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, store: MirrorStore<R>, config: MirrorConfig<S, Name>) => Mirror<SliceRoot<S>, SliceValue<S>, R, Name>;
389
501
  };
390
- //#endregion
391
- export {};
502
+ export type { CookieTooLarge, MirrorDiagnostic, StoreMalformed, StoreUnread, StoreUnwritten };
392
503
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;YAkCY,UAAU,SAAS;;iBAGd;WACN,MAAM;;;iBAIA;WACN,KAAK;WACL,QAAQ;;WAER;;;;;;;iBAQM,YAAY;WAClB,MAAM,OAAO,OAAO,4BAA4B;WAChD,QAAQ,OAAO,gBAAgB,OAAO,oBAAoB;;;YAIzD;;qBA6BC,cAAW,cACV,OACL,KAAK,gCAA8B,WAChC;cAmBN,WAAQ,OAAW,uBAAqB,UAAY,gBAAc;cA0BlE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KAAc,SAClC,MACR,WAAW,QAAQ;aAAc;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BpC,YAAY,UAAQ,OAAS,aAAQ,OAAY,cAAc,UAAU,eAAa;;;;;;;EAStF,MAAM,UAAU,OAAO,8BAA4B,KAC5C,UAAU,UAAU,KAAG,QACpB,gBAAgB,GAAG,UAC1B,UAAU,UAAU,IAAI,WAAW,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;EA2F1C,UACE,UACA;aAA2B;WACrB,YAAY,iBAClB,aAAa,wBACb;aAA8B,OAAO;KACrC;aAAgC,OAAO;KAAU,QAEzC,oBAAoB,UAAU,SAAS,KAAK,MAAM,YAAY,kBACrE,cAAc,UAAU,SAAS,MAAM,YAAY;;;;;;EAwBtD,KAAK,UAAU,OAAO,8BAA4B,KAC3C,UAAU,UAAU,KAAG,QACpB,eAAe,GAAG,UACzB,SAAS,UAAU,IAAI,WAAW,IAAI;;;;;;;;EA0CzC,SAAS,UAAU,OAAO,8BAA4B,KAC/C,UAAU,UAAU,KAAG,QACpB,mBAAmB,GAAG,UAC7B,aAAa,UAAU,IAAI,WAAW,IAAI;;EAoC7C,OAAO,UAAU,OAAO,GAAG,8BAA4B,KAChD,UAAU,UAAU,KAAG,OACrB,YAAY,IAAE,QACb,aAAa,GAAG,UACvB,OAAO,UAAU,IAAI,WAAW,IAAI,GAAG"}
package/dist/index.mjs CHANGED
@@ -1,11 +1,66 @@
1
- import { Effect, Option, Result, Schema, Stream } from "effect";
1
+ import { Duration, Effect, Option, Result, Schema, Stream } from "effect";
2
2
  import { KeyValueStore } from "effect/persistence";
3
3
  import { mapMessage } from "foldkit/command";
4
4
  import { defineMessageUnion } from "foldkit/message";
5
5
  import * as Navigation from "foldkit/navigation";
6
6
  import * as Subscription from "foldkit/subscription";
7
- import { Projection } from "foldkit-surface";
8
- //#region src/index.ts
7
+ import { Diagnostics, Projection } from "foldkit-surface";
8
+ // src/diagnostics.ts
9
+ const source = "foldkit-mirror";
10
+ const cookieTooLarge = (name, bytes, maxBytes) => ({
11
+ _tag: "CookieTooLarge",
12
+ source,
13
+ level: "warning",
14
+ message: `the cookie "${name}" would be ${bytes} bytes, past its ${maxBytes}, so it was not written and keeps what it held.`,
15
+ name,
16
+ bytes,
17
+ maxBytes
18
+ });
19
+ const storeUnread = (key, error) => ({
20
+ _tag: "StoreUnread",
21
+ source,
22
+ level: "warning",
23
+ message: `could not read "${key}" (${error.message}), so the mirror restored nothing.`,
24
+ key,
25
+ error
26
+ });
27
+ const storeUnwritten = (key, error) => ({
28
+ _tag: "StoreUnwritten",
29
+ source,
30
+ level: "warning",
31
+ message: `could not write "${key}" (${error.message}), so the store does not hold the slice.`,
32
+ key,
33
+ error
34
+ });
35
+ const storeMalformed = (key, reason) => ({
36
+ _tag: "StoreMalformed",
37
+ source,
38
+ level: "warning",
39
+ message: `"${key}" held a document no mirror writes (${reason}); it was discarded. Give the mirror a key nothing else writes.`,
40
+ key,
41
+ reason
42
+ });
43
+ // src/record.ts
44
+ /**
45
+ * Records keyed by a field's name or a store's key, which an application or a
46
+ * URL chooses. Read as `record[key]`, `constructor` or `toString` finds
47
+ * `Object.prototype`'s; written as `record[key] = value`, `__proto__` sets the
48
+ * prototype and adds no key.
49
+ */
50
+ /** The value `record` holds under `key` itself, never one it inherits. */
51
+ const own = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
52
+ /** Sets `key` on `record` as a key of its own, whatever the name. */
53
+ const put = (record, key, value) => {
54
+ Object.defineProperty(record, key, {
55
+ value,
56
+ writable: true,
57
+ enumerable: true,
58
+ configurable: true
59
+ });
60
+ };
61
+ /** An empty record with no prototype, for a table only this package reads. */
62
+ const table = () => Object.create(null);
63
+ // src/index.ts
9
64
  /**
10
65
  * `foldkit-mirror` — a Model slice kept in the URL or a key-value store.
11
66
  *
@@ -35,7 +90,7 @@ const readParams = (query, owned) => {
35
90
  const out = {};
36
91
  for (const key of owned) {
37
92
  const value = params.get(key);
38
- if (value !== null) out[key] = value;
93
+ if (value !== null) put(out, key, value);
39
94
  }
40
95
  return out;
41
96
  };
@@ -54,21 +109,24 @@ const currentHref = () => {
54
109
  const loc = globalThis.location;
55
110
  return loc === void 0 ? void 0 : `${loc.pathname}${loc.search}${loc.hash}`;
56
111
  };
57
- const urlStore = (owned, location) => ({
112
+ const urlStoreReporting = (owned, location, wrote) => ({
58
113
  read: Effect.sync(() => {
59
114
  const href = currentHref();
60
115
  if (href === void 0) return void 0;
61
116
  const parts = splitHref(href);
62
117
  return readParams(location === "search" ? parts.search : parts.hash, owned);
63
118
  }),
64
- write: (write) => Effect.suspend(() => {
119
+ write: (write) => Effect.uninterruptible(Effect.suspend(() => {
65
120
  const href = currentHref();
66
121
  if (href === void 0) return Effect.void;
67
122
  const next = applyToHref(href, write, location);
68
123
  if (next === href) return Effect.void;
124
+ wrote(next);
69
125
  return write.intent === "push" ? Navigation.pushUrl(next) : Navigation.replaceUrl(next);
70
- })
126
+ }))
71
127
  });
128
+ const MAX_AWAITED = 64;
129
+ const urlStore = (owned, location) => urlStoreReporting(owned, location, () => {});
72
130
  const KV_VERSION = 1;
73
131
  const KvDocument = Schema.Struct({
74
132
  version: Schema.Number,
@@ -83,13 +141,15 @@ const kvStore = (options) => {
83
141
  const kv = yield* KeyValueStore.KeyValueStore;
84
142
  const raw = yield* Effect.result(kv.get(options.key));
85
143
  if (Result.isFailure(raw)) {
86
- yield* Effect.logWarning(`Mirror: could not read "${options.key}"`, raw.failure);
144
+ yield* Diagnostics.report(storeUnread(options.key, raw.failure));
87
145
  return;
88
146
  }
89
147
  if (raw.success === void 0) return void 0;
90
148
  const document = decode(raw.success);
149
+ if (Result.isFailure(document)) yield* Diagnostics.report(storeMalformed(options.key, document.failure.message));
91
150
  if (Result.isFailure(document) || document.success.version !== KV_VERSION || document.success.scope !== options.scope) {
92
- yield* Effect.result(kv.remove(options.key));
151
+ const removed = yield* Effect.result(kv.remove(options.key));
152
+ if (Result.isFailure(removed)) yield* Diagnostics.report(storeUnwritten(options.key, removed.failure));
93
153
  return;
94
154
  }
95
155
  return document.success.keys;
@@ -102,10 +162,86 @@ const kvStore = (options) => {
102
162
  keys: write.set
103
163
  });
104
164
  const outcome = yield* Effect.result(Object.keys(write.set).length === 0 ? kv.remove(options.key) : kv.set(options.key, text));
105
- if (Result.isFailure(outcome)) yield* Effect.logWarning(`Mirror: could not write "${options.key}"`, outcome.failure);
165
+ if (Result.isFailure(outcome)) yield* Diagnostics.report(storeUnwritten(options.key, outcome.failure));
106
166
  })
107
167
  };
108
168
  };
169
+ const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
170
+ const ATTRIBUTE_VALUE = /^[!-:<-~]+$/;
171
+ const cookieSpec = (name, owned, attributes, maxBytes) => {
172
+ const refuse = (why) => {
173
+ throw new Error(`Mirror.cookie("${name}"): ${why}`);
174
+ };
175
+ if (!COOKIE_NAME.test(name)) refuse("a cookie name is a token: letters, digits and !#$%&'*+-.^_`|~");
176
+ const path = attributes.path ?? "/";
177
+ if (!path.startsWith("/") || !ATTRIBUTE_VALUE.test(path)) refuse(`the path "${path}" starts with / and holds no space, control or ;`);
178
+ const domain = Option.fromUndefinedOr(attributes.domain);
179
+ if (Option.exists(domain, (domain) => !/^[0-9A-Za-z.-]+$/.test(domain))) refuse("a domain holds letters, digits, dots and hyphens only");
180
+ const sameSite = attributes.sameSite ?? "Lax";
181
+ const secure = attributes.secure ?? "auto";
182
+ if (sameSite === "None" && secure !== true) refuse("SameSite=None needs secure: true");
183
+ const maxAge = Math.floor(Duration.toSeconds(Duration.fromInputUnsafe(attributes.maxAge ?? "365 days")));
184
+ if (!(maxAge > 0)) refuse("maxAge is longer than a second");
185
+ if (!(maxBytes > 0)) refuse("maxBytes is a positive number");
186
+ return {
187
+ name,
188
+ owned,
189
+ attributes: [
190
+ `Path=${path}`,
191
+ ...Option.match(domain, {
192
+ onNone: () => [],
193
+ onSome: (domain) => [`Domain=${domain}`]
194
+ }),
195
+ `SameSite=${sameSite}`
196
+ ],
197
+ secure,
198
+ maxAge,
199
+ maxBytes
200
+ };
201
+ };
202
+ /** The mirror's keys a `Cookie` header (or `document.cookie`) holds: none for a cookie past `maxBytes`. */
203
+ const keysOfCookie = (spec, header) => {
204
+ for (const part of header.split(";")) {
205
+ const at = part.indexOf("=");
206
+ if (at < 0 || part.slice(0, at).trim() !== spec.name) continue;
207
+ const value = part.slice(at + 1).trim();
208
+ return spec.name.length + 1 + value.length > spec.maxBytes ? {} : readParams(value, spec.owned);
209
+ }
210
+ return {};
211
+ };
212
+ /**
213
+ * The `Set-Cookie` value keeping `keys`, or clearing the cookie when there are
214
+ * none; the length of its `name=value` when that is past `maxBytes`. The keys
215
+ * are form-encoded, which leaves only characters a cookie's value allows.
216
+ */
217
+ const setCookieOf = (spec, keys, https) => {
218
+ const value = new URLSearchParams(Object.entries(keys)).toString();
219
+ const pair = `${spec.name}=${value}`;
220
+ if (pair.length > spec.maxBytes) return Result.fail(pair.length);
221
+ const secure = spec.secure === "auto" ? https : spec.secure;
222
+ return Result.succeed([
223
+ pair,
224
+ ...spec.attributes,
225
+ `Max-Age=${value === "" ? 0 : spec.maxAge}`,
226
+ ...secure ? ["Secure"] : []
227
+ ].join("; "));
228
+ };
229
+ const documentOf = () => Option.fromUndefinedOr(globalThis.document);
230
+ const cookieStore = (spec) => ({
231
+ read: Effect.sync(() => Option.match(documentOf(), {
232
+ onNone: () => void 0,
233
+ onSome: (document) => keysOfCookie(spec, document.cookie)
234
+ })),
235
+ write: (write) => Option.match(documentOf(), {
236
+ onNone: () => Effect.void,
237
+ onSome: (document) => Result.match(setCookieOf(spec, write.set, globalThis.location?.protocol === "https:"), {
238
+ onFailure: (bytes) => Diagnostics.report(cookieTooLarge(spec.name, bytes, spec.maxBytes)),
239
+ onSuccess: (line) => Effect.sync(() => {
240
+ document.cookie = line;
241
+ })
242
+ })
243
+ })
244
+ });
109
245
  const memoryStore = (initial) => {
110
246
  let held = initial;
111
247
  const writes = [];
@@ -115,7 +251,7 @@ const memoryStore = (initial) => {
115
251
  writes.push(write);
116
252
  const next = { ...held ?? {} };
117
253
  for (const key of write.remove) delete next[key];
118
- Object.assign(next, write.set);
254
+ for (const [key, value] of Object.entries(write.set)) put(next, key, value);
119
255
  held = next;
120
256
  }),
121
257
  current: () => held,
@@ -204,12 +340,12 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
204
340
  if (initial === void 0) throw new Error(`Mirror.${kind}: defaults are read from the initial Model, so build the application with \`initial\` or pass \`initial\` in the config`);
205
341
  const initialSlice = fields.get(initial);
206
342
  const location = config.location ?? "search";
207
- const keyOf = {};
208
- const fieldOf = {};
343
+ const keyOf = table();
344
+ const fieldOf = table();
209
345
  const codecs = {};
210
- const history = {};
346
+ const history = table();
211
347
  const keep = /* @__PURE__ */ new Set();
212
- const initialText = {};
348
+ const initialText = table();
213
349
  for (const field of names) {
214
350
  const option = options[field];
215
351
  const key = option?.key ?? field;
@@ -240,7 +376,7 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
240
376
  for (const field of names) {
241
377
  const text = encodeField(field, slice[field]);
242
378
  if (!keep.has(field) && text === initialText[field]) continue;
243
- out[keyOf[field]] = text;
379
+ put(out, keyOf[field], text);
244
380
  }
245
381
  return out;
246
382
  };
@@ -250,14 +386,14 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
250
386
  const issues = [];
251
387
  for (const field of names) {
252
388
  const key = keyOf[field];
253
- const text = keys[key];
389
+ const text = own(keys, key);
254
390
  if (text === void 0) continue;
255
391
  const decoded = codecs[field].decode(text);
256
392
  if (Result.isFailure(decoded)) issues.push({
257
393
  key,
258
394
  message: decoded.failure
259
395
  });
260
- else value[field] = decoded.success;
396
+ else put(value, field, decoded.success);
261
397
  }
262
398
  return {
263
399
  value,
@@ -281,7 +417,7 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
281
417
  const out = {};
282
418
  for (const field of names) {
283
419
  if (textOf(field) !== initialText[field] || !Object.hasOwn(decoded, field)) continue;
284
- if (encodeField(field, decoded[field]) !== initialText[field]) out[field] = decoded[field];
420
+ if (encodeField(field, decoded[field]) !== initialText[field]) put(out, field, decoded[field]);
285
421
  }
286
422
  return out;
287
423
  };
@@ -299,7 +435,7 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
299
435
  ...patch
300
436
  };
301
437
  const set = encodeSlice(slice);
302
- const remove = owned.filter((key) => !(key in set));
438
+ const remove = owned.filter((key) => !Object.hasOwn(set, key));
303
439
  return applyToHref(base ?? currentHref() ?? "/", {
304
440
  set,
305
441
  remove
@@ -338,7 +474,7 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
338
474
  onSome: (key) => Effect.gen(function* () {
339
475
  const at = yield* key;
340
476
  const session = sessions.get(at) ?? sessionOf(at, (yield* store.read) ?? {});
341
- const text = (field) => encoded[keyOf[field]] ?? initialText[field];
477
+ const text = (field) => own(encoded, keyOf[field]) ?? initialText[field];
342
478
  yield* Effect.callback((resume) => {
343
479
  const check = () => {
344
480
  if (!Option.match(session.pending, {
@@ -365,8 +501,8 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
365
501
  };
366
502
  const sync = (encoded) => Effect.gen(function* () {
367
503
  const current = (yield* store.read) ?? {};
368
- const remove = owned.filter((key) => !(key in encoded) && key in current);
369
- const changed = owned.filter((key) => key in encoded && current[key] !== encoded[key]);
504
+ const remove = owned.filter((key) => !Object.hasOwn(encoded, key) && Object.hasOwn(current, key));
505
+ const changed = owned.filter((key) => Object.hasOwn(encoded, key) && current[key] !== encoded[key]);
370
506
  if (remove.length === 0 && changed.length === 0) return;
371
507
  const intent = changed.some((key) => history[fieldOf[key]] === "push") ? "push" : "replace";
372
508
  yield* store.write({
@@ -398,6 +534,8 @@ const make = (app, kind, store, config, throttle, sessionKey) => {
398
534
  keysOfUrl
399
535
  };
400
536
  };
537
+ /** The store keys a mirror's config names, before `make` builds it: a store that holds them needs them first. */
538
+ const ownedKeys = (config) => Object.keys(projectionOf(config.fields).schema.fields).map((field) => config.keys?.[field]?.key ?? field);
401
539
  const brandEntries = (entries) => Subscription.make()(() => entries);
402
540
  const Mirror = {
403
541
  /** Mirror's Message cases, to spread into the application's union. */
@@ -473,18 +611,45 @@ const Mirror = {
473
611
  * `onUrlChange` and on cold load.
474
612
  */
475
613
  url: (app, config) => {
476
- const owned = Object.keys(projectionOf(config.fields).schema.fields).map((field) => config.keys?.[field]?.key ?? field);
477
- const { mirror, keysOfUrl } = make(app, "url", MirrorStore.url(owned, config.location ?? "search"), config, config.throttle ?? "50 millis", Option.none());
478
- const reduce = (model, url) => mirror.fromKeys(model, keysOfUrl(url));
614
+ const owned = ownedKeys(config);
615
+ const awaited = [];
616
+ let seen = Option.none();
617
+ const textOf = (url) => {
618
+ const keys = keysOfUrl(url);
619
+ return JSON.stringify(owned.map((key) => own(keys, key) ?? null));
620
+ };
621
+ const { mirror, keysOfUrl } = make(app, "url", urlStoreReporting(owned, config.location ?? "search", (href) => {
622
+ const text = textOf(href);
623
+ seen = Option.some(text);
624
+ if (awaited.push(text) > MAX_AWAITED) awaited.shift();
625
+ }), config, config.throttle ?? "50 millis", Option.none());
626
+ const read = (model, url) => {
627
+ seen = Option.some(textOf(url));
628
+ return mirror.fromKeys(model, keysOfUrl(url));
629
+ };
630
+ const reduce = (model, url) => {
631
+ awaited.length = 0;
632
+ return read(model, url);
633
+ };
634
+ const urlChanged = (model, url) => {
635
+ const text = textOf(url);
636
+ const echo = awaited.indexOf(text);
637
+ if (echo >= 0) {
638
+ awaited.splice(0, echo + 1);
639
+ return model;
640
+ }
641
+ return Option.contains(seen, text) ? model : read(model, url);
642
+ };
479
643
  return {
480
644
  ...mirror,
481
645
  kind: "url",
482
646
  reduce,
647
+ urlChanged,
483
648
  wiring: (tag) => ({
484
649
  key: `mirror:${mirror.name}`,
485
650
  handles: [tag],
486
651
  shared: [tag],
487
- route: (model, message) => message._tag === tag ? Option.some({ model: reduce(model, message.url) }) : Option.none(),
652
+ route: (model, message) => message._tag === tag ? Option.some({ model: urlChanged(model, message.url) }) : Option.none(),
488
653
  onUrl: reduce,
489
654
  subscriptions: brandEntries(mirror.subscriptions),
490
655
  contract: mirror.contract
@@ -495,8 +660,9 @@ const Mirror = {
495
660
  * URL mirrors plugged into `Runtime.makeApplication`: spread the result into
496
661
  * its config. `init` reads the starting URL into the Model the application's
497
662
  * `init` returns; `update` reads a `urlChanged` Message's URL into the Model
498
- * before the application's `update` sees it, so a route handler finds the
499
- * slices already read. `routing` is the application's own, passed through.
663
+ * (each mirror's `urlChanged`, so an echo changes nothing) before the
664
+ * application's `update` sees it, so a route handler finds the slices
665
+ * already read. `routing` is the application's own, passed through.
500
666
  *
501
667
  * @example
502
668
  * ```ts
@@ -517,6 +683,7 @@ const Mirror = {
517
683
  */
518
684
  routing: (config) => {
519
685
  const read = (model, url) => config.mirrors.reduce((next, mirror) => mirror.reduce(next, url), model);
686
+ const changed = (model, url) => config.mirrors.reduce((next, mirror) => mirror.urlChanged(next, url), model);
520
687
  const isUrlChanged = (message) => message._tag === config.urlChanged;
521
688
  return {
522
689
  init: (...args) => {
@@ -526,7 +693,7 @@ const Mirror = {
526
693
  model: read(started.model, args[args.length - 1])
527
694
  };
528
695
  },
529
- update: (model, message) => config.update(isUrlChanged(message) ? read(model, message.url) : model, message),
696
+ update: (model, message) => config.update(isUrlChanged(message) ? changed(model, message.url) : model, message),
530
697
  routing: config.routing
531
698
  };
532
699
  },
@@ -562,10 +729,32 @@ const Mirror = {
562
729
  })
563
730
  };
564
731
  },
732
+ /**
733
+ * A slice kept in one cookie named `name`, its keys form-encoded in the
734
+ * value: written from the browser when it changes, read by the server
735
+ * (`keysOf` the request's `Cookie` header, then `bootstrap`) so the first
736
+ * render holds it, and set by a server's answer with `setCookie`. A browser
737
+ * writes it, so it is never `HttpOnly`: keep nothing secret in it.
738
+ */
739
+ cookie: (app, config) => {
740
+ const spec = cookieSpec(config.name, ownedKeys(config), config.attributes ?? {}, config.maxBytes ?? 4096);
741
+ const { mirror } = make(app, "cookie", cookieStore(spec), config, config.throttle ?? 0, Option.none());
742
+ return {
743
+ ...mirror,
744
+ kind: "cookie",
745
+ keysOf: (header) => header === null ? {} : keysOfCookie(spec, header),
746
+ setCookie: (model, request) => Result.getSuccess(setCookieOf(spec, mirror.encode(model), request.url.startsWith("https:"))),
747
+ wiring: () => ({
748
+ key: `mirror:${mirror.name}`,
749
+ handles: [],
750
+ subscriptions: brandEntries(mirror.subscriptions),
751
+ contract: mirror.contract
752
+ })
753
+ };
754
+ },
565
755
  /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`, bootstrapped with `bootstrap`. */
566
756
  make: (app, store, config) => make(app, "memory", store, config, config.throttle ?? 0, Option.some(Effect.succeed(store))).mirror
567
757
  };
568
- //#endregion
569
758
  export { Mirror, MirrorStore, applyToHref, mirrorMessageCases };
570
759
 
571
760
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-mirror` — a Model slice kept in the URL or a key-value store.\n *\n * The Model is the only truth. A mirror names a slice of it (a writable\n * projection over field refs) and keeps an external keyed string store in\n * step with it: the slice is written to the store whenever it changes, and\n * read back into the Model on navigation or cold load. The URL query string\n * and Effect's `KeyValueStore` are the two stores; a mirror is not an owner,\n * and it is last-write-wins with no log, which is what separates it from\n * `foldkit-sync`. See `docs/design/MIRROR.md`.\n */\nimport { Duration, Effect, Option, Result, Schema, Stream } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { mapMessage, type Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Navigation from 'foldkit/navigation'\nimport type { RoutingConfig } from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport type { Url } from 'foldkit/url'\nimport {\n Projection,\n type Contract,\n type FieldRef,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\n\n// ---------------------------------------------------------------------------\n// Stores\n// ---------------------------------------------------------------------------\n\n/** The keys a mirror holds in a store, as the store holds them: strings. */\nexport type Encoded = Readonly<Record<string, string>>\n\n/** The read entry's dependencies: the encoded slice, as a Struct so Foldkit can compare it. */\nexport interface MirrorDependencies {\n readonly keys: Encoded\n}\n\n/** One write to a store: the keys to set, the keys to drop, and how the URL should record it. */\nexport interface MirrorWrite {\n readonly set: Encoded\n readonly remove: ReadonlyArray<string>\n /** `push` adds a history entry; `replace` does not. A store without history ignores it. */\n readonly intent: 'push' | 'replace'\n}\n\n/**\n * A keyed string store a mirror writes to and reads from. Errors are the\n * store's to absorb: a mirror is disposable state, and a failed write must\n * not fail the application.\n */\nexport interface MirrorStore<R = never> {\n readonly read: Effect.Effect<Encoded | undefined, never, R>\n readonly write: (write: MirrorWrite) => Effect.Effect<void, never, R>\n}\n\n/** `MirrorStore.url`: where in the URL the keys live. */\nexport type UrlLocation = 'search' | 'hash'\n\n/** Splits a same-origin href into its three parts; `search` and `hash` keep their leading `?`/`#`. */\nconst splitHref = (href: string): { pathname: string; search: string; hash: string } => {\n const hashAt = href.indexOf('#')\n const hash = hashAt < 0 ? '' : href.slice(hashAt)\n const rest = hashAt < 0 ? href : href.slice(0, hashAt)\n const searchAt = rest.indexOf('?')\n return {\n pathname: searchAt < 0 ? rest : rest.slice(0, searchAt),\n search: searchAt < 0 ? '' : rest.slice(searchAt),\n hash,\n }\n}\n\n/** The keys a query string holds among `owned`, in URL order. */\nconst readParams = (query: string, owned: ReadonlyArray<string>): Encoded => {\n const params = new URLSearchParams(\n query.startsWith('?') || query.startsWith('#') ? query.slice(1) : query,\n )\n const out: Record<string, string> = {}\n for (const key of owned) {\n const value = params.get(key)\n if (value !== null) out[key] = value\n }\n return out\n}\n\n/** `href` with the mirror's keys set and dropped in its location; every other key, the path, and the other part stay. */\nexport const applyToHref = (\n href: string,\n write: Pick<MirrorWrite, 'set' | 'remove'>,\n location: UrlLocation = 'search',\n): string => {\n const parts = splitHref(href)\n const current = location === 'search' ? parts.search : parts.hash\n const params = new URLSearchParams(current.slice(1))\n for (const key of write.remove) params.delete(key)\n for (const [key, value] of Object.entries(write.set)) params.set(key, value)\n const query = params.toString()\n const next = query === '' ? '' : `${location === 'search' ? '?' : '#'}${query}`\n return location === 'search'\n ? `${parts.pathname}${next}${parts.hash}`\n : `${parts.pathname}${parts.search}${next}`\n}\n\nconst currentHref = (): string | undefined => {\n const loc = (globalThis as { location?: Location }).location\n return loc === undefined ? undefined : `${loc.pathname}${loc.search}${loc.hash}`\n}\n\nconst urlStore = (owned: ReadonlyArray<string>, location: UrlLocation): MirrorStore => ({\n read: Effect.sync(() => {\n const href = currentHref()\n if (href === undefined) return undefined\n const parts = splitHref(href)\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }),\n write: write =>\n Effect.suspend(() => {\n // Outside a browser (SSR, a test without a DOM) there is no URL to write.\n const href = currentHref()\n if (href === undefined) return Effect.void\n const next = applyToHref(href, write, location)\n if (next === href) return Effect.void\n return write.intent === 'push' ? Navigation.pushUrl(next) : Navigation.replaceUrl(next)\n }),\n})\n\nconst KV_VERSION = 1\n\nconst KvDocument = Schema.Struct({\n version: Schema.Number,\n scope: Schema.optional(Schema.String),\n keys: Schema.Record(Schema.String, Schema.String),\n})\n\nconst kvStore = (options: {\n readonly key: string\n readonly scope?: string | undefined\n}): MirrorStore<KeyValueStore.KeyValueStore> => {\n const decode = Schema.decodeUnknownResult(Schema.fromJsonString(KvDocument))\n const encode = Schema.encodeSync(Schema.fromJsonString(KvDocument))\n return {\n read: Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const raw = yield* Effect.result(kv.get(options.key))\n if (Result.isFailure(raw)) {\n yield* Effect.logWarning(`Mirror: could not read \"${options.key}\"`, raw.failure)\n return undefined\n }\n if (raw.success === undefined) return undefined\n const document = decode(raw.success)\n // Another version, another scope, or malformed: disposable, so drop it and start clean.\n if (\n Result.isFailure(document) ||\n document.success.version !== KV_VERSION ||\n document.success.scope !== options.scope\n ) {\n yield* Effect.result(kv.remove(options.key))\n return undefined\n }\n return document.success.keys\n }),\n write: write =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const text = encode({\n version: KV_VERSION,\n ...(options.scope === undefined ? {} : { scope: options.scope }),\n keys: write.set,\n })\n const outcome = yield* Effect.result(\n Object.keys(write.set).length === 0 ? kv.remove(options.key) : kv.set(options.key, text),\n )\n if (Result.isFailure(outcome)) {\n yield* Effect.logWarning(`Mirror: could not write \"${options.key}\"`, outcome.failure)\n }\n }),\n }\n}\n\n/** An in-memory store that records its writes, for tests and for a mirror with no host. */\nexport interface MemoryStore extends MirrorStore {\n /** What the store holds now. */\n readonly current: () => Encoded | undefined\n /** Every write, in order. */\n readonly writes: ReadonlyArray<MirrorWrite>\n}\n\nconst memoryStore = (initial?: Encoded): MemoryStore => {\n let held: Encoded | undefined = initial\n const writes: MirrorWrite[] = []\n return {\n read: Effect.sync(() => held),\n write: write =>\n Effect.sync(() => {\n writes.push(write)\n const next: Record<string, string> = { ...(held ?? {}) }\n for (const key of write.remove) delete next[key]\n Object.assign(next, write.set)\n held = next\n }),\n current: () => held,\n writes,\n }\n}\n\nexport const MirrorStore = {\n /** The URL's query string (or hash), through `foldkit/navigation`. `owned` are the keys the mirror may touch. */\n url: urlStore,\n /** One JSON document under `key` in Effect's `KeyValueStore`, scoped and versioned. */\n kv: kvStore,\n memory: memoryStore,\n}\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\n/** Mirror's Message cases, for `defineMessageUnion({ ...Mirror.messages, … })`. */\nexport const mirrorMessageCases = {\n /** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */\n MirrorRestored: { name: Schema.String, keys: Schema.Record(Schema.String, Schema.String) },\n} satisfies Record<string, Schema.Struct.Fields>\n\nexport interface MirrorRestored {\n readonly _tag: 'MirrorRestored'\n readonly name: string\n readonly keys: Encoded\n}\n\nexport type MirrorMessage = MirrorRestored\n\n// ---------------------------------------------------------------------------\n// Key codecs\n// ---------------------------------------------------------------------------\n\n/** A key's text form and back; the decode names what is wrong when it fails. */\ninterface KeyCodec {\n readonly decode: (text: string) => Result.Result<unknown, string>\n readonly encode: (value: unknown) => string\n}\n\nconst failure = (message: string): Result.Result<never, string> => Result.fail(message)\n\n/**\n * A key's codec, from an override or derived from the field: the field's\n * encoded form of the initial value says whether the key is text, a number,\n * a boolean, or JSON, and the field schema validates whatever was parsed.\n */\nconst codecFor = (\n field: Schema.Codec<unknown, unknown, never, never>,\n initial: unknown,\n override: Schema.Codec<unknown, string, never, never> | undefined,\n): KeyCodec => {\n if (override !== undefined) {\n const decode = Schema.decodeUnknownResult(override)\n const encode = Schema.encodeSync(override)\n return {\n decode: text => Result.mapError(decode(text), error => error.message),\n encode: value => encode(value),\n }\n }\n const encodeField = Schema.encodeSync(field)\n const decodeField = Schema.decodeUnknownResult(field)\n const shape = typeof encodeField(initial)\n const validate = (candidate: unknown) =>\n Result.mapError(decodeField(candidate), error => error.message)\n return {\n decode: text => {\n switch (shape) {\n case 'string':\n return validate(text)\n case 'number': {\n const value = text.trim() === '' ? Number.NaN : Number(text)\n return Number.isNaN(value) ? failure(`\"${text}\" is not a number`) : validate(value)\n }\n case 'boolean':\n return text === 'true' || text === 'false'\n ? validate(text === 'true')\n : failure(`\"${text}\" is not \"true\" or \"false\"`)\n default: {\n try {\n return validate(JSON.parse(text))\n } catch {\n return failure(`\"${text}\" is not JSON`)\n }\n }\n }\n },\n encode: value => {\n const encoded = encodeField(value)\n return shape === 'string' || shape === 'number' || shape === 'boolean'\n ? String(encoded)\n : JSON.stringify(encoded)\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mirrors\n// ---------------------------------------------------------------------------\n\n/** The value type of a field schema. */\ntype TypeOf<S> = S extends { readonly Type: infer T } ? T : never\n\n/**\n * The slice a mirror keeps: field refs straight from `App.model`, or a\n * writable projection over them (`Projection.pick`, `Projection.compose`),\n * the same object `foldkit-sync` replicates.\n */\nexport type Slice = WritableProjection<any, any> | readonly FieldRef<any, any, string>[]\n\n/** The Struct fields of a slice. */\nexport type SliceFields<S extends Slice> =\n S extends WritableProjection<any, infer Fields>\n ? Fields\n : S extends readonly FieldRef<any, any, string>[]\n ? { readonly [R in S[number] as R['key']]: R['Schema'] }\n : never\n\n/** The Model a slice is of. */\nexport type SliceRoot<S extends Slice> =\n S extends WritableProjection<infer Root, any>\n ? Root\n : S extends readonly FieldRef<infer Root, any, string>[]\n ? Root\n : never\n\n/** The value a slice reads. */\nexport type SliceValue<S extends Slice> = Schema.Struct.Type<SliceFields<S>>\n\nconst projectionOf = <S extends Slice>(\n slice: S,\n): WritableProjection<SliceRoot<S>, SliceFields<S>> =>\n (Array.isArray(slice)\n ? Projection.pick(...(slice as readonly FieldRef<any, any, string>[]))\n : slice) as WritableProjection<SliceRoot<S>, SliceFields<S>>\n\n/** How one field is kept: its store key, its history intent, whether its default is written, and its text codec. */\nexport interface KeyOptions<Value> {\n /** The store key; default the field name. */\n readonly key?: string | undefined\n /** Whether a change of this key adds a history entry; default `push`. Only the URL has history. */\n readonly history?: 'push' | 'replace' | undefined\n /** Write the key even when the value is the initial one; default false, so a default is elided. */\n readonly keep?: boolean | undefined\n /** The text codec; default derived from the field schema. */\n readonly codec?: Schema.Codec<Value, string, never, never> | undefined\n}\n\nexport interface MirrorConfig<S extends Slice, Name extends string = string> {\n /** Names the mirror in its contract and its Messages; default from the kind and keys. */\n readonly name?: Name | undefined\n /** The slice: field refs (`[App.model.filter, App.model.q]`) or a writable projection over them. */\n readonly fields: S\n readonly keys?:\n | { readonly [K in keyof SliceFields<S>]?: KeyOptions<TypeOf<SliceFields<S>[K]>> }\n | undefined\n /** The Model's initial value, when the application was built without one; defaults are read from it. */\n readonly initial?: SliceRoot<S> | undefined\n /**\n * How long a changed slice waits before it is written; a newer change\n * supersedes a pending write. Browsers rate-limit history writes, so the\n * URL waits 50 ms by default; a store waits 250 ms.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface UrlMirrorConfig<\n S extends Slice,\n Name extends string = string,\n> extends MirrorConfig<S, Name> {\n /** Where in the URL the keys live; default the query string. */\n readonly location?: UrlLocation | undefined\n}\n\nexport interface KvMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<\n S,\n Name\n> {\n /** The store key the mirror's document lives under; also the mirror's name unless one is given. */\n readonly key: Name\n /** A user, a tenant: a document of another scope is discarded rather than restored. */\n readonly scope?: string | undefined\n}\n\n/** One key that failed to decode; the field keeps its initial value. */\nexport interface DecodeIssue {\n readonly key: string\n readonly message: string\n}\n\nexport interface Decoded<Value> {\n /** The fields the store named and decoded. */\n readonly value: Partial<Value>\n readonly issues: ReadonlyArray<DecodeIssue>\n}\n\n/**\n * A synchronous pre-init step: `Bootstrap` / Flags into the initial Model.\n * Pure: no Commands, no Messages, no Effects. It runs inside `init(flags, url)`\n * before the first render, when the store's keys are already in hand (Flags the\n * server embedded, a synchronous read, a test fixture). `Wiring.init` is the\n * other lifecycle: startup Commands after the Model exists, such as the\n * key-value mirror's `restore`, whose answer arrives later through `update`.\n * Compose steps with `Mirror.bootstrap`; a step that changes nothing returns\n * the Model it was given. Deliberately not part of `Wiring`, so the two\n * lifecycles cannot be confused.\n */\nexport type Bootstrap<AppModel> = (model: AppModel) => AppModel\n\n/**\n * A Model slice kept in a store. `Value` is the slice's value type; the keys,\n * codecs, and intents are values on the mirror, not type parameters.\n * `Mirror.url` and `Mirror.kv` add the `reduce` their store calls for.\n */\nexport interface Mirror<\n AppModel,\n Value extends Record<string, unknown>,\n R = never,\n Name extends string = string,\n> {\n readonly kind: 'url' | 'kv' | 'memory'\n readonly name: Name\n /** Store key per field. */\n readonly keys: Readonly<Record<keyof Value & string, string>>\n /** For `Module`: observes the slice, owns nothing. */\n readonly contract: Contract\n /** The store's keys for a Model, defaults elided unless a key is `keep`. */\n readonly encode: (model: AppModel) => Encoded\n /** The fields a store's keys name; a key that fails to decode is an issue, not a value. */\n readonly decode: (keys: Encoded) => Decoded<Value>\n /**\n * The Model with a store's keys as the whole slice: a key the store lacks,\n * or one that fails to decode, is the initial value.\n */\n readonly fromKeys: (model: AppModel, keys: Encoded) => AppModel\n /**\n * The Model with a store's keys applied to the fields it still holds at\n * their initial value, so a change made before the store answered is kept.\n */\n readonly restoreKeys: (model: AppModel, keys: Encoded) => AppModel\n /**\n * A pre-init step applying pre-read keys before the first render:\n * `restoreKeys`, so a store step composed after a URL step (a `reduce` of\n * the starting URL) keeps the URL's values. Takes the store's keys as the\n * store holds them (`Encoded`), which is what Flags carry when the server\n * embedded the store's document. A URL mirror inherits this too; its URL\n * step is `(model) => reduce(model, url)`.\n */\n readonly bootstrap: (keys: Encoded) => Bootstrap<AppModel>\n /** A link: the keys of `model` with `patch` applied, on `base` (default the current URL, else `/`). */\n readonly href: (model: AppModel, patch?: Partial<Value>, base?: string) => string\n /**\n * A Command that reads the store and yields `MirrorRestored` for this\n * mirror. Until the Model holds what it answered, writes wait.\n */\n readonly restore: Command<MirrorMessage, never, R>\n /** One Subscription entry, `<name>.mirror`: writes the store when the encoded slice changes. */\n readonly subscriptions: {\n readonly [K in `${Name}.mirror`]: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>\n }\n}\n\n/** A slice kept in the URL. */\nexport interface UrlMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, never, Name> {\n readonly kind: 'url'\n /** The Model with the URL's keys (a Foldkit `Url` or an href) as the whole slice: `fromKeys`. */\n readonly reduce: (model: AppModel, url: Url | string) => AppModel\n /**\n * How this mirror joins an assembly: it routes the application's URL Message\n * (a variant with a `url` field, tagged `tag`) into `reduce`, reads the URL at\n * startup, and brings its Subscriptions and contract. Several URL mirrors share\n * the URL Message.\n */\n readonly wiring: <const Tag extends string>(tag: Tag) => UrlMirrorWiring<AppModel, Tag>\n}\n\n/** The Message a URL mirror routes: the application's URL variant. */\nexport type UrlChangedMessage<Tag extends string> = {\n readonly _tag: Tag\n readonly url: Url\n}\n\nexport type UrlMirrorWiring<AppModel, Tag extends string> = Wiring<\n AppModel,\n UrlChangedMessage<Tag>\n> & {\n readonly onUrl: (model: AppModel, url: Url) => AppModel\n}\n\n/** `Mirror.routing`'s config: the application's own `init`, `update` and routing, and the URL mirrors to read. */\nexport interface MirrorRoutingConfig<\n AppModel,\n Message extends { readonly _tag: string },\n Tag extends Message['_tag'],\n Args extends ReadonlyArray<unknown>,\n InitReturn extends { readonly model: AppModel },\n UpdateReturn extends { readonly model: AppModel },\n> {\n readonly mirrors: readonly [UrlMirror<AppModel, any, any>, ...UrlMirror<AppModel, any, any>[]]\n /** The tag of the Message `routing.onUrlChange` makes. */\n readonly urlChanged: Tag\n /** `(url) => …`, or `(flags, url) => …` for an application with flags. */\n readonly init: (...args: [...Args, Url]) => InitReturn\n readonly update: (model: AppModel, message: Message) => UpdateReturn\n readonly routing: {\n readonly onUrlRequest: (request: Navigation.UrlRequest) => Message\n readonly onUrlChange: (url: Url) => Extract<Message, UrlChangedMessage<Tag>>\n }\n}\n\n/** `init`, `update` and `routing` for `Runtime.makeApplication`, with the mirrors reading every URL. */\nexport interface MirrorRouting<\n AppModel,\n Message,\n Args extends ReadonlyArray<unknown>,\n InitReturn,\n UpdateReturn,\n> {\n readonly init: (...args: [...Args, Url]) => InitReturn\n readonly update: (model: AppModel, message: Message) => UpdateReturn\n readonly routing: RoutingConfig<Message>\n}\n\nexport type KvMirrorWiring<AppModel> = Wiring<\n AppModel,\n MirrorRestored,\n KeyValueStore.KeyValueStore\n> & {\n readonly init: Update.Step<AppModel, MirrorRestored, KeyValueStore.KeyValueStore>\n}\n\n/**\n * A key-value mirror folded under one of the application's own Message\n * variants, from `Mirror.fold`. Calling it reduces the mirror's\n * `MirrorRestored` into the Model; `restore` and `init` yield the wrapper\n * Message instead of `MirrorRestored`, with the lift recorded so Story and\n * Scene can resolve `restore` by the answer the store gives.\n */\nexport interface MirrorFold<AppModel, ParentMessage> {\n (model: AppModel, message: MirrorRestored): Update.Return<AppModel, ParentMessage>\n /** `restore`, lifted: yields the wrapper Message for this mirror's answer. */\n readonly restore: Command<ParentMessage, never, KeyValueStore.KeyValueStore>\n /** A Step for `init`: the Model unchanged, and `restore` to run. */\n readonly init: Update.Step<AppModel, ParentMessage, KeyValueStore.KeyValueStore>\n}\n\n/** A slice kept in Effect's `KeyValueStore`. */\nexport interface KvMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, KeyValueStore.KeyValueStore, Name> {\n readonly kind: 'kv'\n /** The Model with a `MirrorRestored` for this mirror applied: `restoreKeys`; another mirror's is ignored. */\n readonly reduce: (model: AppModel, message: MirrorRestored) => AppModel\n /**\n * How this mirror joins an assembly: it routes its own `MirrorRestored` into\n * `reduce`, runs `restore` at startup, and brings its Subscriptions and\n * contract. Other key-value mirrors share the `MirrorRestored` tag.\n */\n readonly wiring: () => KvMirrorWiring<AppModel>\n}\n\n/** One runtime's store, for a mirror's writes: the keys its Model has yet to take in, and the writes waiting on that. */\ninterface Session {\n pending: Option.Option<Encoded>\n readonly waiting: Set<() => void>\n}\n\nconst nameOf = (\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n keys: ReadonlyArray<string>,\n given: string | undefined,\n): string => given ?? `${kind}(${keys.join(',')})`\n\n// A URL key belongs to one mirror per application; the same mirror may be\n// declared again (a module re-evaluated, a test), another may not take it.\nconst claimed = new WeakMap<object, Map<string, string>>()\n\nconst claim = (\n owner: object,\n location: UrlLocation,\n keys: ReadonlyArray<string>,\n name: string,\n): void => {\n let byKey = claimed.get(owner)\n if (byKey === undefined) {\n byKey = new Map()\n claimed.set(owner, byKey)\n }\n for (const key of keys) {\n const at = `${location}:${key}`\n const holder = byKey.get(at)\n if (holder !== undefined && holder !== name) {\n throw new Error(\n `Mirror.url: key \"${key}\" in the ${location} is already mirrored by \"${holder}\"; \"${name}\" cannot mirror it too`,\n )\n }\n byKey.set(at, name)\n }\n}\n\n/** An application a mirror is declared over: its identity token, and its initial Model when it has one. */\nexport interface MirrorApp<AppModel> {\n readonly owner: object\n readonly initial?: AppModel | undefined\n}\n\n/** A Foldkit `Url` carries `search` and `hash` without their `?` and `#`; an href has them. */\nconst withPrefix = (prefix: '?' | '#', part: string): string =>\n part === '' || part.startsWith(prefix) ? part : `${prefix}${part}`\n\nconst hrefOf = (url: Url | string): string =>\n typeof url === 'string'\n ? url\n : `${url.pathname}${withPrefix('?', url.search._tag === 'Some' ? url.search.value : '')}${withPrefix(\n '#',\n url.hash._tag === 'Some' ? url.hash.value : '',\n )}`\n\nconst make = <S extends Slice, R, Name extends string>(\n app: MirrorApp<SliceRoot<S>>,\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name> & { readonly location?: UrlLocation | undefined },\n throttle: Duration.Input,\n // Names one runtime's store, so writes wait for that runtime's restore; none\n // for the URL, which startup reads before the first write.\n sessionKey: Option.Option<Effect.Effect<object, never, R>>,\n) => {\n type AppModel = SliceRoot<S>\n type Value = SliceValue<S>\n const fields = projectionOf(config.fields)\n const names = Object.keys(fields.schema.fields)\n const options = (config.keys ?? {}) as Readonly<Record<string, KeyOptions<unknown> | undefined>>\n const initial = config.initial ?? app.initial\n if (initial === undefined) {\n throw new Error(\n `Mirror.${kind}: defaults are read from the initial Model, so build the application with \\`initial\\` or pass \\`initial\\` in the config`,\n )\n }\n const initialSlice = fields.get(initial) as Readonly<Record<string, unknown>>\n const location = config.location ?? 'search'\n\n const keyOf: Record<string, string> = {}\n const fieldOf: Record<string, string> = {}\n const codecs: Record<string, KeyCodec> = {}\n const history: Record<string, 'push' | 'replace'> = {}\n const keep = new Set<string>()\n const initialText: Record<string, string> = {}\n for (const field of names) {\n const option = options[field]\n const key = option?.key ?? field\n if (fieldOf[key] !== undefined) {\n throw new Error(\n `Mirror: fields \"${fieldOf[key]}\" and \"${field}\" both use the key \"${key}\"; give one another key`,\n )\n }\n keyOf[field] = key\n fieldOf[key] = field\n codecs[field] = codecFor(\n fields.schema.fields[field] as Schema.Codec<unknown, unknown, never, never>,\n initialSlice[field],\n option?.codec as Schema.Codec<unknown, string, never, never> | undefined,\n )\n history[field] = option?.history ?? 'push'\n if (option?.keep === true) keep.add(field)\n initialText[field] = codecs[field].encode(initialSlice[field])\n }\n const owned = names.map(field => keyOf[field]!)\n const name = nameOf(kind, owned, config.name) as Name\n if (kind === 'url') claim(app.owner, location, owned, name)\n\n // A field's text, remembered by the value's identity: the write entry\n // encodes the slice on every Model change and `href` on every render, and a\n // structured field (JSON) costs a stringify each time. Primitives are cheap\n // and have no identity to remember.\n const texts: Record<string, WeakMap<object, string>> = {}\n for (const field of names) texts[field] = new WeakMap()\n const encodeField = (field: string, value: unknown): string => {\n if (typeof value !== 'object' || value === null) return codecs[field]!.encode(value)\n const known = texts[field]!.get(value)\n if (known !== undefined) return known\n const text = codecs[field]!.encode(value)\n texts[field]!.set(value, text)\n return text\n }\n\n // Two slices a store cannot tell apart are the same slice: a Model keeps\n // its identity when a store reads back what it holds, as it does after its\n // own write to the URL, so Foldkit does not render it again.\n const sameSlice = (\n current: Readonly<Record<string, unknown>>,\n next: Readonly<Record<string, unknown>>,\n ): boolean =>\n names.every(\n field =>\n Object.is(current[field], next[field]) ||\n encodeField(field, current[field]) === encodeField(field, next[field]),\n )\n\n const encodeSlice = (slice: Readonly<Record<string, unknown>>): Encoded => {\n const out: Record<string, string> = {}\n for (const field of names) {\n const text = encodeField(field, slice[field])\n if (!keep.has(field) && text === initialText[field]) continue\n out[keyOf[field]!] = text\n }\n return out\n }\n const encode = (model: AppModel): Encoded =>\n encodeSlice(fields.get(model) as Readonly<Record<string, unknown>>)\n\n const decode = (keys: Encoded): Decoded<Value> => {\n const value: Record<string, unknown> = {}\n const issues: DecodeIssue[] = []\n for (const field of names) {\n const key = keyOf[field]!\n const text = keys[key]\n if (text === undefined) continue\n const decoded = codecs[field]!.decode(text)\n if (Result.isFailure(decoded)) issues.push({ key, message: decoded.failure })\n else value[field] = decoded.success\n }\n return { value: value as Partial<Value>, issues }\n }\n\n const keysOfUrl = (source: Url | string): Encoded => {\n const parts = splitHref(hrefOf(source))\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }\n\n const fromKeys = (model: AppModel, keys: Encoded): AppModel => {\n const decoded = decode(keys).value as Readonly<Record<string, unknown>>\n const next = { ...initialSlice, ...decoded }\n return sameSlice(fields.get(model) as Readonly<Record<string, unknown>>, next)\n ? model\n : fields.set(model, next as never)\n }\n\n // The fields a restore of `keys` would change in a slice whose text per\n // field is `textOf`: those still at their initial text, since a change the\n // user made before the store answered wins over the store.\n const restorable = (\n textOf: (field: string) => string,\n keys: Encoded,\n ): Readonly<Record<string, unknown>> => {\n const decoded = decode(keys).value as Readonly<Record<string, unknown>>\n const out: Record<string, unknown> = {}\n for (const field of names) {\n if (textOf(field) !== initialText[field] || !Object.hasOwn(decoded, field)) continue\n if (encodeField(field, decoded[field]) !== initialText[field]) out[field] = decoded[field]\n }\n return out\n }\n\n const restoreKeys = (model: AppModel, keys: Encoded): AppModel => {\n const current = fields.get(model) as Readonly<Record<string, unknown>>\n const restored = restorable(field => encodeField(field, current[field]), keys)\n return Object.keys(restored).length === 0\n ? model\n : fields.set(model, { ...current, ...restored } as never)\n }\n\n const href = (model: AppModel, patch?: Partial<Value>, base?: string): string => {\n const slice = { ...(fields.get(model) as Readonly<Record<string, unknown>>), ...patch }\n const set = encodeSlice(slice)\n const remove = owned.filter(key => !(key in set))\n return applyToHref(base ?? currentHref() ?? '/', { set, remove }, location)\n }\n\n const contract: Contract = {\n kind: 'mirror',\n name,\n owner: app.owner,\n owns: [],\n observes: fields.dependencies,\n messages: kind === 'kv' ? ['MirrorRestored'] : [],\n metadata: [],\n }\n\n // Until the Model has taken in what the store held, a write would replace\n // the stored slice with the initial one: the write Subscription starts with\n // the initial Model, before `restore` answers. So per session (one runtime's\n // store) a write waits until its slice is one a restore of the store's keys\n // leaves unchanged. The keys are the latest restore's answer, or, before any\n // answer, what the store holds at the first write, so a mirror nobody\n // restores (a test, a Model kept across a hot reload) writes once its slice\n // agrees with the store.\n const sessions = new WeakMap<object, Session>()\n const sessionOf = (key: object, keys: Encoded): Session => {\n const known = sessions.get(key)\n if (known !== undefined) return known\n const made: Session = { pending: Option.some(keys), waiting: new Set() }\n sessions.set(key, made)\n return made\n }\n const answered = (keys: Encoded): Effect.Effect<void, never, R> =>\n Option.match(sessionKey, {\n onNone: () => Effect.void,\n onSome: key =>\n Effect.map(key, key => {\n const session = sessionOf(key, keys)\n session.pending = Option.some(keys)\n for (const wake of [...session.waiting]) wake()\n }),\n })\n const settled = (encoded: Encoded): Effect.Effect<void, never, R> =>\n Option.match(sessionKey, {\n onNone: () => Effect.void,\n onSome: key =>\n Effect.gen(function* () {\n const at = yield* key\n const session = sessions.get(at) ?? sessionOf(at, (yield* store.read) ?? {})\n const text = (field: string) => encoded[keyOf[field]!] ?? initialText[field]!\n yield* Effect.callback<void>(resume => {\n const check = () => {\n const absorbed = Option.match(session.pending, {\n onNone: () => true,\n onSome: keys => Object.keys(restorable(text, keys)).length === 0,\n })\n if (!absorbed) return\n session.pending = Option.none()\n session.waiting.delete(check)\n resume(Effect.void)\n }\n session.waiting.add(check)\n check()\n // A newer slice interrupts this one before the Model took the keys in.\n return Effect.sync(() => session.waiting.delete(check))\n })\n }),\n })\n\n const restore: Command<MirrorMessage, never, R> = {\n name: `Mirror.restore(${name})`,\n effect: store.read.pipe(\n Effect.map(keys => keys ?? {}),\n Effect.tap(answered),\n Effect.map((keys): MirrorMessage => ({ _tag: 'MirrorRestored', name, keys })),\n ),\n }\n\n // Writes only what changed, and pushes only for a changed key that pushes:\n // a removal (a key back at its default) never adds a history entry.\n const sync = (encoded: Encoded): Effect.Effect<void, never, R> =>\n Effect.gen(function* () {\n const current = (yield* store.read) ?? {}\n const remove = owned.filter(key => !(key in encoded) && key in current)\n const changed = owned.filter(key => key in encoded && current[key] !== encoded[key])\n if (remove.length === 0 && changed.length === 0) return\n const intent = changed.some(key => history[fieldOf[key]!] === 'push') ? 'push' : 'replace'\n yield* store.write({ set: encoded, remove, intent })\n })\n\n const entry: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R> = {\n dependenciesSchema: Schema.Struct({ keys: Schema.Record(Schema.String, Schema.String) }),\n modelToDependencies: model => ({ keys: encode(model) }),\n dependenciesToStream: ({ keys }) =>\n Stream.fromEffect(\n settled(keys).pipe(Effect.andThen(sync(keys)), Effect.delay(throttle)),\n ).pipe(Stream.drain),\n }\n\n const mirror: Mirror<AppModel, Value, R, Name> = {\n kind,\n name,\n keys: keyOf as Readonly<Record<keyof Value & string, string>>,\n contract,\n encode,\n decode,\n fromKeys,\n restoreKeys,\n bootstrap: keys => model => restoreKeys(model, keys),\n href,\n restore,\n subscriptions: { [`${name}.mirror`]: entry } as Mirror<\n AppModel,\n Value,\n R,\n Name\n >['subscriptions'],\n }\n return { mirror, keysOfUrl }\n}\n\n// A mirror's Subscription entries are unbranded so an application can spread them\n// into its own `Subscription.make`; wiring hands them over as a branded record.\nconst brandEntries = <AppModel, R>(\n entries: Readonly<Record<string, EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>>>,\n): Subscription.Subscriptions<AppModel, never, R> =>\n Subscription.make<AppModel, never, R>()(() => entries)\n\nexport const Mirror = {\n /** Mirror's Message cases, to spread into the application's union. */\n messages: mirrorMessageCases,\n\n /**\n * Mirror's Messages as one Schema, for a wrapper variant in the\n * application's union: `GotPrefsMessage: { message: Mirror.Message }`. With\n * a wrapper, `update` matches the application's union exhaustively and\n * `Mirror.fold` reduces what arrives inside it.\n */\n Message: defineMessageUnion(mirrorMessageCases),\n\n /**\n * A key-value mirror under one wrapper variant of the application's union,\n * the same shape Foldkit gives a Submodel: `toParentMessage` wraps the\n * mirror's `MirrorRestored`, the fold reduces it, and `fold.init` runs the\n * lifted `restore` at startup. One wrapper per mirror: two mirrors that\n * share a variant would each have to reduce the other's answer.\n *\n * @example\n * ```ts\n * const Message = defineMessageUnion({ GotPrefsMessage: { message: Mirror.Message } })\n * const foldPrefs = Mirror.fold(Prefs, message => Message.GotPrefsMessage({ message }))\n *\n * const init = (): Return => foldPrefs.init(initial)\n * const update = (model: Model, message: Message): Return =>\n * Message.match(message, {\n * GotPrefsMessage: ({ message }) => foldPrefs(model, message),\n * })\n * ```\n */\n fold: <AppModel, Value extends Record<string, unknown>, Name extends string, ParentMessage>(\n mirror: KvMirror<AppModel, Value, Name>,\n toParentMessage: (message: MirrorRestored) => ParentMessage,\n ): MirrorFold<AppModel, ParentMessage> => {\n const restore = mapMessage(mirror.restore, toParentMessage)\n const fold = (model: AppModel, message: MirrorRestored) => ({\n model: mirror.reduce(model, message),\n })\n return Object.assign(fold, {\n restore,\n init: (model: AppModel) => ({ model, commands: [restore] }),\n })\n },\n\n /** Narrows the application's union to Mirror's cases, by tag. */\n reduces: <M extends { readonly _tag: string }>(\n message: M,\n ): message is Extract<M, { readonly _tag: 'MirrorRestored' }> =>\n Object.hasOwn(mirrorMessageCases, message._tag),\n\n /**\n * Folds pre-init steps into the initial Model, in list order: stores first,\n * the URL last. Either order keeps URL > store > initial (a store bootstrap\n * only fills fields still at their initial value, while a URL `reduce` sets\n * its whole slice), but listing the URL last states the precedence. Among\n * store bootstraps sharing a field, the first one wins.\n *\n * Use this when the keys are already in hand at boot: Flags the server\n * embedded, a synchronous read, a test fixture. When the store can only be\n * read asynchronously, use the `restore` Command (`wiring.init`,\n * `fold.init`) instead: bootstrapping what the store holds needs the keys,\n * and `restore` is how they arrive.\n *\n * @example\n * ```ts\n * const init = (flags: { prefs: Encoded }, url: Url): Return => ({\n * model: Mirror.bootstrap(\n * initial,\n * Prefs.bootstrap(flags.prefs),\n * model => Filters.reduce(model, url),\n * ),\n * })\n * ```\n */\n bootstrap: <AppModel>(model: AppModel, ...steps: ReadonlyArray<Bootstrap<AppModel>>): AppModel =>\n steps.reduce((next, step) => step(next), model),\n\n /**\n * A slice kept in the URL: `Projection.pick(App.model.filter, App.model.q)`\n * as `?filter=…&q=…`, defaults elided, written when it changes (one history\n * write per Model change) and read back with `reduce(model, url)` on\n * `onUrlChange` and on cold load.\n */\n url: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: UrlMirrorConfig<S, Name>,\n ): UrlMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const owned = Object.keys(projectionOf(config.fields).schema.fields).map(\n field =>\n (config.keys as Readonly<Record<string, KeyOptions<unknown> | undefined>> | undefined)?.[\n field\n ]?.key ?? field,\n )\n const { mirror, keysOfUrl } = make(\n app,\n 'url',\n MirrorStore.url(owned, config.location ?? 'search'),\n config,\n config.throttle ?? '50 millis',\n Option.none(),\n )\n const reduce = (model: SliceRoot<S>, url: Url | string) =>\n mirror.fromKeys(model, keysOfUrl(url))\n return {\n ...mirror,\n kind: 'url',\n reduce,\n wiring: tag => ({\n key: `mirror:${mirror.name}`,\n handles: [tag],\n shared: [tag],\n route: (model, message) =>\n // tag-check: open — `Tag` is the application's URL variant, generic here\n message._tag === tag ? Option.some({ model: reduce(model, message.url) }) : Option.none(),\n onUrl: reduce,\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\n }\n },\n\n /**\n * URL mirrors plugged into `Runtime.makeApplication`: spread the result into\n * its config. `init` reads the starting URL into the Model the application's\n * `init` returns; `update` reads a `urlChanged` Message's URL into the Model\n * before the application's `update` sees it, so a route handler finds the\n * slices already read. `routing` is the application's own, passed through.\n *\n * @example\n * ```ts\n * Runtime.makeApplication({\n * Model, view, subscriptions, container,\n * ...Mirror.routing({\n * mirrors: [Filters],\n * urlChanged: 'ChangedUrl',\n * init,\n * update,\n * routing: {\n * onUrlRequest: request => Message.ClickedLink({ request }),\n * onUrlChange: url => Message.ChangedUrl({ url }),\n * },\n * }),\n * })\n * ```\n */\n routing: <\n AppModel,\n Message extends { readonly _tag: string },\n const Tag extends Message['_tag'],\n Args extends ReadonlyArray<unknown>,\n InitReturn extends { readonly model: AppModel },\n UpdateReturn extends { readonly model: AppModel },\n >(\n config: MirrorRoutingConfig<AppModel, Message, Tag, Args, InitReturn, UpdateReturn>,\n ): MirrorRouting<AppModel, Message, Args, InitReturn, UpdateReturn> => {\n const read = (model: AppModel, url: Url): AppModel =>\n config.mirrors.reduce((next, mirror) => mirror.reduce(next, url), model)\n const isUrlChanged = (message: Message): message is Message & UrlChangedMessage<Tag> =>\n // tag-check: open — `Tag` is the application's URL variant, generic here\n message._tag === config.urlChanged\n return {\n init: (...args) => {\n const started = config.init(...args)\n return { ...started, model: read(started.model, args[args.length - 1] as Url) }\n },\n update: (model, message) =>\n config.update(isUrlChanged(message) ? read(model, message.url) : model, message),\n routing: config.routing,\n }\n },\n\n /**\n * A slice kept in Effect's `KeyValueStore` under `key`, as one scoped,\n * versioned JSON document: written when it changes, read back by the\n * `restore` Command whose `MirrorRestored` `reduce` applies.\n */\n kv: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: KvMirrorConfig<S, Name>,\n ): KvMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const { mirror } = make(\n app,\n 'kv',\n MirrorStore.kv({\n key: config.key,\n ...(config.scope === undefined ? {} : { scope: config.scope }),\n }),\n { ...config, name: config.name ?? config.key },\n config.throttle ?? '250 millis',\n // One runtime builds one KeyValueStore: the session is that service.\n Option.some(Effect.service(KeyValueStore.KeyValueStore)),\n )\n const reduce = (model: SliceRoot<S>, message: MirrorRestored) =>\n message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model\n return {\n ...mirror,\n kind: 'kv',\n reduce,\n wiring: () => ({\n key: `mirror:${mirror.name}`,\n handles: ['MirrorRestored'],\n shared: ['MirrorRestored'],\n // Another mirror's restore is not this one's: `None` lets the next mirror take it.\n route: (model, message) =>\n message._tag === 'MirrorRestored' && message.name === mirror.name\n ? Option.some({ model: reduce(model, message) })\n : Option.none(),\n init: model => ({ model, commands: [mirror.restore] }),\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\n }\n },\n\n /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`, bootstrapped with `bootstrap`. */\n make: <S extends Slice, R, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name>,\n ): Mirror<SliceRoot<S>, SliceValue<S>, R, Name> =>\n make(app, 'memory', store, config, config.throttle ?? 0, Option.some(Effect.succeed(store)))\n .mirror,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+DA,MAAM,aAAa,SAAqE;CACtF,MAAM,SAAS,KAAK,QAAQ,GAAG;CAC/B,MAAM,OAAO,SAAS,IAAI,KAAK,KAAK,MAAM,MAAM;CAChD,MAAM,OAAO,SAAS,IAAI,OAAO,KAAK,MAAM,GAAG,MAAM;CACrD,MAAM,WAAW,KAAK,QAAQ,GAAG;CACjC,OAAO;EACL,UAAU,WAAW,IAAI,OAAO,KAAK,MAAM,GAAG,QAAQ;EACtD,QAAQ,WAAW,IAAI,KAAK,KAAK,MAAM,QAAQ;EAC/C;CACF;AACF;;AAGA,MAAM,cAAc,OAAe,UAA0C;CAC3E,MAAM,SAAS,IAAI,gBACjB,MAAM,WAAW,GAAG,KAAK,MAAM,WAAW,GAAG,IAAI,MAAM,MAAM,CAAC,IAAI,KACpE;CACA,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,QAAQ,OAAO,IAAI,GAAG;EAC5B,IAAI,UAAU,MAAM,IAAI,OAAO;CACjC;CACA,OAAO;AACT;;AAGA,MAAa,eACX,MACA,OACA,WAAwB,aACb;CACX,MAAM,QAAQ,UAAU,IAAI;CAC5B,MAAM,UAAU,aAAa,WAAW,MAAM,SAAS,MAAM;CAC7D,MAAM,SAAS,IAAI,gBAAgB,QAAQ,MAAM,CAAC,CAAC;CACnD,KAAK,MAAM,OAAO,MAAM,QAAQ,OAAO,OAAO,GAAG;CACjD,KAAK,MAAM,CAAC,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ts","../src/record.ts","../src/index.ts"],"sourcesContent":["/**\n * What a key-value mirror absorbs: a store that fails a read or a write, and\n * a document under its key that is not a mirror's; and what a cookie mirror\n * refuses to write. The mirror is disposable\n * state, so it goes on as if the store held nothing; each is reported through\n * `Diagnostics.report`, so the log says why a slice did not survive.\n */\nimport type { KeyValueStore } from 'effect/persistence'\nimport type { Diagnostic } from 'foldkit-surface'\n\nconst source = 'foldkit-mirror'\n\n/** The store failed to read the mirror's document: the slice restored nothing. */\nexport interface StoreUnread extends Diagnostic {\n readonly _tag: 'StoreUnread'\n readonly key: string\n readonly error: KeyValueStore.KeyValueStoreError\n}\n\n/** The store failed to write (or remove) the mirror's document: the slice was not kept. */\nexport interface StoreUnwritten extends Diagnostic {\n readonly _tag: 'StoreUnwritten'\n readonly key: string\n readonly error: KeyValueStore.KeyValueStoreError\n}\n\n/**\n * The document under the mirror's key is not one a mirror writes (not JSON,\n * or not its shape), so it was discarded: something else writes that key.\n * Another version or scope is a mirror's own and is discarded with no report.\n */\nexport interface StoreMalformed extends Diagnostic {\n readonly _tag: 'StoreMalformed'\n readonly key: string\n /** Why it did not decode. */\n readonly reason: string\n}\n\n/**\n * A cookie mirror's slice encoded past its `maxBytes`, so it was not written:\n * the browser would drop it, and the cookie keeps what it held.\n */\nexport interface CookieTooLarge extends Diagnostic {\n readonly _tag: 'CookieTooLarge'\n readonly name: string\n readonly bytes: number\n readonly maxBytes: number\n}\n\n/** Every diagnostic a mirror reports. */\nexport type MirrorDiagnostic = StoreUnread | StoreUnwritten | StoreMalformed | CookieTooLarge\n\nexport const cookieTooLarge = (name: string, bytes: number, maxBytes: number): CookieTooLarge => ({\n _tag: 'CookieTooLarge',\n source,\n level: 'warning',\n message: `the cookie \"${name}\" would be ${bytes} bytes, past its ${maxBytes}, so it was not written and keeps what it held.`,\n name,\n bytes,\n maxBytes,\n})\n\nexport const storeUnread = (key: string, error: KeyValueStore.KeyValueStoreError): StoreUnread => ({\n _tag: 'StoreUnread',\n source,\n level: 'warning',\n message: `could not read \"${key}\" (${error.message}), so the mirror restored nothing.`,\n key,\n error,\n})\n\nexport const storeUnwritten = (\n key: string,\n error: KeyValueStore.KeyValueStoreError,\n): StoreUnwritten => ({\n _tag: 'StoreUnwritten',\n source,\n level: 'warning',\n message: `could not write \"${key}\" (${error.message}), so the store does not hold the slice.`,\n key,\n error,\n})\n\nexport const storeMalformed = (key: string, reason: string): StoreMalformed => ({\n _tag: 'StoreMalformed',\n source,\n level: 'warning',\n message: `\"${key}\" held a document no mirror writes (${reason}); it was discarded. Give the mirror a key nothing else writes.`,\n key,\n reason,\n})\n","/**\n * Records keyed by a field's name or a store's key, which an application or a\n * URL chooses. Read as `record[key]`, `constructor` or `toString` finds\n * `Object.prototype`'s; written as `record[key] = value`, `__proto__` sets the\n * prototype and adds no key.\n */\n\n/** The value `record` holds under `key` itself, never one it inherits. */\nexport const own = <A>(record: Readonly<Record<string, A>>, key: string): A | undefined =>\n Object.hasOwn(record, key) ? record[key] : undefined\n\n/** Sets `key` on `record` as a key of its own, whatever the name. */\nexport const put = <A>(record: Record<string, A>, key: string, value: A): void => {\n Object.defineProperty(record, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n}\n\n/** An empty record with no prototype, for a table only this package reads. */\nexport const table = <A>(): Record<string, A> => Object.create(null)\n","/**\n * `foldkit-mirror` — a Model slice kept in the URL or a key-value store.\n *\n * The Model is the only truth. A mirror names a slice of it (a writable\n * projection over field refs) and keeps an external keyed string store in\n * step with it: the slice is written to the store whenever it changes, and\n * read back into the Model on navigation or cold load. The URL query string\n * and Effect's `KeyValueStore` are the two stores; a mirror is not an owner,\n * and it is last-write-wins with no log, which is what separates it from\n * `foldkit-sync`. See `docs/design/MIRROR.md`.\n */\nimport { Duration, Effect, Option, Result, Schema, Stream } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { mapMessage, type Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Navigation from 'foldkit/navigation'\nimport type { RoutingConfig } from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport type { Url } from 'foldkit/url'\nimport {\n Diagnostics,\n Projection,\n type Contract,\n type FieldRef,\n RefTypeId,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport { cookieTooLarge, storeMalformed, storeUnread, storeUnwritten } from './diagnostics.js'\nimport { own, put, table } from './record.js'\n\nexport type {\n CookieTooLarge,\n MirrorDiagnostic,\n StoreMalformed,\n StoreUnread,\n StoreUnwritten,\n} from './diagnostics.js'\n\n// ---------------------------------------------------------------------------\n// Stores\n// ---------------------------------------------------------------------------\n\n/** The keys a mirror holds in a store, as the store holds them: strings. */\nexport type Encoded = Readonly<Record<string, string>>\n\n/** The read entry's dependencies: the encoded slice, as a Struct so Foldkit can compare it. */\nexport interface MirrorDependencies {\n readonly keys: Encoded\n}\n\n/** One write to a store: the keys to set, the keys to drop, and how the URL should record it. */\nexport interface MirrorWrite {\n readonly set: Encoded\n readonly remove: ReadonlyArray<string>\n /** `push` adds a history entry; `replace` does not. A store without history ignores it. */\n readonly intent: 'push' | 'replace'\n}\n\n/**\n * A keyed string store a mirror writes to and reads from. Errors are the\n * store's to absorb: a mirror is disposable state, and a failed write must\n * not fail the application.\n */\nexport interface MirrorStore<R = never> {\n readonly read: Effect.Effect<Encoded | undefined, never, R>\n readonly write: (write: MirrorWrite) => Effect.Effect<void, never, R>\n}\n\n/** `MirrorStore.url`: where in the URL the keys live. */\nexport type UrlLocation = 'search' | 'hash'\n\n/** Splits a same-origin href into its three parts; `search` and `hash` keep their leading `?`/`#`. */\nconst splitHref = (href: string): { pathname: string; search: string; hash: string } => {\n const hashAt = href.indexOf('#')\n const hash = hashAt < 0 ? '' : href.slice(hashAt)\n const rest = hashAt < 0 ? href : href.slice(0, hashAt)\n const searchAt = rest.indexOf('?')\n return {\n pathname: searchAt < 0 ? rest : rest.slice(0, searchAt),\n search: searchAt < 0 ? '' : rest.slice(searchAt),\n hash,\n }\n}\n\n/** The keys a query string holds among `owned`, in URL order. */\nconst readParams = (query: string, owned: ReadonlyArray<string>): Encoded => {\n const params = new URLSearchParams(\n query.startsWith('?') || query.startsWith('#') ? query.slice(1) : query,\n )\n const out: Record<string, string> = {}\n for (const key of owned) {\n const value = params.get(key)\n if (value !== null) put(out, key, value)\n }\n return out\n}\n\n/** `href` with the mirror's keys set and dropped in its location; every other key, the path, and the other part stay. */\nexport const applyToHref = (\n href: string,\n write: Pick<MirrorWrite, 'set' | 'remove'>,\n location: UrlLocation = 'search',\n): string => {\n const parts = splitHref(href)\n const current = location === 'search' ? parts.search : parts.hash\n const params = new URLSearchParams(current.slice(1))\n for (const key of write.remove) params.delete(key)\n for (const [key, value] of Object.entries(write.set)) params.set(key, value)\n const query = params.toString()\n const next = query === '' ? '' : `${location === 'search' ? '?' : '#'}${query}`\n return location === 'search'\n ? `${parts.pathname}${next}${parts.hash}`\n : `${parts.pathname}${parts.search}${next}`\n}\n\nconst currentHref = (): string | undefined => {\n const loc = (globalThis as { location?: Location }).location\n return loc === undefined ? undefined : `${loc.pathname}${loc.search}${loc.hash}`\n}\n\n// `wrote` hears each href the store writes, before Foldkit answers it with a\n// `UrlChanged`, in the same uninterruptible step.\nconst urlStoreReporting = (\n owned: ReadonlyArray<string>,\n location: UrlLocation,\n wrote: (href: string) => void,\n): MirrorStore => ({\n read: Effect.sync(() => {\n const href = currentHref()\n if (href === undefined) return undefined\n const parts = splitHref(href)\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }),\n write: write =>\n Effect.uninterruptible(\n Effect.suspend(() => {\n // Outside a browser (SSR, a test without a DOM) there is no URL to write.\n const href = currentHref()\n if (href === undefined) return Effect.void\n const next = applyToHref(href, write, location)\n if (next === href) return Effect.void\n wrote(next)\n return write.intent === 'push' ? Navigation.pushUrl(next) : Navigation.replaceUrl(next)\n }),\n ),\n})\n\n// Writes a URL mirror awaits the echo of; far more than a burst ever leaves.\nconst MAX_AWAITED = 64\n\nconst urlStore = (owned: ReadonlyArray<string>, location: UrlLocation): MirrorStore =>\n urlStoreReporting(owned, location, () => {})\n\nconst KV_VERSION = 1\n\nconst KvDocument = Schema.Struct({\n version: Schema.Number,\n scope: Schema.optional(Schema.String),\n keys: Schema.Record(Schema.String, Schema.String),\n})\n\nconst kvStore = (options: {\n readonly key: string\n readonly scope?: string | undefined\n}): MirrorStore<KeyValueStore.KeyValueStore> => {\n const decode = Schema.decodeUnknownResult(Schema.fromJsonString(KvDocument))\n const encode = Schema.encodeSync(Schema.fromJsonString(KvDocument))\n return {\n read: Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const raw = yield* Effect.result(kv.get(options.key))\n if (Result.isFailure(raw)) {\n yield* Diagnostics.report(storeUnread(options.key, raw.failure))\n return undefined\n }\n if (raw.success === undefined) return undefined\n const document = decode(raw.success)\n if (Result.isFailure(document))\n yield* Diagnostics.report(storeMalformed(options.key, document.failure.message))\n // Another version, another scope, or malformed: disposable, so drop it and start clean.\n if (\n Result.isFailure(document) ||\n document.success.version !== KV_VERSION ||\n document.success.scope !== options.scope\n ) {\n const removed = yield* Effect.result(kv.remove(options.key))\n if (Result.isFailure(removed))\n yield* Diagnostics.report(storeUnwritten(options.key, removed.failure))\n return undefined\n }\n return document.success.keys\n }),\n write: write =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const text = encode({\n version: KV_VERSION,\n ...(options.scope === undefined ? {} : { scope: options.scope }),\n keys: write.set,\n })\n const outcome = yield* Effect.result(\n Object.keys(write.set).length === 0 ? kv.remove(options.key) : kv.set(options.key, text),\n )\n if (Result.isFailure(outcome))\n yield* Diagnostics.report(storeUnwritten(options.key, outcome.failure))\n }),\n }\n}\n\n/** `Mirror.cookie`'s attributes; each default is what a cookie the browser writes needs. */\nexport interface CookieAttributes {\n /** Default `/`, so every page sends it. */\n readonly path?: string | undefined\n /** Default none: the host that set it, and no other. */\n readonly domain?: string | undefined\n /** Default `Lax`: sent on a navigation and a same-site post, never a cross-site post. */\n readonly sameSite?: 'Strict' | 'Lax' | 'None' | undefined\n /**\n * Default `auto`: `Secure` on an https page, or for an https request on the\n * server. Behind a proxy that terminates TLS the server's request is http,\n * so a cookie it sets has no `Secure`: set `true` in production there.\n */\n readonly secure?: boolean | 'auto' | undefined\n /** How long the browser keeps it; default 365 days. */\n readonly maxAge?: Duration.Input | undefined\n}\n\n/** A cookie mirror's cookie, its attributes checked once, when it is declared. */\ninterface CookieSpec {\n readonly name: string\n readonly owned: ReadonlyArray<string>\n readonly attributes: ReadonlyArray<string>\n readonly secure: boolean | 'auto'\n readonly maxAge: number\n readonly maxBytes: number\n}\n\n// RFC 6265's cookie-name (an RFC 7230 token), and an attribute value: no\n// control, space or `;`, so neither can end the header's field or add another.\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\nconst ATTRIBUTE_VALUE = /^[!-:<-~]+$/\n\nconst cookieSpec = (\n name: string,\n owned: ReadonlyArray<string>,\n attributes: CookieAttributes,\n maxBytes: number,\n): CookieSpec => {\n const refuse = (why: string): never => {\n throw new Error(`Mirror.cookie(\"${name}\"): ${why}`)\n }\n if (!COOKIE_NAME.test(name))\n refuse(\"a cookie name is a token: letters, digits and !#$%&'*+-.^_`|~\")\n const path = attributes.path ?? '/'\n if (!path.startsWith('/') || !ATTRIBUTE_VALUE.test(path))\n refuse(`the path \"${path}\" starts with / and holds no space, control or ;`)\n const domain = Option.fromUndefinedOr(attributes.domain)\n if (Option.exists(domain, domain => !/^[0-9A-Za-z.-]+$/.test(domain)))\n refuse('a domain holds letters, digits, dots and hyphens only')\n const sameSite = attributes.sameSite ?? 'Lax'\n const secure = attributes.secure ?? 'auto'\n // A browser refuses a `SameSite=None` cookie without `Secure`.\n if (sameSite === 'None' && secure !== true) refuse('SameSite=None needs secure: true')\n const maxAge = Math.floor(\n Duration.toSeconds(Duration.fromInputUnsafe(attributes.maxAge ?? '365 days')),\n )\n if (!(maxAge > 0)) refuse('maxAge is longer than a second')\n if (!(maxBytes > 0)) refuse('maxBytes is a positive number')\n return {\n name,\n owned,\n attributes: [\n `Path=${path}`,\n ...Option.match(domain, { onNone: () => [], onSome: domain => [`Domain=${domain}`] }),\n `SameSite=${sameSite}`,\n ],\n secure,\n maxAge,\n maxBytes,\n }\n}\n\n/** The mirror's keys a `Cookie` header (or `document.cookie`) holds: none for a cookie past `maxBytes`. */\nconst keysOfCookie = (spec: CookieSpec, header: string): Encoded => {\n for (const part of header.split(';')) {\n const at = part.indexOf('=')\n if (at < 0 || part.slice(0, at).trim() !== spec.name) continue\n const value = part.slice(at + 1).trim()\n // The first of two cookies by one name is the one of the longer path, as browsers send them.\n return spec.name.length + 1 + value.length > spec.maxBytes ? {} : readParams(value, spec.owned)\n }\n return {}\n}\n\n/**\n * The `Set-Cookie` value keeping `keys`, or clearing the cookie when there are\n * none; the length of its `name=value` when that is past `maxBytes`. The keys\n * are form-encoded, which leaves only characters a cookie's value allows.\n */\nconst setCookieOf = (\n spec: CookieSpec,\n keys: Encoded,\n https: boolean,\n): Result.Result<string, number> => {\n const value = new URLSearchParams(Object.entries(keys)).toString()\n const pair = `${spec.name}=${value}`\n if (pair.length > spec.maxBytes) return Result.fail(pair.length)\n const secure = spec.secure === 'auto' ? https : spec.secure\n return Result.succeed(\n [\n pair,\n ...spec.attributes,\n `Max-Age=${value === '' ? 0 : spec.maxAge}`,\n ...(secure ? ['Secure'] : []),\n ].join('; '),\n )\n}\n\nconst documentOf = (): Option.Option<Document> =>\n Option.fromUndefinedOr((globalThis as { document?: Document }).document)\n\n// Outside a browser (a server, a test without a DOM) there is no cookie to read or write.\nconst cookieStore = (spec: CookieSpec): MirrorStore => ({\n read: Effect.sync(() =>\n Option.match(documentOf(), {\n onNone: () => undefined,\n onSome: document => keysOfCookie(spec, document.cookie),\n }),\n ),\n write: write =>\n Option.match(documentOf(), {\n onNone: () => Effect.void,\n onSome: document =>\n Result.match(\n setCookieOf(\n spec,\n write.set,\n (globalThis as { location?: Location }).location?.protocol === 'https:',\n ),\n {\n onFailure: bytes => Diagnostics.report(cookieTooLarge(spec.name, bytes, spec.maxBytes)),\n onSuccess: line =>\n Effect.sync(() => {\n document.cookie = line\n }),\n },\n ),\n }),\n})\n\n/** An in-memory store that records its writes, for tests and for a mirror with no host. */\nexport interface MemoryStore extends MirrorStore {\n /** What the store holds now. */\n readonly current: () => Encoded | undefined\n /** Every write, in order. */\n readonly writes: ReadonlyArray<MirrorWrite>\n}\n\nconst memoryStore = (initial?: Encoded): MemoryStore => {\n let held: Encoded | undefined = initial\n const writes: MirrorWrite[] = []\n return {\n read: Effect.sync(() => held),\n write: write =>\n Effect.sync(() => {\n writes.push(write)\n const next: Record<string, string> = { ...(held ?? {}) }\n for (const key of write.remove) delete next[key]\n for (const [key, value] of Object.entries(write.set)) put(next, key, value)\n held = next\n }),\n current: () => held,\n writes,\n }\n}\n\nexport const MirrorStore = {\n /** The URL's query string (or hash), through `foldkit/navigation`. `owned` are the keys the mirror may touch. */\n url: urlStore,\n /** One JSON document under `key` in Effect's `KeyValueStore`, scoped and versioned. */\n kv: kvStore,\n memory: memoryStore,\n}\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\n/** Mirror's Message cases, for `defineMessageUnion({ ...Mirror.messages, … })`. */\nexport const mirrorMessageCases = {\n /** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */\n MirrorRestored: { name: Schema.String, keys: Schema.Record(Schema.String, Schema.String) },\n} satisfies Record<string, Schema.Struct.Fields>\n\nexport interface MirrorRestored {\n readonly _tag: 'MirrorRestored'\n readonly name: string\n readonly keys: Encoded\n}\n\nexport type MirrorMessage = MirrorRestored\n\n// ---------------------------------------------------------------------------\n// Key codecs\n// ---------------------------------------------------------------------------\n\n/** A key's text form and back; the decode names what is wrong when it fails. */\ninterface KeyCodec {\n readonly decode: (text: string) => Result.Result<unknown, string>\n readonly encode: (value: unknown) => string\n}\n\nconst failure = (message: string): Result.Result<never, string> => Result.fail(message)\n\n/**\n * A key's codec, from an override or derived from the field: the field's\n * encoded form of the initial value says whether the key is text, a number,\n * a boolean, or JSON, and the field schema validates whatever was parsed.\n */\nconst codecFor = (\n field: Schema.Codec<unknown, unknown, never, never>,\n initial: unknown,\n override: Schema.Codec<unknown, string, never, never> | undefined,\n): KeyCodec => {\n if (override !== undefined) {\n const decode = Schema.decodeUnknownResult(override)\n const encode = Schema.encodeSync(override)\n return {\n decode: text => Result.mapError(decode(text), error => error.message),\n encode: value => encode(value),\n }\n }\n const encodeField = Schema.encodeSync(field)\n const decodeField = Schema.decodeUnknownResult(field)\n const shape = typeof encodeField(initial)\n const validate = (candidate: unknown) =>\n Result.mapError(decodeField(candidate), error => error.message)\n return {\n decode: text => {\n switch (shape) {\n case 'string':\n return validate(text)\n case 'number': {\n const value = text.trim() === '' ? Number.NaN : Number(text)\n return Number.isNaN(value) ? failure(`\"${text}\" is not a number`) : validate(value)\n }\n case 'boolean':\n return text === 'true' || text === 'false'\n ? validate(text === 'true')\n : failure(`\"${text}\" is not \"true\" or \"false\"`)\n default: {\n try {\n return validate(JSON.parse(text))\n } catch {\n return failure(`\"${text}\" is not JSON`)\n }\n }\n }\n },\n encode: value => {\n const encoded = encodeField(value)\n return shape === 'string' || shape === 'number' || shape === 'boolean'\n ? String(encoded)\n : JSON.stringify(encoded)\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mirrors\n// ---------------------------------------------------------------------------\n\n/** The value type of a field schema. */\ntype TypeOf<S> = S extends { readonly Type: infer T } ? T : never\n\n/**\n * The slice a mirror keeps: field refs straight from `App.model`, or a\n * writable projection over them (`Projection.pick`, `Projection.compose`),\n * the same object `foldkit-sync` replicates.\n */\nexport type Slice = WritableProjection<any, any> | readonly FieldRef<any, any, string>[]\n\n/** The Struct fields of a slice. */\nexport type SliceFields<S extends Slice> =\n S extends WritableProjection<any, infer Fields>\n ? Fields\n : S extends readonly FieldRef<any, any, string>[]\n ? {\n readonly [R in S[number] as R[typeof RefTypeId]['key']]: R[typeof RefTypeId]['Schema']\n }\n : never\n\n/** The Model a slice is of. */\nexport type SliceRoot<S extends Slice> =\n S extends WritableProjection<infer Root, any>\n ? Root\n : S extends readonly FieldRef<infer Root, any, string>[]\n ? Root\n : never\n\n/** The value a slice reads. */\nexport type SliceValue<S extends Slice> = Schema.Struct.Type<SliceFields<S>>\n\nconst projectionOf = <S extends Slice>(\n slice: S,\n): WritableProjection<SliceRoot<S>, SliceFields<S>> =>\n (Array.isArray(slice)\n ? Projection.pick(...(slice as readonly FieldRef<any, any, string>[]))\n : slice) as WritableProjection<SliceRoot<S>, SliceFields<S>>\n\n/** How one field is kept: its store key, its history intent, whether its default is written, and its text codec. */\nexport interface KeyOptions<Value> {\n /** The store key; default the field name. */\n readonly key?: string | undefined\n /** Whether a change of this key adds a history entry; default `push`. Only the URL has history. */\n readonly history?: 'push' | 'replace' | undefined\n /** Write the key even when the value is the initial one; default false, so a default is elided. */\n readonly keep?: boolean | undefined\n /** The text codec; default derived from the field schema. */\n readonly codec?: Schema.Codec<Value, string, never, never> | undefined\n}\n\nexport interface MirrorConfig<S extends Slice, Name extends string = string> {\n /** Names the mirror in its contract and its Messages; default from the kind and keys. */\n readonly name?: Name | undefined\n /** The slice: field refs (`[App.model.filter, App.model.q]`) or a writable projection over them. */\n readonly fields: S\n readonly keys?:\n | { readonly [K in keyof SliceFields<S>]?: KeyOptions<TypeOf<SliceFields<S>[K]>> }\n | undefined\n /** The Model's initial value, when the application was built without one; defaults are read from it. */\n readonly initial?: SliceRoot<S> | undefined\n /**\n * How long a changed slice waits before it is written; a newer change\n * supersedes a pending write. Browsers rate-limit history writes, so the\n * URL waits 50 ms by default; a store waits 250 ms.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface UrlMirrorConfig<\n S extends Slice,\n Name extends string = string,\n> extends MirrorConfig<S, Name> {\n /** Where in the URL the keys live; default the query string. */\n readonly location?: UrlLocation | undefined\n}\n\nexport interface KvMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<\n S,\n Name\n> {\n /** The store key the mirror's document lives under; also the mirror's name unless one is given. */\n readonly key: Name\n /** A user, a tenant: a document of another scope is discarded rather than restored. */\n readonly scope?: string | undefined\n}\n\nexport interface CookieMirrorConfig<\n S extends Slice,\n Name extends string = string,\n> extends MirrorConfig<S, Name> {\n /** The cookie's name, a token (`cart`); also the mirror's name. */\n readonly name: Name\n readonly attributes?: CookieAttributes | undefined\n /**\n * The most the cookie's `name=value` may hold, in bytes; default 4096, what\n * every browser keeps. A slice encoded past it is not written, and a cookie\n * past it is read as holding nothing.\n */\n readonly maxBytes?: number | undefined\n}\n\n/** One key that failed to decode; the field keeps its initial value. */\nexport interface DecodeIssue {\n readonly key: string\n readonly message: string\n}\n\nexport interface Decoded<Value> {\n /** The fields the store named and decoded. */\n readonly value: Partial<Value>\n readonly issues: ReadonlyArray<DecodeIssue>\n}\n\n/**\n * A synchronous pre-init step: `Bootstrap` / Flags into the initial Model.\n * Pure: no Commands, no Messages, no Effects. It runs inside `init(flags, url)`\n * before the first render, when the store's keys are already in hand (Flags the\n * server embedded, a synchronous read, a test fixture). `Wiring.init` is the\n * other lifecycle: startup Commands after the Model exists, such as the\n * key-value mirror's `restore`, whose answer arrives later through `update`.\n * Compose steps with `Mirror.bootstrap`; a step that changes nothing returns\n * the Model it was given. Deliberately not part of `Wiring`, so the two\n * lifecycles cannot be confused.\n */\nexport type Bootstrap<AppModel> = (model: AppModel) => AppModel\n\n/**\n * A Model slice kept in a store. `Value` is the slice's value type; the keys,\n * codecs, and intents are values on the mirror, not type parameters.\n * `Mirror.url` and `Mirror.kv` add the `reduce` their store calls for.\n */\nexport interface Mirror<\n AppModel,\n Value extends Record<string, unknown>,\n R = never,\n Name extends string = string,\n> {\n readonly kind: 'url' | 'kv' | 'cookie' | 'memory'\n readonly name: Name\n /** Store key per field. */\n readonly keys: Readonly<Record<keyof Value & string, string>>\n /** For `Module`: observes the slice, owns nothing. */\n readonly contract: Contract\n /** The store's keys for a Model, defaults elided unless a key is `keep`. */\n readonly encode: (model: AppModel) => Encoded\n /** The fields a store's keys name; a key that fails to decode is an issue, not a value. */\n readonly decode: (keys: Encoded) => Decoded<Value>\n /**\n * The Model with a store's keys as the whole slice: a key the store lacks,\n * or one that fails to decode, is the initial value.\n */\n readonly fromKeys: (model: AppModel, keys: Encoded) => AppModel\n /**\n * The Model with a store's keys applied to the fields it still holds at\n * their initial value, so a change made before the store answered is kept.\n */\n readonly restoreKeys: (model: AppModel, keys: Encoded) => AppModel\n /**\n * A pre-init step applying pre-read keys before the first render:\n * `restoreKeys`, so a store step composed after a URL step (a `reduce` of\n * the starting URL) keeps the URL's values. Takes the store's keys as the\n * store holds them (`Encoded`), which is what Flags carry when the server\n * embedded the store's document. A URL mirror inherits this too; its URL\n * step is `(model) => reduce(model, url)`.\n */\n readonly bootstrap: (keys: Encoded) => Bootstrap<AppModel>\n /** A link: the keys of `model` with `patch` applied, on `base` (default the current URL, else `/`). */\n readonly href: (model: AppModel, patch?: Partial<Value>, base?: string) => string\n /**\n * A Command that reads the store and yields `MirrorRestored` for this\n * mirror. Until the Model holds what it answered, writes wait.\n */\n readonly restore: Command<MirrorMessage, never, R>\n /** One Subscription entry, `<name>.mirror`: writes the store when the encoded slice changes. */\n readonly subscriptions: {\n readonly [K in `${Name}.mirror`]: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>\n }\n}\n\n/** A slice kept in the URL. */\nexport interface UrlMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, never, Name> {\n readonly kind: 'url'\n /**\n * The Model with the URL's keys (a Foldkit `Url` or an href) as the whole\n * slice: `fromKeys`. For the starting URL; a later one is `urlChanged`'s.\n */\n readonly reduce: (model: AppModel, url: Url | string) => AppModel\n /**\n * The Model after a `UrlChanged`: `reduce`, unless the URL is the echo of\n * one of this mirror's writes or leaves its keys as it last read or wrote\n * them (a path change, another mirror's write), when the Model is returned\n * as it is. An echo can land after newer edits, and reading it would undo\n * them.\n */\n readonly urlChanged: (model: AppModel, url: Url | string) => AppModel\n /**\n * How this mirror joins an assembly: it routes the application's URL Message\n * (a variant with a `url` field, tagged `tag`) into `urlChanged`, reads the URL at\n * startup, and brings its Subscriptions and contract. Several URL mirrors share\n * the URL Message.\n */\n readonly wiring: <const Tag extends string>(tag: Tag) => UrlMirrorWiring<AppModel, Tag>\n}\n\n/** The Message a URL mirror routes: the application's URL variant. */\nexport type UrlChangedMessage<Tag extends string> = {\n readonly _tag: Tag\n readonly url: Url\n}\n\nexport type UrlMirrorWiring<AppModel, Tag extends string> = Wiring<\n AppModel,\n UrlChangedMessage<Tag>\n> & {\n readonly onUrl: (model: AppModel, url: Url) => AppModel\n}\n\n/** `Mirror.routing`'s config: the application's own `init`, `update` and routing, and the URL mirrors to read. */\nexport interface MirrorRoutingConfig<\n AppModel,\n Message extends { readonly _tag: string },\n Tag extends Message['_tag'],\n Args extends ReadonlyArray<unknown>,\n InitReturn extends { readonly model: AppModel },\n UpdateReturn extends { readonly model: AppModel },\n> {\n readonly mirrors: readonly [UrlMirror<AppModel, any, any>, ...UrlMirror<AppModel, any, any>[]]\n /** The tag of the Message `routing.onUrlChange` makes. */\n readonly urlChanged: Tag\n /** `(url) => …`, or `(flags, url) => …` for an application with flags. */\n readonly init: (...args: [...Args, Url]) => InitReturn\n readonly update: (model: AppModel, message: Message) => UpdateReturn\n readonly routing: {\n readonly onUrlRequest: (request: Navigation.UrlRequest) => Message\n readonly onUrlChange: (url: Url) => Extract<Message, UrlChangedMessage<Tag>>\n }\n}\n\n/** `init`, `update` and `routing` for `Runtime.makeApplication`, with the mirrors reading every URL. */\nexport interface MirrorRouting<\n AppModel,\n Message,\n Args extends ReadonlyArray<unknown>,\n InitReturn,\n UpdateReturn,\n> {\n readonly init: (...args: [...Args, Url]) => InitReturn\n readonly update: (model: AppModel, message: Message) => UpdateReturn\n readonly routing: RoutingConfig<Message>\n}\n\nexport type KvMirrorWiring<AppModel> = Wiring<\n AppModel,\n MirrorRestored,\n KeyValueStore.KeyValueStore\n> & {\n readonly init: Update.Step<AppModel, MirrorRestored, KeyValueStore.KeyValueStore>\n}\n\n/**\n * A key-value mirror folded under one of the application's own Message\n * variants, from `Mirror.fold`. Calling it reduces the mirror's\n * `MirrorRestored` into the Model; `restore` and `init` yield the wrapper\n * Message instead of `MirrorRestored`, with the lift recorded so Story and\n * Scene can resolve `restore` by the answer the store gives.\n */\nexport interface MirrorFold<AppModel, ParentMessage> {\n (model: AppModel, message: MirrorRestored): Update.Return<AppModel, ParentMessage>\n /** `restore`, lifted: yields the wrapper Message for this mirror's answer. */\n readonly restore: Command<ParentMessage, never, KeyValueStore.KeyValueStore>\n /** A Step for `init`: the Model unchanged, and `restore` to run. */\n readonly init: Update.Step<AppModel, ParentMessage, KeyValueStore.KeyValueStore>\n}\n\n/** A slice kept in Effect's `KeyValueStore`. */\nexport interface KvMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, KeyValueStore.KeyValueStore, Name> {\n readonly kind: 'kv'\n /** The Model with a `MirrorRestored` for this mirror applied: `restoreKeys`; another mirror's is ignored. */\n readonly reduce: (model: AppModel, message: MirrorRestored) => AppModel\n /**\n * How this mirror joins an assembly: it routes its own `MirrorRestored` into\n * `reduce`, runs `restore` at startup, and brings its Subscriptions and\n * contract. Other key-value mirrors share the `MirrorRestored` tag.\n */\n readonly wiring: () => KvMirrorWiring<AppModel>\n}\n\n/**\n * A slice kept in one cookie, which the server reads for a render and the\n * browser writes when the slice changes. A cookie is the visitor's to edit:\n * `keysOf` and `decode` check its shape, and what the application trusts\n * (a price, a permission) it checks again.\n */\nexport interface CookieMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, never, Name> {\n readonly kind: 'cookie'\n /**\n * The mirror's keys a `Cookie` header holds (`request.headers.get('cookie')`,\n * or `document.cookie`), for `bootstrap` or `decode`: only the keys it owns,\n * and none from a cookie past `maxBytes`.\n */\n readonly keysOf: (cookieHeader: string | null) => Encoded\n /**\n * The `Set-Cookie` value keeping the slice of `model`, for a server's answer\n * (a form posted without scripts): it clears the cookie when the slice is at\n * its defaults, and `Secure` is `auto`'s for `request.url`. `None` when the\n * slice encodes past `maxBytes`: the browser keeps the cookie it holds.\n */\n readonly setCookie: (model: AppModel, request: { readonly url: string }) => Option.Option<string>\n /**\n * How this mirror joins an assembly: its Subscription, which writes the\n * cookie, and its contract. It reads nothing at startup; `bootstrap` does,\n * from the request's cookie on the server or `document.cookie` in a browser.\n */\n readonly wiring: () => Wiring<AppModel, never>\n}\n\n/** One runtime's store, for a mirror's writes: the keys its Model has yet to take in, and the writes waiting on that. */\ninterface Session {\n pending: Option.Option<Encoded>\n readonly waiting: Set<() => void>\n}\n\nconst nameOf = (\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n keys: ReadonlyArray<string>,\n given: string | undefined,\n): string => given ?? `${kind}(${keys.join(',')})`\n\n// A URL key belongs to one mirror per application; the same mirror may be\n// declared again (a module re-evaluated, a test), another may not take it.\nconst claimed = new WeakMap<object, Map<string, string>>()\n\nconst claim = (\n owner: object,\n location: UrlLocation,\n keys: ReadonlyArray<string>,\n name: string,\n): void => {\n let byKey = claimed.get(owner)\n if (byKey === undefined) {\n byKey = new Map()\n claimed.set(owner, byKey)\n }\n for (const key of keys) {\n const at = `${location}:${key}`\n const holder = byKey.get(at)\n if (holder !== undefined && holder !== name) {\n throw new Error(\n `Mirror.url: key \"${key}\" in the ${location} is already mirrored by \"${holder}\"; \"${name}\" cannot mirror it too`,\n )\n }\n byKey.set(at, name)\n }\n}\n\n/** An application a mirror is declared over: its identity token, and its initial Model when it has one. */\nexport interface MirrorApp<AppModel> {\n readonly owner: object\n readonly initial?: AppModel | undefined\n}\n\n/** A Foldkit `Url` carries `search` and `hash` without their `?` and `#`; an href has them. */\nconst withPrefix = (prefix: '?' | '#', part: string): string =>\n part === '' || part.startsWith(prefix) ? part : `${prefix}${part}`\n\nconst hrefOf = (url: Url | string): string =>\n typeof url === 'string'\n ? url\n : `${url.pathname}${withPrefix('?', url.search._tag === 'Some' ? url.search.value : '')}${withPrefix(\n '#',\n url.hash._tag === 'Some' ? url.hash.value : '',\n )}`\n\nconst make = <S extends Slice, R, Name extends string>(\n app: MirrorApp<SliceRoot<S>>,\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name> & { readonly location?: UrlLocation | undefined },\n throttle: Duration.Input,\n // Names one runtime's store, so writes wait for that runtime's restore; none\n // for the URL, which startup reads before the first write.\n sessionKey: Option.Option<Effect.Effect<object, never, R>>,\n) => {\n type AppModel = SliceRoot<S>\n type Value = SliceValue<S>\n const fields = projectionOf(config.fields)\n const names = Object.keys(fields.schema.fields)\n const options = (config.keys ?? {}) as Readonly<Record<string, KeyOptions<unknown> | undefined>>\n const initial = config.initial ?? app.initial\n if (initial === undefined) {\n throw new Error(\n `Mirror.${kind}: defaults are read from the initial Model, so build the application with \\`initial\\` or pass \\`initial\\` in the config`,\n )\n }\n const initialSlice = fields.get(initial) as Readonly<Record<string, unknown>>\n const location = config.location ?? 'search'\n\n const keyOf = table<string>()\n const fieldOf = table<string>()\n const codecs: Record<string, KeyCodec> = {}\n const history = table<'push' | 'replace'>()\n const keep = new Set<string>()\n const initialText = table<string>()\n for (const field of names) {\n const option = options[field]\n const key = option?.key ?? field\n if (fieldOf[key] !== undefined) {\n throw new Error(\n `Mirror: fields \"${fieldOf[key]}\" and \"${field}\" both use the key \"${key}\"; give one another key`,\n )\n }\n keyOf[field] = key\n fieldOf[key] = field\n codecs[field] = codecFor(\n fields.schema.fields[field] as Schema.Codec<unknown, unknown, never, never>,\n initialSlice[field],\n option?.codec as Schema.Codec<unknown, string, never, never> | undefined,\n )\n history[field] = option?.history ?? 'push'\n if (option?.keep === true) keep.add(field)\n initialText[field] = codecs[field].encode(initialSlice[field])\n }\n const owned = names.map(field => keyOf[field]!)\n const name = nameOf(kind, owned, config.name) as Name\n if (kind === 'url') claim(app.owner, location, owned, name)\n\n // A field's text, remembered by the value's identity: the write entry\n // encodes the slice on every Model change and `href` on every render, and a\n // structured field (JSON) costs a stringify each time. Primitives are cheap\n // and have no identity to remember.\n const texts: Record<string, WeakMap<object, string>> = {}\n for (const field of names) texts[field] = new WeakMap()\n const encodeField = (field: string, value: unknown): string => {\n if (typeof value !== 'object' || value === null) return codecs[field]!.encode(value)\n const known = texts[field]!.get(value)\n if (known !== undefined) return known\n const text = codecs[field]!.encode(value)\n texts[field]!.set(value, text)\n return text\n }\n\n // Two slices a store cannot tell apart are the same slice: a Model keeps\n // its identity when a store reads back what it holds, as it does after its\n // own write to the URL, so Foldkit does not render it again.\n const sameSlice = (\n current: Readonly<Record<string, unknown>>,\n next: Readonly<Record<string, unknown>>,\n ): boolean =>\n names.every(\n field =>\n Object.is(current[field], next[field]) ||\n encodeField(field, current[field]) === encodeField(field, next[field]),\n )\n\n const encodeSlice = (slice: Readonly<Record<string, unknown>>): Encoded => {\n const out: Record<string, string> = {}\n for (const field of names) {\n const text = encodeField(field, slice[field])\n if (!keep.has(field) && text === initialText[field]) continue\n put(out, keyOf[field]!, text)\n }\n return out\n }\n const encode = (model: AppModel): Encoded =>\n encodeSlice(fields.get(model) as Readonly<Record<string, unknown>>)\n\n const decode = (keys: Encoded): Decoded<Value> => {\n const value: Record<string, unknown> = {}\n const issues: DecodeIssue[] = []\n for (const field of names) {\n const key = keyOf[field]!\n const text = own(keys, key)\n if (text === undefined) continue\n const decoded = codecs[field]!.decode(text)\n if (Result.isFailure(decoded)) issues.push({ key, message: decoded.failure })\n else put(value, field, decoded.success)\n }\n return { value: value as Partial<Value>, issues }\n }\n\n const keysOfUrl = (source: Url | string): Encoded => {\n const parts = splitHref(hrefOf(source))\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }\n\n const fromKeys = (model: AppModel, keys: Encoded): AppModel => {\n const decoded = decode(keys).value as Readonly<Record<string, unknown>>\n const next = { ...initialSlice, ...decoded }\n return sameSlice(fields.get(model) as Readonly<Record<string, unknown>>, next)\n ? model\n : fields.set(model, next as never)\n }\n\n // The fields a restore of `keys` would change in a slice whose text per\n // field is `textOf`: those still at their initial text, since a change the\n // user made before the store answered wins over the store.\n const restorable = (\n textOf: (field: string) => string,\n keys: Encoded,\n ): Readonly<Record<string, unknown>> => {\n const decoded = decode(keys).value as Readonly<Record<string, unknown>>\n const out: Record<string, unknown> = {}\n for (const field of names) {\n if (textOf(field) !== initialText[field] || !Object.hasOwn(decoded, field)) continue\n if (encodeField(field, decoded[field]) !== initialText[field]) put(out, field, decoded[field])\n }\n return out\n }\n\n const restoreKeys = (model: AppModel, keys: Encoded): AppModel => {\n const current = fields.get(model) as Readonly<Record<string, unknown>>\n const restored = restorable(field => encodeField(field, current[field]), keys)\n return Object.keys(restored).length === 0\n ? model\n : fields.set(model, { ...current, ...restored } as never)\n }\n\n const href = (model: AppModel, patch?: Partial<Value>, base?: string): string => {\n const slice = { ...(fields.get(model) as Readonly<Record<string, unknown>>), ...patch }\n const set = encodeSlice(slice)\n const remove = owned.filter(key => !Object.hasOwn(set, key))\n return applyToHref(base ?? currentHref() ?? '/', { set, remove }, location)\n }\n\n const contract: Contract = {\n kind: 'mirror',\n name,\n owner: app.owner,\n owns: [],\n observes: fields.dependencies,\n messages: kind === 'kv' ? ['MirrorRestored'] : [],\n metadata: [],\n }\n\n // Until the Model has taken in what the store held, a write would replace\n // the stored slice with the initial one: the write Subscription starts with\n // the initial Model, before `restore` answers. So per session (one runtime's\n // store) a write waits until its slice is one a restore of the store's keys\n // leaves unchanged. The keys are the latest restore's answer, or, before any\n // answer, what the store holds at the first write, so a mirror nobody\n // restores (a test, a Model kept across a hot reload) writes once its slice\n // agrees with the store.\n const sessions = new WeakMap<object, Session>()\n const sessionOf = (key: object, keys: Encoded): Session => {\n const known = sessions.get(key)\n if (known !== undefined) return known\n const made: Session = { pending: Option.some(keys), waiting: new Set() }\n sessions.set(key, made)\n return made\n }\n const answered = (keys: Encoded): Effect.Effect<void, never, R> =>\n Option.match(sessionKey, {\n onNone: () => Effect.void,\n onSome: key =>\n Effect.map(key, key => {\n const session = sessionOf(key, keys)\n session.pending = Option.some(keys)\n for (const wake of [...session.waiting]) wake()\n }),\n })\n const settled = (encoded: Encoded): Effect.Effect<void, never, R> =>\n Option.match(sessionKey, {\n onNone: () => Effect.void,\n onSome: key =>\n Effect.gen(function* () {\n const at = yield* key\n const session = sessions.get(at) ?? sessionOf(at, (yield* store.read) ?? {})\n const text = (field: string) => own(encoded, keyOf[field]!) ?? initialText[field]!\n yield* Effect.callback<void>(resume => {\n const check = () => {\n const absorbed = Option.match(session.pending, {\n onNone: () => true,\n onSome: keys => Object.keys(restorable(text, keys)).length === 0,\n })\n if (!absorbed) return\n session.pending = Option.none()\n session.waiting.delete(check)\n resume(Effect.void)\n }\n session.waiting.add(check)\n check()\n // A newer slice interrupts this one before the Model took the keys in.\n return Effect.sync(() => session.waiting.delete(check))\n })\n }),\n })\n\n const restore: Command<MirrorMessage, never, R> = {\n name: `Mirror.restore(${name})`,\n effect: store.read.pipe(\n Effect.map(keys => keys ?? {}),\n Effect.tap(answered),\n Effect.map((keys): MirrorMessage => ({ _tag: 'MirrorRestored', name, keys })),\n ),\n }\n\n // Writes only what changed, and pushes only for a changed key that pushes:\n // a removal (a key back at its default) never adds a history entry.\n const sync = (encoded: Encoded): Effect.Effect<void, never, R> =>\n Effect.gen(function* () {\n const current = (yield* store.read) ?? {}\n const remove = owned.filter(\n key => !Object.hasOwn(encoded, key) && Object.hasOwn(current, key),\n )\n const changed = owned.filter(\n key => Object.hasOwn(encoded, key) && current[key] !== encoded[key],\n )\n if (remove.length === 0 && changed.length === 0) return\n const intent = changed.some(key => history[fieldOf[key]!] === 'push') ? 'push' : 'replace'\n yield* store.write({ set: encoded, remove, intent })\n })\n\n const entry: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R> = {\n dependenciesSchema: Schema.Struct({ keys: Schema.Record(Schema.String, Schema.String) }),\n modelToDependencies: model => ({ keys: encode(model) }),\n dependenciesToStream: ({ keys }) =>\n Stream.fromEffect(\n settled(keys).pipe(Effect.andThen(sync(keys)), Effect.delay(throttle)),\n ).pipe(Stream.drain),\n }\n\n const mirror: Mirror<AppModel, Value, R, Name> = {\n kind,\n name,\n keys: keyOf as Readonly<Record<keyof Value & string, string>>,\n contract,\n encode,\n decode,\n fromKeys,\n restoreKeys,\n bootstrap: keys => model => restoreKeys(model, keys),\n href,\n restore,\n subscriptions: { [`${name}.mirror`]: entry } as Mirror<\n AppModel,\n Value,\n R,\n Name\n >['subscriptions'],\n }\n return { mirror, keysOfUrl }\n}\n\n/** The store keys a mirror's config names, before `make` builds it: a store that holds them needs them first. */\nconst ownedKeys = (config: MirrorConfig<Slice>): ReadonlyArray<string> =>\n Object.keys(projectionOf(config.fields).schema.fields).map(\n field =>\n (config.keys as Readonly<Record<string, KeyOptions<unknown> | undefined>> | undefined)?.[\n field\n ]?.key ?? field,\n )\n\n// A mirror's Subscription entries are unbranded so an application can spread them\n// into its own `Subscription.make`; wiring hands them over as a branded record.\nconst brandEntries = <AppModel, R>(\n entries: Readonly<Record<string, EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>>>,\n): Subscription.Subscriptions<AppModel, never, R> =>\n Subscription.make<AppModel, never, R>()(() => entries)\n\nexport const Mirror = {\n /** Mirror's Message cases, to spread into the application's union. */\n messages: mirrorMessageCases,\n\n /**\n * Mirror's Messages as one Schema, for a wrapper variant in the\n * application's union: `GotPrefsMessage: { message: Mirror.Message }`. With\n * a wrapper, `update` matches the application's union exhaustively and\n * `Mirror.fold` reduces what arrives inside it.\n */\n Message: defineMessageUnion(mirrorMessageCases),\n\n /**\n * A key-value mirror under one wrapper variant of the application's union,\n * the same shape Foldkit gives a Submodel: `toParentMessage` wraps the\n * mirror's `MirrorRestored`, the fold reduces it, and `fold.init` runs the\n * lifted `restore` at startup. One wrapper per mirror: two mirrors that\n * share a variant would each have to reduce the other's answer.\n *\n * @example\n * ```ts\n * const Message = defineMessageUnion({ GotPrefsMessage: { message: Mirror.Message } })\n * const foldPrefs = Mirror.fold(Prefs, message => Message.GotPrefsMessage({ message }))\n *\n * const init = (): Return => foldPrefs.init(initial)\n * const update = (model: Model, message: Message): Return =>\n * Message.match(message, {\n * GotPrefsMessage: ({ message }) => foldPrefs(model, message),\n * })\n * ```\n */\n fold: <AppModel, Value extends Record<string, unknown>, Name extends string, ParentMessage>(\n mirror: KvMirror<AppModel, Value, Name>,\n toParentMessage: (message: MirrorRestored) => ParentMessage,\n ): MirrorFold<AppModel, ParentMessage> => {\n const restore = mapMessage(mirror.restore, toParentMessage)\n const fold = (model: AppModel, message: MirrorRestored) => ({\n model: mirror.reduce(model, message),\n })\n return Object.assign(fold, {\n restore,\n init: (model: AppModel) => ({ model, commands: [restore] }),\n })\n },\n\n /** Narrows the application's union to Mirror's cases, by tag. */\n reduces: <M extends { readonly _tag: string }>(\n message: M,\n ): message is Extract<M, { readonly _tag: 'MirrorRestored' }> =>\n Object.hasOwn(mirrorMessageCases, message._tag),\n\n /**\n * Folds pre-init steps into the initial Model, in list order: stores first,\n * the URL last. Either order keeps URL > store > initial (a store bootstrap\n * only fills fields still at their initial value, while a URL `reduce` sets\n * its whole slice), but listing the URL last states the precedence. Among\n * store bootstraps sharing a field, the first one wins.\n *\n * Use this when the keys are already in hand at boot: Flags the server\n * embedded, a synchronous read, a test fixture. When the store can only be\n * read asynchronously, use the `restore` Command (`wiring.init`,\n * `fold.init`) instead: bootstrapping what the store holds needs the keys,\n * and `restore` is how they arrive.\n *\n * @example\n * ```ts\n * const init = (flags: { prefs: Encoded }, url: Url): Return => ({\n * model: Mirror.bootstrap(\n * initial,\n * Prefs.bootstrap(flags.prefs),\n * model => Filters.reduce(model, url),\n * ),\n * })\n * ```\n */\n bootstrap: <AppModel>(model: AppModel, ...steps: ReadonlyArray<Bootstrap<AppModel>>): AppModel =>\n steps.reduce((next, step) => step(next), model),\n\n /**\n * A slice kept in the URL: `Projection.pick(App.model.filter, App.model.q)`\n * as `?filter=…&q=…`, defaults elided, written when it changes (one history\n * write per Model change) and read back with `reduce(model, url)` on\n * `onUrlChange` and on cold load.\n */\n url: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: UrlMirrorConfig<S, Name>,\n ): UrlMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const owned = ownedKeys(config)\n // A write comes back as a `UrlChanged`, and under load it lands after newer\n // edits, even after a second write: reading it would put the older value\n // back (#379). So the mirror keeps the text of its keys in each write whose\n // echo is still to come, and of the URL it last read or wrote; a\n // `UrlChanged` matching either changed nothing of the slice's (an echo, or\n // a write or a path change that left these keys alone).\n const awaited: Array<string> = []\n let seen: Option.Option<string> = Option.none()\n const textOf = (url: Url | string): string => {\n const keys = keysOfUrl(url)\n return JSON.stringify(owned.map(key => own(keys, key) ?? null))\n }\n const { mirror, keysOfUrl } = make(\n app,\n 'url',\n urlStoreReporting(owned, config.location ?? 'search', href => {\n const text = textOf(href)\n seen = Option.some(text)\n // Bounded for an application that never routes its URL Message here.\n if (awaited.push(text) > MAX_AWAITED) awaited.shift()\n }),\n config,\n config.throttle ?? '50 millis',\n Option.none(),\n )\n const read = (model: SliceRoot<S>, url: Url | string) => {\n seen = Option.some(textOf(url))\n return mirror.fromKeys(model, keysOfUrl(url))\n }\n const reduce = (model: SliceRoot<S>, url: Url | string) => {\n // A starting URL: no echo of an earlier runtime's write is coming.\n awaited.length = 0\n return read(model, url)\n }\n const urlChanged = (model: SliceRoot<S>, url: Url | string) => {\n const text = textOf(url)\n const echo = awaited.indexOf(text)\n if (echo >= 0) {\n awaited.splice(0, echo + 1)\n return model\n }\n return Option.contains(seen, text) ? model : read(model, url)\n }\n return {\n ...mirror,\n kind: 'url',\n reduce,\n urlChanged,\n wiring: tag => ({\n key: `mirror:${mirror.name}`,\n handles: [tag],\n shared: [tag],\n route: (model, message) =>\n // tag-check: open — `Tag` is the application's URL variant, generic here\n message._tag === tag\n ? Option.some({ model: urlChanged(model, message.url) })\n : Option.none(),\n onUrl: reduce,\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\n }\n },\n\n /**\n * URL mirrors plugged into `Runtime.makeApplication`: spread the result into\n * its config. `init` reads the starting URL into the Model the application's\n * `init` returns; `update` reads a `urlChanged` Message's URL into the Model\n * (each mirror's `urlChanged`, so an echo changes nothing) before the\n * application's `update` sees it, so a route handler finds the slices\n * already read. `routing` is the application's own, passed through.\n *\n * @example\n * ```ts\n * Runtime.makeApplication({\n * Model, view, subscriptions, container,\n * ...Mirror.routing({\n * mirrors: [Filters],\n * urlChanged: 'ChangedUrl',\n * init,\n * update,\n * routing: {\n * onUrlRequest: request => Message.ClickedLink({ request }),\n * onUrlChange: url => Message.ChangedUrl({ url }),\n * },\n * }),\n * })\n * ```\n */\n routing: <\n AppModel,\n Message extends { readonly _tag: string },\n const Tag extends Message['_tag'],\n Args extends ReadonlyArray<unknown>,\n InitReturn extends { readonly model: AppModel },\n UpdateReturn extends { readonly model: AppModel },\n >(\n config: MirrorRoutingConfig<AppModel, Message, Tag, Args, InitReturn, UpdateReturn>,\n ): MirrorRouting<AppModel, Message, Args, InitReturn, UpdateReturn> => {\n const read = (model: AppModel, url: Url): AppModel =>\n config.mirrors.reduce((next, mirror) => mirror.reduce(next, url), model)\n const changed = (model: AppModel, url: Url): AppModel =>\n config.mirrors.reduce((next, mirror) => mirror.urlChanged(next, url), model)\n const isUrlChanged = (message: Message): message is Message & UrlChangedMessage<Tag> =>\n // tag-check: open — `Tag` is the application's URL variant, generic here\n message._tag === config.urlChanged\n return {\n init: (...args) => {\n const started = config.init(...args)\n return { ...started, model: read(started.model, args[args.length - 1] as Url) }\n },\n update: (model, message) =>\n config.update(isUrlChanged(message) ? changed(model, message.url) : model, message),\n routing: config.routing,\n }\n },\n\n /**\n * A slice kept in Effect's `KeyValueStore` under `key`, as one scoped,\n * versioned JSON document: written when it changes, read back by the\n * `restore` Command whose `MirrorRestored` `reduce` applies.\n */\n kv: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: KvMirrorConfig<S, Name>,\n ): KvMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const { mirror } = make(\n app,\n 'kv',\n MirrorStore.kv({\n key: config.key,\n ...(config.scope === undefined ? {} : { scope: config.scope }),\n }),\n { ...config, name: config.name ?? config.key },\n config.throttle ?? '250 millis',\n // One runtime builds one KeyValueStore: the session is that service.\n Option.some(Effect.service(KeyValueStore.KeyValueStore)),\n )\n const reduce = (model: SliceRoot<S>, message: MirrorRestored) =>\n message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model\n return {\n ...mirror,\n kind: 'kv',\n reduce,\n wiring: () => ({\n key: `mirror:${mirror.name}`,\n handles: ['MirrorRestored'],\n shared: ['MirrorRestored'],\n // Another mirror's restore is not this one's: `None` lets the next mirror take it.\n route: (model, message) =>\n message._tag === 'MirrorRestored' && message.name === mirror.name\n ? Option.some({ model: reduce(model, message) })\n : Option.none(),\n init: model => ({ model, commands: [mirror.restore] }),\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\n }\n },\n\n /**\n * A slice kept in one cookie named `name`, its keys form-encoded in the\n * value: written from the browser when it changes, read by the server\n * (`keysOf` the request's `Cookie` header, then `bootstrap`) so the first\n * render holds it, and set by a server's answer with `setCookie`. A browser\n * writes it, so it is never `HttpOnly`: keep nothing secret in it.\n */\n cookie: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: CookieMirrorConfig<S, Name>,\n ): CookieMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const spec = cookieSpec(\n config.name,\n ownedKeys(config),\n config.attributes ?? {},\n config.maxBytes ?? 4096,\n )\n // No session: the server's render, not a restore, put the cookie's slice\n // in the Model, and a slice the server cleaned (a name it dropped) must\n // still be written.\n const { mirror } = make(\n app,\n 'cookie',\n cookieStore(spec),\n config,\n config.throttle ?? 0,\n Option.none(),\n )\n return {\n ...mirror,\n kind: 'cookie',\n keysOf: header => (header === null ? {} : keysOfCookie(spec, header)),\n setCookie: (model, request) =>\n Result.getSuccess(\n setCookieOf(spec, mirror.encode(model), request.url.startsWith('https:')),\n ),\n wiring: () => ({\n key: `mirror:${mirror.name}`,\n handles: [],\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\n }\n },\n\n /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`, bootstrapped with `bootstrap`. */\n make: <S extends Slice, R, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name>,\n ): Mirror<SliceRoot<S>, SliceValue<S>, R, Name> =>\n make(app, 'memory', store, config, config.throttle ?? 0, Option.some(Effect.succeed(store)))\n .mirror,\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,SAAS;AA0Cf,MAAa,kBAAkB,MAAc,OAAe,cAAsC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,eAAe,KAAK,aAAa,MAAM,mBAAmB,SAAS;CAC5E;CACA;CACA;AACF;AAEA,MAAa,eAAe,KAAa,WAA0D;CACjG,MAAM;CACN;CACA,OAAO;CACP,SAAS,mBAAmB,IAAI,KAAK,MAAM,QAAQ;CACnD;CACA;AACF;AAEA,MAAa,kBACX,KACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,oBAAoB,IAAI,KAAK,MAAM,QAAQ;CACpD;CACA;AACF;AAEA,MAAa,kBAAkB,KAAa,YAAoC;CAC9E,MAAM;CACN;CACA,OAAO;CACP,SAAS,IAAI,IAAI,sCAAsC,OAAO;CAC9D;CACA;AACF;;;;;;;;;AClFA,MAAa,OAAU,QAAqC,QAC1D,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA;;AAG7C,MAAa,OAAU,QAA2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,OAAO,OAAO,KAAK,GAAG,QAAQ,IAAI,WAAW,QAAQ,CAAC,CAC1E;GACF,eAAe;IACb,KAAK,UAAU,OAAO;IACtB,SAAS,CAAC;IACV,eAAe,aAAa,OAAO,aAAa;IAChD,UAAU,OAAO;GACnB;EACF;CACF;;CAGA,OACE,KACA,OACA,WAEA,KAAK,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,GAAG,OAAO,KAAK,OAAO,QAAQ,KAAK,CAAC,CAAC,CAAC,CACzF;AACP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-mirror",
3
- "version": "0.6.3",
3
+ "version": "0.8.0",
4
4
  "description": "A Foldkit Model slice kept in the URL or a key-value store: written when the slice changes, read back on navigation or cold load.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -39,23 +39,23 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "foldkit-surface": "0.10.2"
42
+ "foldkit-surface": "0.12.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "effect": "^4.0.0",
46
- "foldkit": "^0.169.0"
45
+ "effect": "^4.1.0",
46
+ "foldkit": "^0.170.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@effect/platform-browser": "^4.0.5",
50
- "effect": "^4.0.5",
51
- "foldkit": "0.169.0",
49
+ "@effect/platform-browser": "^4.1.1",
50
+ "effect": "^4.1.1",
51
+ "foldkit": "0.170.0",
52
52
  "jsdom": "30.1.3",
53
53
  "tsdown": "^0.23.1",
54
54
  "typescript": "7.0.2",
55
- "foldkit-bundle": "0.8.1"
55
+ "foldkit-bundle": "0.10.0"
56
56
  },
57
57
  "scripts": {
58
- "build": "tsdown",
58
+ "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
59
59
  "typecheck": "tsc -b"
60
60
  }
61
61
  }