@softistx/riva 0.0.0-stage → 0.1.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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/dist/batch.d.ts +5 -0
  4. package/dist/batch.d.ts.map +1 -0
  5. package/dist/chunks/index-2g2s3y31.js +58 -0
  6. package/dist/chunks/index-2g2s3y31.js.map +10 -0
  7. package/dist/chunks/index-46sbdyt0.js +84 -0
  8. package/dist/chunks/index-46sbdyt0.js.map +12 -0
  9. package/dist/chunks/index-5xnfwj57.js +21 -0
  10. package/dist/chunks/index-5xnfwj57.js.map +10 -0
  11. package/dist/chunks/index-asz1gnp1.js +50 -0
  12. package/dist/chunks/index-asz1gnp1.js.map +10 -0
  13. package/dist/chunks/index-e4vzsfy1.js +253 -0
  14. package/dist/chunks/index-e4vzsfy1.js.map +11 -0
  15. package/dist/chunks/index-tn8ankny.js +137 -0
  16. package/dist/chunks/index-tn8ankny.js.map +10 -0
  17. package/dist/chunks/index-vz93xwnj.js +35 -0
  18. package/dist/chunks/index-vz93xwnj.js.map +10 -0
  19. package/dist/chunks/index-y6bzw104.js +53 -0
  20. package/dist/chunks/index-y6bzw104.js.map +11 -0
  21. package/dist/client.d.ts +48 -0
  22. package/dist/client.d.ts.map +1 -0
  23. package/dist/computed.d.ts +21 -0
  24. package/dist/computed.d.ts.map +1 -0
  25. package/dist/data/index.d.ts +19 -0
  26. package/dist/data/index.d.ts.map +1 -0
  27. package/dist/data/index.js +60 -0
  28. package/dist/data/index.js.map +10 -0
  29. package/dist/data/types.d.ts +12 -0
  30. package/dist/data/types.d.ts.map +1 -0
  31. package/dist/duration.d.ts +5 -0
  32. package/dist/duration.d.ts.map +1 -0
  33. package/dist/effect.d.ts +5 -0
  34. package/dist/effect.d.ts.map +1 -0
  35. package/dist/entities/api.d.ts +18 -0
  36. package/dist/entities/api.d.ts.map +1 -0
  37. package/dist/entities/denormalize.d.ts +13 -0
  38. package/dist/entities/denormalize.d.ts.map +1 -0
  39. package/dist/entities/identity.d.ts +11 -0
  40. package/dist/entities/identity.d.ts.map +1 -0
  41. package/dist/entities/index.d.ts +6 -0
  42. package/dist/entities/index.d.ts.map +1 -0
  43. package/dist/entities/index.js +414 -0
  44. package/dist/entities/index.js.map +16 -0
  45. package/dist/entities/json.d.ts +15 -0
  46. package/dist/entities/json.d.ts.map +1 -0
  47. package/dist/entities/normalize.d.ts +11 -0
  48. package/dist/entities/normalize.d.ts.map +1 -0
  49. package/dist/entities/policy.d.ts +41 -0
  50. package/dist/entities/policy.d.ts.map +1 -0
  51. package/dist/entities/store.d.ts +47 -0
  52. package/dist/entities/store.d.ts.map +1 -0
  53. package/dist/env.d.ts +15 -0
  54. package/dist/env.d.ts.map +1 -0
  55. package/dist/errors.d.ts +38 -0
  56. package/dist/errors.d.ts.map +1 -0
  57. package/dist/flush.d.ts +11 -0
  58. package/dist/flush.d.ts.map +1 -0
  59. package/dist/graph.d.ts +47 -0
  60. package/dist/graph.d.ts.map +1 -0
  61. package/dist/index.d.ts +14 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +502 -0
  64. package/dist/index.js.map +18 -0
  65. package/dist/infinite/index.d.ts +3 -0
  66. package/dist/infinite/index.d.ts.map +1 -0
  67. package/dist/infinite/index.js +207 -0
  68. package/dist/infinite/index.js.map +13 -0
  69. package/dist/infinite/infinite.d.ts +8 -0
  70. package/dist/infinite/infinite.d.ts.map +1 -0
  71. package/dist/infinite/more.d.ts +19 -0
  72. package/dist/infinite/more.d.ts.map +1 -0
  73. package/dist/infinite/refetch.d.ts +16 -0
  74. package/dist/infinite/refetch.d.ts.map +1 -0
  75. package/dist/infinite/slots.d.ts +22 -0
  76. package/dist/infinite/slots.d.ts.map +1 -0
  77. package/dist/infinite/types.d.ts +68 -0
  78. package/dist/infinite/types.d.ts.map +1 -0
  79. package/dist/key.d.ts +3 -0
  80. package/dist/key.d.ts.map +1 -0
  81. package/dist/mutation-run.d.ts +5 -0
  82. package/dist/mutation-run.d.ts.map +1 -0
  83. package/dist/mutation.d.ts +53 -0
  84. package/dist/mutation.d.ts.map +1 -0
  85. package/dist/query-cache.d.ts +33 -0
  86. package/dist/query-cache.d.ts.map +1 -0
  87. package/dist/query-entry.d.ts +85 -0
  88. package/dist/query-entry.d.ts.map +1 -0
  89. package/dist/query-observe.d.ts +9 -0
  90. package/dist/query-observe.d.ts.map +1 -0
  91. package/dist/query-run.d.ts +12 -0
  92. package/dist/query-run.d.ts.map +1 -0
  93. package/dist/query.d.ts +100 -0
  94. package/dist/query.d.ts.map +1 -0
  95. package/dist/retry.d.ts +18 -0
  96. package/dist/retry.d.ts.map +1 -0
  97. package/dist/scope.d.ts +16 -0
  98. package/dist/scope.d.ts.map +1 -0
  99. package/dist/signal.d.ts +22 -0
  100. package/dist/signal.d.ts.map +1 -0
  101. package/dist/ssr/codec.d.ts +10 -0
  102. package/dist/ssr/codec.d.ts.map +1 -0
  103. package/dist/ssr/dehydrate.d.ts +37 -0
  104. package/dist/ssr/dehydrate.d.ts.map +1 -0
  105. package/dist/ssr/hydrate.d.ts +20 -0
  106. package/dist/ssr/hydrate.d.ts.map +1 -0
  107. package/dist/ssr/index.d.ts +5 -0
  108. package/dist/ssr/index.d.ts.map +1 -0
  109. package/dist/ssr/index.js +136 -0
  110. package/dist/ssr/index.js.map +11 -0
  111. package/dist/store/def.d.ts +31 -0
  112. package/dist/store/def.d.ts.map +1 -0
  113. package/dist/store/index.d.ts +3 -0
  114. package/dist/store/index.d.ts.map +1 -0
  115. package/dist/store/index.js +215 -0
  116. package/dist/store/index.js.map +14 -0
  117. package/dist/store/instance.d.ts +14 -0
  118. package/dist/store/instance.d.ts.map +1 -0
  119. package/dist/store/run.d.ts +12 -0
  120. package/dist/store/run.d.ts.map +1 -0
  121. package/dist/store/store.d.ts +10 -0
  122. package/dist/store/store.d.ts.map +1 -0
  123. package/dist/store/types.d.ts +70 -0
  124. package/dist/store/types.d.ts.map +1 -0
  125. package/dist/store/view.d.ts +10 -0
  126. package/dist/store/view.d.ts.map +1 -0
  127. package/docs/README.md +19 -0
  128. package/docs/guide/data.md +36 -0
  129. package/docs/guide/entities.md +90 -0
  130. package/docs/guide/errors.md +31 -0
  131. package/docs/guide/infinite.md +62 -0
  132. package/docs/guide/mutations.md +73 -0
  133. package/docs/guide/queries.md +93 -0
  134. package/docs/guide/signals.md +72 -0
  135. package/docs/guide/ssr.md +65 -0
  136. package/docs/guide/store.md +88 -0
  137. package/docs/troubleshooting.md +343 -0
  138. package/package.json +84 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # @softistx/riva
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Core: signals, RivaClient, query and mutation engine, normalized and keyed cache, pagination, optimistic layer, dehydrate and hydrate. Pure TypeScript, no DOM, no React.
4
+
5
+ Work in progress, see the [spec](https://github.com/softistx/riva/blob/develop/docs/spec.md). Guides and fixes: [docs](./docs/README.md).
6
+
7
+ ```sh
8
+ bun add @softistx/riva
9
+ ```
10
+
11
+ Zero runtime dependencies. Definitions are stateless; values live in a `RivaClient`: one per request on the server, so values never leak between requests.
12
+
13
+ | Import | Holds | Guide |
14
+ | --- | --- | --- |
15
+ | `@softistx/riva` | `signal`, `computed`, `effect`, `batch`, `createRivaClient`, `query`, `mutation`, the errors | [signals](./docs/guide/signals.md), [queries](./docs/guide/queries.md), [mutations](./docs/guide/mutations.md), [errors](./docs/guide/errors.md) |
16
+ | `@softistx/riva/entities` | the normalized cache | [entities](./docs/guide/entities.md) |
17
+ | `@softistx/riva/infinite` | cursor pagination | [infinite](./docs/guide/infinite.md) |
18
+ | `@softistx/riva/store` | domain stores | [store](./docs/guide/store.md) |
19
+ | `@softistx/riva/ssr` | dehydrate, hydrate, scope resolver | [ssr](./docs/guide/ssr.md) |
20
+ | `@softistx/riva/data` | the browser's `/_data` client | [data](./docs/guide/data.md) |
21
+
22
+ ## Signals
23
+
24
+ ```ts
25
+ import { batch, computed, createRivaClient, signal, untracked } from '@softistx/riva';
26
+
27
+ const count = signal(0);
28
+ const double = computed((get) => get(count) * 2); // lazy, cached, tracked dynamically
29
+
30
+ const client = createRivaClient();
31
+ client.subscribe(double, (v) => console.log('double', v));
32
+ client.set(count, 2); // logs "double 4"
33
+ client.set(count, (n) => n + 1); // logs "double 6"
34
+
35
+ client.run(() => {
36
+ count.set(10); // ambient reads and writes go through that client
37
+ batch(() => { count.set(11); count.set(12); }); // one notification at the end
38
+ untracked(() => count.get()); // read without becoming a dependency
39
+ });
40
+
41
+ client.effect(() => {
42
+ const n = client.get(count);
43
+ return () => console.log('leaving', n); // runs before each re-run
44
+ });
45
+ ```
46
+
47
+ `signal(initial, { name?, equals?, ssr? })`, `computed(fn, { name?, equals? })`. A read with no client in scope throws `RivaScopeError` (`RIVA_SCOPE`): read through `client.get(def)` or wrap the code in `client.run(() => …)`. In a browser, `setDefaultClient(client)` sets one default; on the server it throws. Details: [signals](./docs/guide/signals.md).
48
+
49
+ ## Queries
50
+
51
+ ```ts
52
+ import { createRivaClient, query, RivaHttpError } from '@softistx/riva';
53
+
54
+ const user = query({
55
+ id: 'user',
56
+ staleTime: '30s', // "250ms" | "30s" | "5m" | "2h", or a number of ms
57
+ fetch: async (vars: { id: string }, { signal }) => {
58
+ const res = await fetch(`/api/users/${vars.id}`, { signal });
59
+ if (!res.ok) throw new RivaHttpError(res.status);
60
+ return (await res.json()) as { id: string; name: string };
61
+ },
62
+ });
63
+
64
+ const client = createRivaClient();
65
+ await user.ensure(client, { id: '1' }); // fetch if missing or stale, else the cache
66
+ client.get(user, { id: '1' }); // { status, data, error, isFetching, updatedAt }
67
+ client.subscribe(user, { id: '1' }, (state) => console.log(state.status)); // fetches, polls, refetches on focus
68
+ user.invalidate(client, { id: '1' }); // stale; refetches when observed
69
+ ```
70
+
71
+ Options: `staleTime` (0), `gcTime` (5 min in a browser, `Infinity` on the server), `retry` (3 in a browser, 0 on the server), `retryDelay`, `refetchOnFocus`, `refetchOnReconnect`, `refetchEvery`, `cache`. One in-flight fetch per key. All of it, with `prefetch`, `setData`, `cancel` and abort: [queries](./docs/guide/queries.md).
72
+
73
+ ## Mutations
74
+
75
+ ```ts
76
+ import { createRivaClient, mutation, query } from '@softistx/riva';
77
+
78
+ const todos = query({ id: 'todos', fetch: async () => (await fetch('/api/todos')).json() as Promise<string[]> });
79
+
80
+ const addTodo = mutation<string, string>({
81
+ id: 'addTodo',
82
+ run: async (title, { signal }) => (await fetch('/api/todos', { method: 'POST', body: title, signal })).text(),
83
+ optimistic: (title, tx) => tx.set(todos, undefined, (prev) => [...(prev ?? []), title]), // shown at once
84
+ updates: (tx, saved) => tx.set(todos, undefined, (prev) => [...(prev ?? []), saved]), // on success
85
+ invalidates: [todos], // marks stale; observed ones refetch
86
+ });
87
+
88
+ await addTodo.run(createRivaClient(), 'Buy milk'); // rejects, with the layer dropped, on failure
89
+ ```
90
+
91
+ The optimistic layer, rollback, ordering and `cache: entities()`: [mutations](./docs/guide/mutations.md). Trap: after success the layer is dropped, so give the mutation `updates`, `invalidates` or `cache`.
92
+
93
+ ## Normalized cache
94
+
95
+ ```ts
96
+ import { entities, readEntity, writeEntity } from '@softistx/riva/entities';
97
+
98
+ const cache = entities({ keys: { Book: (b) => b['isbn'] as string } });
99
+ const patient = query({ id: 'patient', cache, fetch: fetchPatient }); // objects with __typename and id are stored once
100
+ writeEntity(client, 'Patient:1', { name: 'Ann' }); // every query reaching it sees it
101
+ readEntity(client, 'Patient:1');
102
+ ```
103
+
104
+ `invalidateEntity`, `evict`, a codec of your own, and the traps (one set of identity rules per client): [entities](./docs/guide/entities.md).
105
+
106
+ ## Infinite lists
107
+
108
+ ```ts
109
+ import { infinite } from '@softistx/riva/infinite';
110
+
111
+ const feed = infinite({
112
+ id: 'patientsFeed',
113
+ fetch: (v: { search: string; after?: string }) => fetchPage(v), // the library fills `after`
114
+ connection: (page) => page.patients, // { edges, pageInfo }
115
+ });
116
+
117
+ await feed.ensure(client, { search: 'a' });
118
+ await feed.fetchNext(client, { search: 'a' });
119
+ client.get(feed, { search: 'a' }).data?.nodes; // every loaded node
120
+ ```
121
+
122
+ Refetch semantics, `fetchPrevious`, `cursor` names and writing to a feed: [infinite](./docs/guide/infinite.md).
123
+
124
+ ## Stores
125
+
126
+ ```ts
127
+ import { store, type StoreContext } from '@softistx/riva/store';
128
+
129
+ export const BookStore = store({
130
+ name: 'books',
131
+ state: { items: [] as Book[], filter: '' },
132
+ computed: { total: (s) => s.items.length },
133
+ actions: {
134
+ add(s, book: Book) { s.items = [...s.items, book]; }, // only actions write
135
+ async save(s, book: Book, { mutate }: StoreContext) { s.items = [...s.items, await mutate(saveBook, { book })]; },
136
+ },
137
+ });
138
+
139
+ const [s, a] = BookStore.bind(client); // read-only view and bound actions
140
+ ```
141
+
142
+ The context, `reset`, naming rules and SSR: [store](./docs/guide/store.md).
143
+
144
+ ## Server rendering
145
+
146
+ ```ts
147
+ import { dehydrate, hydrate } from '@softistx/riva/ssr';
148
+
149
+ const snapshot = dehydrate(client); // on the server, once the loaders are done
150
+ hydrate(client, snapshot); // in the browser, before the first render
151
+ ```
152
+
153
+ The snapshot is an opaque format: pass on what `dehydrate` returned. A fresh entry is not fetched again, so give hydrated queries a `staleTime`. Escaping, `deferObserved` and `setScopeResolver`: [ssr](./docs/guide/ssr.md).
154
+
155
+ ## Errors
156
+
157
+ `RivaError` (with a `code`) is the base class, defined once here so `instanceof` holds. `RivaScopeError` (`RIVA_SCOPE`), `RivaRequestError` (`status?`, `retryable`), `RivaHttpError` (`HTTP_<status>`), `RivaNetworkError` (`RIVA_NETWORK`), `RivaAbortError` (`RIVA_ABORT`); `isRetryableStatus(status)` tells whether an HTTP status is worth retrying (5xx, 408, 429); `RIVA_CYCLE`, `RIVA_LOOP`, `RIVA_DURATION`, `RIVA_KEY`, `RIVA_CACHE`, `RIVA_STORE` and `RIVA_SSR` are plain `RivaError`s. [errors](./docs/guide/errors.md), [troubleshooting](./docs/troubleshooting.md).
158
+
159
+ ## Data route client
160
+
161
+ `@softistx/riva/data` is the browser's side of a `/_data` route, for a transport of your own: `postData(opts, id, variables, signal?)`. [data](./docs/guide/data.md).
162
+
163
+ ## Types
164
+
165
+ `ClientOptions` (what `createRivaClient` takes), `DataOperation` and `DataSource` (a `/_data` route's operations, from the main entry), `AddContextLast` and `ReservedKey` (the store's typing helpers, from `/store`). Each subpath exports its own types, listed in its [guide](./docs/README.md).
166
+
167
+ ## Size budget
168
+
169
+ The main entry stays within 6144 B gzipped, with `entities` or `infinite` within 8192 B each, with `ssr` or `store` within 7680 B each, with `data` within 7168 B, with every subpath within 12288 B, core + react within 9216 B (`bun run size` checks every row).
@@ -0,0 +1,5 @@
1
+ /** Defers notifications until the outermost batch ends. Without a client in scope, just runs `fn`. */
2
+ export declare const batch: <R>(fn: () => R) => R;
3
+ /** Reads without tracking. Without a client in scope, just runs `fn`. */
4
+ export declare const untracked: <R>(fn: () => R) => R;
5
+ //# sourceMappingURL=batch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.d.ts","sourceRoot":"","sources":["../src/batch.ts"],"names":[],"mappings":"AAEA,sGAAsG;AACtG,eAAO,MAAM,KAAK,GAAI,CAAC,MAAM,MAAM,CAAC,KAAG,CAGtC,CAAC;AAEF,yEAAyE;AACzE,eAAO,MAAM,SAAS,GAAI,CAAC,MAAM,MAAM,CAAC,KAAG,CAG1C,CAAC"}
@@ -0,0 +1,58 @@
1
+ // src/errors.ts
2
+ class RivaError2 extends Error {
3
+ code;
4
+ constructor(code, message, options) {
5
+ super(message, options);
6
+ this.name = "RivaError";
7
+ this.code = code;
8
+ }
9
+ }
10
+
11
+ class RivaScopeError2 extends RivaError2 {
12
+ constructor(message) {
13
+ super("RIVA_SCOPE", message);
14
+ this.name = "RivaScopeError";
15
+ }
16
+ }
17
+
18
+ class RivaRequestError2 extends RivaError2 {
19
+ status;
20
+ retryable;
21
+ constructor(code, message, options) {
22
+ super(code, message, options);
23
+ this.name = "RivaRequestError";
24
+ this.status = options.status;
25
+ this.retryable = options.retryable;
26
+ }
27
+ }
28
+ var isRetryableStatus2 = (status) => status >= 500 || status === 408 || status === 429;
29
+
30
+ class RivaHttpError2 extends RivaRequestError2 {
31
+ constructor(status, message = `HTTP ${status}`, cause) {
32
+ super(`HTTP_${status}`, message, {
33
+ status,
34
+ retryable: isRetryableStatus2(status),
35
+ ...cause
36
+ });
37
+ this.name = "RivaHttpError";
38
+ }
39
+ }
40
+
41
+ class RivaNetworkError2 extends RivaRequestError2 {
42
+ constructor(message = "Network error", cause) {
43
+ super("RIVA_NETWORK", message, { retryable: true, ...cause });
44
+ this.name = "RivaNetworkError";
45
+ }
46
+ }
47
+
48
+ class RivaAbortError2 extends RivaError2 {
49
+ constructor(message = "The request was aborted.") {
50
+ super("RIVA_ABORT", message);
51
+ this.name = "RivaAbortError";
52
+ }
53
+ }
54
+
55
+ export { RivaError2, RivaScopeError2, RivaRequestError2, isRetryableStatus2, RivaHttpError2, RivaNetworkError2, RivaAbortError2 };
56
+
57
+ //# debugId=B61AA4B7A9DA3A8364756E2164756E21
58
+ //# sourceMappingURL=index-2g2s3y31.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/errors.ts"],
4
+ "sourcesContent": [
5
+ "/** Base of every error riva throws. Defined once here so `instanceof` holds across packages. */\nexport class RivaError extends Error {\n\treadonly code: string;\n\tconstructor(code: string, message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = 'RivaError';\n\t\tthis.code = code;\n\t}\n}\n\n/** A value was read with no `RivaClient` in scope. */\nexport class RivaScopeError extends RivaError {\n\tconstructor(message: string) {\n\t\tsuper('RIVA_SCOPE', message);\n\t\tthis.name = 'RivaScopeError';\n\t}\n}\n\n/** A request failed. `retryable` tells the query engine whether trying again can help. */\nexport class RivaRequestError extends RivaError {\n\treadonly status: number | undefined;\n\treadonly retryable: boolean;\n\tconstructor(\n\t\tcode: string,\n\t\tmessage: string,\n\t\toptions: { retryable: boolean; status?: number; cause?: unknown },\n\t) {\n\t\tsuper(code, message, options);\n\t\tthis.name = 'RivaRequestError';\n\t\tthis.status = options.status;\n\t\tthis.retryable = options.retryable;\n\t}\n}\n\n/** Whether a failed HTTP status is worth retrying: 5xx, 408 and 429. */\nexport const isRetryableStatus = (status: number): boolean =>\n\tstatus >= 500 || status === 408 || status === 429;\n\n/** An HTTP error status. Retryable for 5xx, 408 and 429. */\nexport class RivaHttpError extends RivaRequestError {\n\tconstructor(\n\t\tstatus: number,\n\t\tmessage = `HTTP ${status}`,\n\t\tcause?: { cause?: unknown },\n\t) {\n\t\tsuper(`HTTP_${status}`, message, {\n\t\t\tstatus,\n\t\t\tretryable: isRetryableStatus(status),\n\t\t\t...cause,\n\t\t});\n\t\tthis.name = 'RivaHttpError';\n\t}\n}\n\n/** The network failed before any response. Always retryable. */\nexport class RivaNetworkError extends RivaRequestError {\n\tconstructor(message = 'Network error', cause?: { cause?: unknown }) {\n\t\tsuper('RIVA_NETWORK', message, { retryable: true, ...cause });\n\t\tthis.name = 'RivaNetworkError';\n\t}\n}\n\n/** A request was aborted. Never retried. */\nexport class RivaAbortError extends RivaError {\n\tconstructor(message = 'The request was aborted.') {\n\t\tsuper('RIVA_ABORT', message);\n\t\tthis.name = 'RivaAbortError';\n\t}\n}\n"
6
+ ],
7
+ "mappings": ";AACO,MAAM,mBAAkB,MAAM;AAAA,EAC3B;AAAA,EACT,WAAW,CAAC,MAAc,SAAiB,SAAwB;AAAA,IAClE,MAAM,SAAS,OAAO;AAAA,IACtB,KAAK,OAAO;AAAA,IACZ,KAAK,OAAO;AAAA;AAEd;AAAA;AAGO,MAAM,wBAAuB,WAAU;AAAA,EAC7C,WAAW,CAAC,SAAiB;AAAA,IAC5B,MAAM,cAAc,OAAO;AAAA,IAC3B,KAAK,OAAO;AAAA;AAEd;AAAA;AAGO,MAAM,0BAAyB,WAAU;AAAA,EACtC;AAAA,EACA;AAAA,EACT,WAAW,CACV,MACA,SACA,SACC;AAAA,IACD,MAAM,MAAM,SAAS,OAAO;AAAA,IAC5B,KAAK,OAAO;AAAA,IACZ,KAAK,SAAS,QAAQ;AAAA,IACtB,KAAK,YAAY,QAAQ;AAAA;AAE3B;AAGO,IAAM,qBAAoB,CAAC,WACjC,UAAU,OAAO,WAAW,OAAO,WAAW;AAAA;AAGxC,MAAM,uBAAsB,kBAAiB;AAAA,EACnD,WAAW,CACV,QACA,UAAU,QAAQ,UAClB,OACC;AAAA,IACD,MAAM,QAAQ,UAAU,SAAS;AAAA,MAChC;AAAA,MACA,WAAW,mBAAkB,MAAM;AAAA,SAChC;AAAA,IACJ,CAAC;AAAA,IACD,KAAK,OAAO;AAAA;AAEd;AAAA;AAGO,MAAM,0BAAyB,kBAAiB;AAAA,EACtD,WAAW,CAAC,UAAU,iBAAiB,OAA6B;AAAA,IACnE,MAAM,gBAAgB,SAAS,EAAE,WAAW,SAAS,MAAM,CAAC;AAAA,IAC5D,KAAK,OAAO;AAAA;AAEd;AAAA;AAGO,MAAM,wBAAuB,WAAU;AAAA,EAC7C,WAAW,CAAC,UAAU,4BAA4B;AAAA,IACjD,MAAM,cAAc,OAAO;AAAA,IAC3B,KAAK,OAAO;AAAA;AAEd;",
8
+ "debugId": "B61AA4B7A9DA3A8364756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,84 @@
1
+ import {
2
+ isBrowser
3
+ } from "./index-y6bzw104.js";
4
+ import {
5
+ RivaError2,
6
+ RivaRequestError2,
7
+ RivaAbortError2
8
+ } from "./index-2g2s3y31.js";
9
+
10
+ // src/duration.ts
11
+ var UNITS = { ms: 1, s: 1000, m: 60000, h: 3600000 };
12
+ function toMs(d) {
13
+ const m = /^(\d+(\.\d+)?)(ms|s|m|h)$/.exec(d);
14
+ if (m)
15
+ return Number(m[1]) * UNITS[m[3]];
16
+ if (typeof d === "number" && d >= 0)
17
+ return d;
18
+ throw new RivaError2("RIVA_DURATION", `Invalid duration ${JSON.stringify(d)}: use ms, Infinity or "30s", "5m".`);
19
+ }
20
+
21
+ // src/retry.ts
22
+ function shouldRetry(retry, failures, error) {
23
+ if (error instanceof RivaAbortError2)
24
+ return false;
25
+ if (error instanceof RivaRequestError2 && !error.retryable)
26
+ return false;
27
+ if (typeof retry === "function")
28
+ return retry(failures, error);
29
+ return failures < (retry ?? (isBrowser() ? 3 : 0));
30
+ }
31
+ var retryDelay = (fn, failures) => fn ? fn(failures) : Math.min(1000 * 2 ** failures, 30000);
32
+ function raceAbort(p, signal) {
33
+ return new Promise((resolve, reject) => {
34
+ const onAbort = () => reject(new RivaAbortError2);
35
+ if (signal.aborted)
36
+ return onAbort();
37
+ signal.addEventListener("abort", onAbort, { once: true });
38
+ p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
39
+ });
40
+ }
41
+ function sleep(sched, ms, signal) {
42
+ let h;
43
+ if (signal.aborted)
44
+ return Promise.resolve();
45
+ return raceAbort(new Promise((r) => h = sched.setTimeout(r, ms)), signal).catch(() => {}).finally(() => sched.clearTimeout(h));
46
+ }
47
+ async function withRetry(sched, opts, signal, fn) {
48
+ for (let failures = 0;; ) {
49
+ try {
50
+ return await raceAbort(fn(), signal);
51
+ } catch (x) {
52
+ if (!shouldRetry(opts.retry, failures, x))
53
+ throw x;
54
+ await sleep(sched, retryDelay(opts.retryDelay, failures++), signal);
55
+ if (signal.aborted)
56
+ throw new RivaAbortError2;
57
+ }
58
+ }
59
+ }
60
+
61
+ // src/query.ts
62
+ var ms = (d, fallback) => d === undefined ? fallback : toMs(d);
63
+ function query2(opts) {
64
+ const def = {
65
+ kind: "query",
66
+ id: opts.id,
67
+ options: Object.freeze({
68
+ ...opts,
69
+ staleTime: ms(opts.staleTime, 0),
70
+ gcTime: ms(opts.gcTime),
71
+ refetchOnFocus: opts.refetchOnFocus ?? true,
72
+ refetchOnReconnect: opts.refetchOnReconnect ?? true,
73
+ refetchEvery: ms(opts.refetchEvery)
74
+ })
75
+ };
76
+ for (const m of ["ensure", "prefetch", "invalidate", "setData", "cancel"])
77
+ def[m] = (client, ...args) => client.queries[m]?.(def, ...args);
78
+ return Object.freeze(def);
79
+ }
80
+
81
+ export { toMs, shouldRetry, retryDelay, raceAbort, sleep, withRetry, query2 };
82
+
83
+ //# debugId=49F12CAA68DE934164756E2164756E21
84
+ //# sourceMappingURL=index-46sbdyt0.js.map
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/duration.ts", "../src/retry.ts", "../src/query.ts"],
4
+ "sourcesContent": [
5
+ "import { RivaError } from './errors';\n\n/** A duration: a number of milliseconds, or a string such as `\"30s\"`, `\"5m\"`, `\"2h\"`, `\"250ms\"`. */\nexport type Duration = number | `${number}${'ms' | 's' | 'm' | 'h'}`;\n\nconst UNITS = { ms: 1, s: 1e3, m: 6e4, h: 36e5 };\n\n/** Converts a `Duration` to milliseconds. `Infinity` is allowed; anything else invalid throws `RIVA_DURATION`. */\nexport function toMs(d: Duration): number {\n\tconst m = /^(\\d+(\\.\\d+)?)(ms|s|m|h)$/.exec(d as string);\n\tif (m) return Number(m[1]) * UNITS[m[3] as keyof typeof UNITS];\n\tif (typeof d === 'number' && d >= 0) return d;\n\tthrow new RivaError(\n\t\t'RIVA_DURATION',\n\t\t`Invalid duration ${JSON.stringify(d)}: use ms, Infinity or \"30s\", \"5m\".`,\n\t);\n}\n",
6
+ "import type { Scheduler } from './env';\nimport { RivaAbortError, RivaRequestError } from './errors';\nimport { isBrowser } from './scope';\n\n/**\n * Whether a failed fetch is tried again. `failures` counts the failures\n * before this one (0 for the first). An abort and a non-retryable request\n * error never retry; any other error (unknown) does.\n */\nexport function shouldRetry(\n\tretry: number | ((failures: number, error: unknown) => boolean) | undefined,\n\tfailures: number,\n\terror: unknown,\n): boolean {\n\tif (error instanceof RivaAbortError) return false;\n\tif (error instanceof RivaRequestError && !error.retryable) return false;\n\tif (typeof retry === 'function') return retry(failures, error);\n\treturn failures < (retry ?? (isBrowser() ? 3 : 0));\n}\n\nexport const retryDelay = (\n\tfn: ((failures: number) => number) | undefined,\n\tfailures: number,\n): number => (fn ? fn(failures) : Math.min(1000 * 2 ** failures, 30_000));\n\n/** Settles with `p`, or as soon as `signal` aborts (rejecting with `RivaAbortError`), even if `p` never settles. */\nexport function raceAbort<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(new RivaAbortError());\n\t\tif (signal.aborted) return onAbort();\n\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\tp.then(resolve, reject).finally(() =>\n\t\t\tsignal.removeEventListener('abort', onAbort),\n\t\t);\n\t});\n}\n\n/** Waits `ms`, or until `signal` aborts (whichever comes first). */\nexport function sleep(\n\tsched: Scheduler,\n\tms: number,\n\tsignal: AbortSignal,\n): Promise<void> {\n\tlet h: unknown;\n\tif (signal.aborted) return Promise.resolve();\n\treturn raceAbort(\n\t\tnew Promise<void>((r) => (h = sched.setTimeout(r, ms))),\n\t\tsignal,\n\t)\n\t\t.catch(() => {})\n\t\t.finally(() => sched.clearTimeout(h));\n}\n\n/** Runs `fn` until it succeeds, retrying as `shouldRetry` decides, with backoff; stops with `RivaAbortError` once `signal` aborts. */\nexport async function withRetry<T>(\n\tsched: Scheduler,\n\topts: {\n\t\tretry: number | ((failures: number, error: unknown) => boolean) | undefined;\n\t\tretryDelay: ((failures: number) => number) | undefined;\n\t},\n\tsignal: AbortSignal,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tfor (let failures = 0; ; ) {\n\t\ttry {\n\t\t\treturn await raceAbort(fn(), signal);\n\t\t} catch (x) {\n\t\t\tif (!shouldRetry(opts.retry, failures, x)) throw x;\n\t\t\tawait sleep(sched, retryDelay(opts.retryDelay, failures++), signal);\n\t\t\tif (signal.aborted) throw new RivaAbortError();\n\t\t}\n\t}\n}\n",
7
+ "import type { RivaClient } from './client';\nimport { type Duration, toMs } from './duration';\n\nexport type QueryStatus = 'idle' | 'pending' | 'success' | 'error';\n\n/**\n * What a query entry holds. `status` stays `success` with the old data during\n * a background refetch (`isFetching` is true); an error keeps the last data.\n */\nexport interface QueryState<Data> {\n\treadonly status: QueryStatus;\n\treadonly data: Data | undefined;\n\treadonly error: unknown;\n\treadonly isFetching: boolean;\n\t/** Epoch milliseconds of the last success (0 when none). */\n\treadonly updatedAt: number;\n}\n\nexport interface FetchContext {\n\tsignal: AbortSignal;\n\tclient: RivaClient;\n}\n\n/**\n * How a query entry stores its data. The default keeps it as is; a policy such\n * as `entities()` from `@softistx/riva/entities` normalizes it into shared\n * entities. `read` runs in a computed, so what it reads is tracked.\n */\nexport interface CachePolicy<Stored = unknown> {\n\t/** `prev` is what the entry stored before, so a policy can keep identities across writes; `vars` are the entry's variables. */\n\twrite(\n\t\tclient: RivaClient,\n\t\tdata: unknown,\n\t\tprev?: Stored,\n\t\tvars?: unknown,\n\t): Stored;\n\t/** `committed` skips the optimistic layers (the data a write must start from). */\n\tread(client: RivaClient, stored: Stored, committed?: boolean): unknown;\n\t/** The entry was replaced or collected: drop what `write` retained. */\n\trelease(client: RivaClient, stored: Stored): void;\n\t/** Mutations: shows `data` over the committed data until `drop` (an optimistic layer). */\n\tlayer?(client: RivaClient, data: unknown, vars?: unknown): { drop(): void };\n\t/** Mutations: merges a server result into the committed data, notifying its readers. */\n\tcommit?(client: RivaClient, data: unknown, vars?: unknown): void;\n}\n\nexport interface QueryOptions<Vars, Data> {\n\t/** Identifies the definition; the cache key is the id plus the stable-serialized variables. */\n\tid: string;\n\tfetch: (vars: Vars, ctx: FetchContext) => Promise<Data>;\n\t/** How long data stays fresh. Default 0. */\n\tstaleTime?: Duration;\n\t/** How long an unobserved entry is kept. Default 5 min in a browser, `Infinity` on the server. */\n\tgcTime?: Duration;\n\t/** A count of retries, or a decision. `failures` is the number of failures before this one. Default 3 in a browser, 0 on the server. */\n\tretry?: number | ((failures: number, error: unknown) => boolean);\n\t/** Delay before a retry, in ms. Default `min(1000 * 2 ** failures, 30_000)`. */\n\tretryDelay?: (failures: number) => number;\n\t/** Default true. */\n\trefetchOnFocus?: boolean;\n\t/** Default true. */\n\trefetchOnReconnect?: boolean;\n\t/** Polls while the entry is observed. */\n\trefetchEvery?: Duration;\n\t/** How the data is stored. Default: as is (a keyed cache). */\n\tcache?: CachePolicy;\n\t/** @internal Shapes the state readers see, last (after the policy and the layers); read inside a computed. */\n\tderive?: (client: RivaClient, state: QueryState<Data>, vars: Vars) => unknown;\n}\n\nexport interface EnsureOptions {\n\tsignal?: AbortSignal;\n}\n\n/** The variables argument, optional when `Vars` is `void` or `undefined`. */\nexport type VarsArgs<Vars, Rest extends unknown[] = []> = [Vars] extends [\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void variables are optional at call sites\n\tvoid | undefined,\n]\n\t? [vars?: Vars, ...rest: Rest]\n\t: [vars: Vars, ...rest: Rest];\n\n/** A stateless query definition: the data lives in a `RivaClient`. `S` is the state readers get (`QueryState<Data>` unless a module derives more). */\nexport interface Query<\n\tVars,\n\tData,\n\tS extends QueryState<unknown> = QueryState<Data>,\n> {\n\t/** @internal Phantom: carries `S` to `client.get` and `subscribe`. */\n\treadonly '~state'?: S;\n\treadonly kind: 'query';\n\treadonly id: string;\n\t/** @internal */\n\treadonly options: {\n\t\treadonly fetch: QueryOptions<Vars, Data>['fetch'];\n\t\treadonly staleTime: number;\n\t\treadonly gcTime: number | undefined;\n\t\treadonly retry: QueryOptions<Vars, Data>['retry'];\n\t\treadonly retryDelay: QueryOptions<Vars, Data>['retryDelay'];\n\t\treadonly refetchOnFocus: boolean;\n\t\treadonly refetchOnReconnect: boolean;\n\t\treadonly refetchEvery: number | undefined;\n\t\treadonly cache: CachePolicy | undefined;\n\t\treadonly derive: QueryOptions<Vars, Data>['derive'];\n\t};\n\t/** Fetches when missing or stale and awaits; resolves the cache when fresh. */\n\tensure(\n\t\tclient: RivaClient,\n\t\t...args: VarsArgs<Vars, [opts?: EnsureOptions]>\n\t): Promise<Data>;\n\t/** Fire and forget; never rejects. */\n\tprefetch(client: RivaClient, ...args: VarsArgs<Vars>): void;\n\t/** Marks stale (one entry, or every entry of the definition without variables); observed entries refetch. */\n\tinvalidate(client: RivaClient, vars?: Vars): void;\n\t/** Writes a success with `updatedAt` now. */\n\tsetData(\n\t\tclient: RivaClient,\n\t\tvars: Vars,\n\t\tdata: Data | ((prev: Data | undefined) => Data),\n\t): void;\n\t/** Aborts the in-flight fetch and restores the previous state. */\n\tcancel(client: RivaClient, ...args: VarsArgs<Vars>): void;\n}\n\nconst ms = (d: Duration | undefined, fallback?: number) =>\n\td === undefined ? fallback : toMs(d);\n\nexport function query<Vars = void, Data = unknown>(\n\topts: QueryOptions<Vars, Data>,\n): Query<Vars, Data> {\n\tconst def = {\n\t\tkind: 'query',\n\t\tid: opts.id,\n\t\toptions: Object.freeze({\n\t\t\t...opts,\n\t\t\tstaleTime: ms(opts.staleTime, 0),\n\t\t\tgcTime: ms(opts.gcTime),\n\t\t\trefetchOnFocus: opts.refetchOnFocus ?? true,\n\t\t\trefetchOnReconnect: opts.refetchOnReconnect ?? true,\n\t\t\trefetchEvery: ms(opts.refetchEvery),\n\t\t}),\n\t} as Record<string, unknown>;\n\tfor (const m of ['ensure', 'prefetch', 'invalidate', 'setData', 'cancel'])\n\t\tdef[m] = (client: RivaClient, ...args: unknown[]) =>\n\t\t\t(\n\t\t\t\tclient.queries as unknown as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\t(...a: unknown[]) => unknown\n\t\t\t\t>\n\t\t\t)[m]?.(def, ...args);\n\treturn Object.freeze(def) as unknown as Query<Vars, Data>;\n}\n"
8
+ ],
9
+ "mappings": ";;;;;;;;;;AAKA,IAAM,QAAQ,EAAE,IAAI,GAAG,GAAG,MAAK,GAAG,OAAK,GAAG,QAAK;AAGxC,SAAS,IAAI,CAAC,GAAqB;AAAA,EACzC,MAAM,IAAI,4BAA4B,KAAK,CAAW;AAAA,EACtD,IAAI;AAAA,IAAG,OAAO,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE;AAAA,EACrC,IAAI,OAAO,MAAM,YAAY,KAAK;AAAA,IAAG,OAAO;AAAA,EAC5C,MAAM,IAAI,WACT,iBACA,oBAAoB,KAAK,UAAU,CAAC,qCACrC;AAAA;;;ACNM,SAAS,WAAW,CAC1B,OACA,UACA,OACU;AAAA,EACV,IAAI,iBAAiB;AAAA,IAAgB,OAAO;AAAA,EAC5C,IAAI,iBAAiB,qBAAoB,CAAC,MAAM;AAAA,IAAW,OAAO;AAAA,EAClE,IAAI,OAAO,UAAU;AAAA,IAAY,OAAO,MAAM,UAAU,KAAK;AAAA,EAC7D,OAAO,YAAY,UAAU,UAAU,IAAI,IAAI;AAAA;AAGzC,IAAM,aAAa,CACzB,IACA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ACN,IAAI,KAAK;AAAA,IACT,SAAS,OAAO,OAAO;AAAA,SACnB;AAAA,MACH,WAAW,GAAG,KAAK,WAAW,CAAC;AAAA,MAC/B,QAAQ,GAAG,KAAK,MAAM;AAAA,MACtB,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,oBAAoB,KAAK,sBAAsB;AAAA,MAC/C,cAAc,GAAG,KAAK,YAAY;AAAA,IACnC,CAAC;AAAA,EACF;AAAA,EACA,WAAW,KAAK,CAAC,UAAU,YAAY,cAAc,WAAW,QAAQ;AAAA,IACvE,IAAI,KAAK,CAAC,WAAuB,SAE/B,OAAO,QAIN,KAAK,KAAK,GAAG,IAAI;AAAA,EACrB,OAAO,OAAO,OAAO,GAAG;AAAA;",
10
+ "debugId": "49F12CAA68DE934164756E2164756E21",
11
+ "names": []
12
+ }
@@ -0,0 +1,21 @@
1
+ import {
2
+ resolve
3
+ } from "./index-y6bzw104.js";
4
+
5
+ // src/computed.ts
6
+ function computed2(fn, opts = {}) {
7
+ const def = Object.freeze({
8
+ kind: "computed",
9
+ name: opts.name,
10
+ fn,
11
+ equals: opts.equals ?? Object.is,
12
+ get: () => resolve().get(def),
13
+ subscribe: (listener) => resolve().subscribe(def, listener)
14
+ });
15
+ return def;
16
+ }
17
+
18
+ export { computed2 };
19
+
20
+ //# debugId=C80B516600D8DE1464756E2164756E21
21
+ //# sourceMappingURL=index-5xnfwj57.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/computed.ts"],
4
+ "sourcesContent": [
5
+ "import { resolve } from './scope';\nimport type { Listener, Signal, Unsubscribe } from './signal';\n\n/** A signal seen without its setter: what a store exposes for its state keys. */\nexport interface ReadonlySignal<T> extends Omit<Signal<T>, 'set' | 'equals'> {}\n\nexport type Readable<T> = Signal<T> | ReadonlySignal<T> | Computed<T>;\nexport type Getter = <U>(def: Readable<U>) => U;\n\nexport interface ComputedOptions<T> {\n\tname?: string;\n\tequals?: (a: T, b: T) => boolean;\n}\n\n/** A stateless derived value: lazy, cached per client, tracked dynamically. */\nexport interface Computed<T> {\n\treadonly kind: 'computed';\n\treadonly name: string | undefined;\n\tfn(get: Getter): T;\n\tequals(a: T, b: T): boolean;\n\tget(): T;\n\tsubscribe(listener: Listener<T>): Unsubscribe;\n}\n\nexport function computed<T>(\n\tfn: (get: Getter) => T,\n\topts: ComputedOptions<T> = {},\n): Computed<T> {\n\tconst def: Computed<T> = Object.freeze({\n\t\tkind: 'computed',\n\t\tname: opts.name,\n\t\tfn,\n\t\tequals: opts.equals ?? Object.is,\n\t\tget: () => resolve().get(def),\n\t\tsubscribe: (listener: Listener<T>) => resolve().subscribe(def, listener),\n\t});\n\treturn def;\n}\n"
6
+ ],
7
+ "mappings": ";;;;;AAwBO,SAAS,SAAW,CAC1B,IACA,OAA2B,CAAC,GACd;AAAA,EACd,MAAM,MAAmB,OAAO,OAAO;AAAA,IACtC,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX;AAAA,IACA,QAAQ,KAAK,UAAU,OAAO;AAAA,IAC9B,KAAK,MAAM,QAAQ,EAAE,IAAI,GAAG;AAAA,IAC5B,WAAW,CAAC,aAA0B,QAAQ,EAAE,UAAU,KAAK,QAAQ;AAAA,EACxE,CAAC;AAAA,EACD,OAAO;AAAA;",
8
+ "debugId": "C80B516600D8DE1464756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,50 @@
1
+ import {
2
+ RivaError2
3
+ } from "./index-2g2s3y31.js";
4
+
5
+ // src/ssr/codec.ts
6
+ var ssrError = (message) => new RivaError2("RIVA_SSR", message);
7
+ var refuse = (what, path) => {
8
+ throw ssrError(`Cannot dehydrate ${what} at ${path}: snapshots hold JSON values and Dates. Convert it in the fetch, or keep it out of the cache.`);
9
+ };
10
+ var mapObject = (o, f) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v, k)]));
11
+ function encodeAt(value, path = "$", seen = []) {
12
+ const type = typeof value;
13
+ if (type === "bigint" || type === "function" || type === "symbol")
14
+ return refuse(`a ${type}`, path);
15
+ if (type === "number")
16
+ return Number.isFinite(value) ? value : { $t: "N", v: String(value) };
17
+ if (type !== "object" || value === null)
18
+ return value;
19
+ const obj = value;
20
+ if (seen.includes(obj))
21
+ return refuse("a cycle", path);
22
+ if (obj instanceof Date)
23
+ return { $t: "D", v: Number.isNaN(+obj) ? "NaN" : obj.toISOString() };
24
+ const list = Array.isArray(obj);
25
+ const p = Object.getPrototypeOf(obj);
26
+ if (!list && p !== Object.prototype && p !== null)
27
+ return refuse(`an instance of ${p?.constructor?.name ?? "object"}`, path);
28
+ seen.push(obj);
29
+ const out = list ? obj.map((x, i) => encodeAt(x, `${path}[${i}]`, seen)) : mapObject(obj, (v, k) => encodeAt(v, `${path}.${k}`, seen));
30
+ seen.pop();
31
+ return "$t" in obj ? { $t: "O", v: out } : out;
32
+ }
33
+ var encode2 = encodeAt;
34
+ function decode2(value) {
35
+ if (typeof value !== "object" || value === null)
36
+ return value;
37
+ if (Array.isArray(value))
38
+ return value.map(decode2);
39
+ const { $t: tag, v } = value;
40
+ if (tag === "D")
41
+ return new Date(v === "NaN" ? Number.NaN : v);
42
+ if (tag === "N")
43
+ return Number(v);
44
+ return mapObject(tag === "O" ? v : value, decode2);
45
+ }
46
+
47
+ export { ssrError, encodeAt, encode2, decode2 };
48
+
49
+ //# debugId=3C348DE861B9D2E164756E2164756E21
50
+ //# sourceMappingURL=index-asz1gnp1.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/ssr/codec.ts"],
4
+ "sourcesContent": [
5
+ "import { RivaError } from '../errors';\n\n/** The error of every refused snapshot. */\nexport const ssrError = (message: string): RivaError =>\n\tnew RivaError('RIVA_SSR', message);\n\nconst refuse = (what: string, path: string): never => {\n\tthrow ssrError(\n\t\t`Cannot dehydrate ${what} at ${path}: snapshots hold JSON values and Dates. Convert it in the fetch, or keep it out of the cache.`,\n\t);\n};\n\nconst mapObject = (o: object, f: (v: unknown, k: string) => unknown) =>\n\tObject.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v, k)]));\n\n/** `encode` with the path shown in a refusal's message. */\nexport function encodeAt(\n\tvalue: unknown,\n\tpath = '$',\n\tseen: object[] = [],\n): unknown {\n\tconst type = typeof value;\n\tif (type === 'bigint' || type === 'function' || type === 'symbol')\n\t\treturn refuse(`a ${type}`, path);\n\tif (type === 'number')\n\t\treturn Number.isFinite(value) ? value : { $t: 'N', v: String(value) };\n\tif (type !== 'object' || value === null) return value;\n\tconst obj = value as object;\n\tif (seen.includes(obj)) return refuse('a cycle', path);\n\t// An invalid Date has no ISO string: its tag carries 'NaN' and decodes back to it.\n\tif (obj instanceof Date)\n\t\treturn { $t: 'D', v: Number.isNaN(+obj) ? 'NaN' : obj.toISOString() };\n\tconst list = Array.isArray(obj);\n\tconst p = Object.getPrototypeOf(obj);\n\tif (!list && p !== Object.prototype && p !== null)\n\t\treturn refuse(`an instance of ${p?.constructor?.name ?? 'object'}`, path);\n\tseen.push(obj);\n\tconst out = list\n\t\t? obj.map((x, i) => encodeAt(x, `${path}[${i}]`, seen))\n\t\t: mapObject(obj, (v, k) => encodeAt(v, `${path}.${k}`, seen));\n\tseen.pop();\n\treturn '$t' in obj ? { $t: 'O', v: out } : out;\n}\n\n/** A JSON-safe copy of `value`: Dates and non-finite numbers are tagged, `$t` keys escaped. */\nexport const encode: (value: unknown) => unknown = encodeAt;\n\n/** The inverse of `encode`. */\nexport function decode(value: unknown): unknown {\n\tif (typeof value !== 'object' || value === null) return value;\n\tif (Array.isArray(value)) return value.map(decode);\n\t// biome-ignore lint/style/useNamingConvention: the tag key of the wire format\n\tconst { $t: tag, v } = value as { $t?: unknown; v?: unknown };\n\tif (tag === 'D') return new Date(v === 'NaN' ? Number.NaN : (v as string));\n\tif (tag === 'N') return Number(v);\n\treturn mapObject((tag === 'O' ? v : value) as object, decode);\n}\n"
6
+ ],
7
+ "mappings": ";;;;;AAGO,IAAM,WAAW,CAAC,YACxB,IAAI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