@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
@@ -0,0 +1,253 @@
1
+ import {
2
+ withClient
3
+ } from "./index-y6bzw104.js";
4
+ import {
5
+ RivaError2
6
+ } from "./index-2g2s3y31.js";
7
+
8
+ // src/flush.ts
9
+ var MAX_RUNS = 100;
10
+ function collect(g, n) {
11
+ const seen = new Set([n]);
12
+ const stack = [n];
13
+ for (let x = stack.pop();x; x = stack.pop()) {
14
+ if (x.listeners.size > 0)
15
+ g.pending.add(x);
16
+ for (const o of x.observers)
17
+ if (!seen.has(o)) {
18
+ seen.add(o);
19
+ stack.push(o);
20
+ }
21
+ }
22
+ }
23
+ function flush(g, refresh) {
24
+ if (g.depth > 0 || g.flushing)
25
+ return;
26
+ g.flushing = true;
27
+ const errors = [];
28
+ const runs = new Map;
29
+ try {
30
+ while (g.pending.size > 0) {
31
+ const queue = [...g.pending];
32
+ g.pending.clear();
33
+ for (const n of queue) {
34
+ const count = (runs.get(n) ?? 0) + 1;
35
+ runs.set(n, count);
36
+ if (count > MAX_RUNS) {
37
+ errors.push(new RivaError2("RIVA_LOOP", n.def.name ? `Loop detected: ${n.def.name} re-ran more than ${MAX_RUNS} times in one flush.` : `Loop detected: a node re-ran more than ${MAX_RUNS} times in one flush; name it with { name } to find it.`));
38
+ continue;
39
+ }
40
+ try {
41
+ refresh(g, n);
42
+ if (n.def.kind === "computed" && n.stamp !== g.epoch)
43
+ g.pending.add(n);
44
+ if (n.ver === n.seen)
45
+ continue;
46
+ n.seen = n.ver;
47
+ for (const l of [...n.listeners])
48
+ try {
49
+ withClient(g.client, () => l(n.value));
50
+ } catch (e) {
51
+ errors.push(e);
52
+ }
53
+ } catch (e) {
54
+ errors.push(e);
55
+ }
56
+ }
57
+ }
58
+ } finally {
59
+ g.flushing = false;
60
+ }
61
+ if (errors.length === 1)
62
+ throw errors[0];
63
+ if (errors.length > 1)
64
+ throw new AggregateError(errors, "Several listeners or computeds threw.");
65
+ }
66
+
67
+ // src/graph.ts
68
+ var createGraph = (client) => ({
69
+ client,
70
+ nodes: new WeakMap,
71
+ epoch: 0,
72
+ track: undefined,
73
+ depth: 0,
74
+ flushing: false,
75
+ pending: new Set,
76
+ named: new Map
77
+ });
78
+ function initialOf(g, def) {
79
+ const { name } = def;
80
+ return def.ssr && name !== undefined && g.seeds?.has(name) ? g.seeds.get(name) : def.initial;
81
+ }
82
+ function nodeOf(g, def) {
83
+ let n = g.nodes.get(def);
84
+ if (!n) {
85
+ const isSignal = def.kind === "signal";
86
+ n = {
87
+ def,
88
+ value: isSignal ? initialOf(g, def) : undefined,
89
+ ver: 0,
90
+ stamp: -1,
91
+ refs: 0,
92
+ observers: new Set,
93
+ deps: new Map,
94
+ listeners: new Set,
95
+ seen: 0,
96
+ busy: false,
97
+ init: isSignal
98
+ };
99
+ g.nodes.set(def, n);
100
+ if (isSignal && def.ssr && def.name !== undefined)
101
+ g.named.set(def.name, g.named.has(def.name) ? null : n);
102
+ }
103
+ return n;
104
+ }
105
+ function retain(n) {
106
+ if (n.refs++ === 0)
107
+ for (const d of n.deps.keys()) {
108
+ d.observers.add(n);
109
+ retain(d);
110
+ }
111
+ }
112
+ function release(n) {
113
+ if (--n.refs === 0)
114
+ for (const d of n.deps.keys()) {
115
+ d.observers.delete(n);
116
+ release(d);
117
+ }
118
+ }
119
+ function untracked2(g, fn) {
120
+ const previous = g.track;
121
+ g.track = undefined;
122
+ try {
123
+ return fn();
124
+ } finally {
125
+ g.track = previous;
126
+ }
127
+ }
128
+ function recompute(g, n) {
129
+ const def = n.def;
130
+ const next = new Map;
131
+ const previous = g.track;
132
+ g.track = next;
133
+ let value;
134
+ try {
135
+ value = withClient(g.client, () => def.fn((d) => read(g, d)));
136
+ } finally {
137
+ g.track = previous;
138
+ }
139
+ if (n.refs > 0) {
140
+ for (const d of next.keys())
141
+ if (!n.deps.has(d)) {
142
+ d.observers.add(n);
143
+ retain(d);
144
+ }
145
+ for (const d of n.deps.keys())
146
+ if (!next.has(d)) {
147
+ d.observers.delete(n);
148
+ release(d);
149
+ }
150
+ }
151
+ n.deps = next;
152
+ if (!n.init || !def.equals(n.value, value)) {
153
+ n.value = value;
154
+ n.ver++;
155
+ n.init = true;
156
+ }
157
+ }
158
+ function refresh(g, n) {
159
+ if (n.def.kind === "signal" || n.stamp === g.epoch)
160
+ return;
161
+ if (n.busy)
162
+ throw new RivaError2("RIVA_CYCLE", `Cycle detected: computed ${n.def.name ?? "(anonymous)"} reads itself.`);
163
+ const epoch = g.epoch;
164
+ n.busy = true;
165
+ try {
166
+ let stale = !n.init;
167
+ if (!stale)
168
+ for (const [d, v] of n.deps) {
169
+ refresh(g, d);
170
+ if (d.ver !== v) {
171
+ stale = true;
172
+ break;
173
+ }
174
+ }
175
+ if (stale)
176
+ recompute(g, n);
177
+ n.stamp = epoch;
178
+ } finally {
179
+ n.busy = false;
180
+ }
181
+ }
182
+ function read(g, def) {
183
+ const n = nodeOf(g, def);
184
+ refresh(g, n);
185
+ g.track?.set(n, n.ver);
186
+ return n.value;
187
+ }
188
+ var settle = (g) => flush(g, refresh);
189
+ function write(g, def, value) {
190
+ const n = nodeOf(g, def);
191
+ const next = typeof value === "function" ? value(n.value) : value;
192
+ if (def.equals(n.value, next))
193
+ return;
194
+ n.value = next;
195
+ n.ver++;
196
+ g.epoch++;
197
+ collect(g, n);
198
+ settle(g);
199
+ }
200
+ function subscribe(g, def, listener) {
201
+ const n = nodeOf(g, def);
202
+ if (n.listeners.size === 0)
203
+ refresh(g, n);
204
+ if (n.listeners.size === 0)
205
+ n.seen = n.ver;
206
+ const entry = listener;
207
+ const own = (v) => entry(v);
208
+ n.listeners.add(own);
209
+ retain(n);
210
+ const off = () => {
211
+ if (!n.listeners.delete(own))
212
+ return;
213
+ release(n);
214
+ };
215
+ if (n.def.kind === "computed" && n.stamp !== g.epoch) {
216
+ g.pending.add(n);
217
+ try {
218
+ settle(g);
219
+ } catch (e) {
220
+ off();
221
+ throw e;
222
+ }
223
+ }
224
+ return off;
225
+ }
226
+ function batch2(g, fn) {
227
+ g.depth++;
228
+ let result;
229
+ try {
230
+ result = fn();
231
+ } catch (e) {
232
+ g.depth--;
233
+ try {
234
+ settle(g);
235
+ } catch (flushError) {
236
+ if (typeof e === "object" && e !== null && Object.isExtensible(e) && !("cause" in e))
237
+ Object.defineProperty(e, "cause", {
238
+ value: flushError,
239
+ configurable: true,
240
+ writable: true
241
+ });
242
+ }
243
+ throw e;
244
+ }
245
+ g.depth--;
246
+ settle(g);
247
+ return result;
248
+ }
249
+
250
+ export { createGraph, nodeOf, untracked2, read, write, subscribe, batch2 };
251
+
252
+ //# debugId=F76F237F85F017E164756E2164756E21
253
+ //# sourceMappingURL=index-e4vzsfy1.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/flush.ts", "../src/graph.ts"],
4
+ "sourcesContent": [
5
+ "import { RivaError } from './errors';\nimport type { Graph, Node } from './graph';\nimport { withClient } from './scope';\n\nconst MAX_RUNS = 100;\n\n/** Queues every node with listeners reachable from `n`: each node once, no recursion. */\nexport function collect(g: Graph, n: Node): void {\n\tconst seen = new Set([n]);\n\tconst stack = [n];\n\tfor (let x = stack.pop(); x; x = stack.pop()) {\n\t\tif (x.listeners.size > 0) g.pending.add(x);\n\t\tfor (const o of x.observers)\n\t\t\tif (!seen.has(o)) {\n\t\t\t\tseen.add(o);\n\t\t\t\tstack.push(o);\n\t\t\t}\n\t}\n}\n\n/**\n * Notifies the queued nodes' listeners, each in its own client. Every\n * notification runs; errors are collected and rethrown after (one as is,\n * several as an AggregateError). A node re-running over 100 times in one\n * flush is a loop.\n */\nexport function flush(g: Graph, refresh: (g: Graph, n: Node) => void): void {\n\tif (g.depth > 0 || g.flushing) return;\n\tg.flushing = true;\n\tconst errors: unknown[] = [];\n\tconst runs = new Map<Node, number>();\n\ttry {\n\t\twhile (g.pending.size > 0) {\n\t\t\tconst queue = [...g.pending];\n\t\t\tg.pending.clear();\n\t\t\tfor (const n of queue) {\n\t\t\t\tconst count = (runs.get(n) ?? 0) + 1;\n\t\t\t\truns.set(n, count);\n\t\t\t\tif (count > MAX_RUNS) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\tnew RivaError(\n\t\t\t\t\t\t\t'RIVA_LOOP',\n\t\t\t\t\t\t\tn.def.name\n\t\t\t\t\t\t\t\t? `Loop detected: ${n.def.name} re-ran more than ${MAX_RUNS} times in one flush.`\n\t\t\t\t\t\t\t\t: `Loop detected: a node re-ran more than ${MAX_RUNS} times in one flush; name it with { name } to find it.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\trefresh(g, n);\n\t\t\t\t\t// It wrote a source of its own while running: check it again.\n\t\t\t\t\tif (n.def.kind === 'computed' && n.stamp !== g.epoch)\n\t\t\t\t\t\tg.pending.add(n);\n\t\t\t\t\tif (n.ver === n.seen) continue;\n\t\t\t\t\tn.seen = n.ver;\n\t\t\t\t\tfor (const l of [...n.listeners])\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\twithClient(g.client, () => l(n.value));\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\terrors.push(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tg.flushing = false;\n\t}\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1)\n\t\tthrow new AggregateError(errors, 'Several listeners or computeds threw.');\n}\n",
6
+ "import type { RivaClient } from './client';\nimport type { Computed, Readable } from './computed';\nimport { RivaError } from './errors';\nimport { collect, flush } from './flush';\nimport { withClient } from './scope';\nimport type { Listener, Signal } from './signal';\n\ntype Def = Signal<unknown> | Computed<unknown>;\n\n/** The per-client node of a definition: its value and its links. */\nexport interface Node {\n\tdef: Def;\n\tvalue: unknown;\n\t/** Bumped each time the value changes. */\n\tver: number;\n\t/** The graph epoch this computed was last verified at. */\n\tstamp: number;\n\t/** Live observers plus listeners: links to sources exist only while > 0. */\n\trefs: number;\n\tobservers: Set<Node>;\n\t/** Sources read by the last evaluation, with the version seen. */\n\tdeps: Map<Node, number>;\n\tlisteners: Set<Listener<unknown>>;\n\tseen: number;\n\tbusy: boolean;\n\tinit: boolean;\n}\n\nexport interface Graph {\n\tclient: RivaClient;\n\tnodes: WeakMap<Def, Node>;\n\t/** Bumped on every write: a computed verified at this epoch is fresh. */\n\tepoch: number;\n\ttrack: Map<Node, number> | undefined;\n\tdepth: number;\n\tflushing: boolean;\n\tpending: Set<Node>;\n\t/** The signals that travel in an SSR snapshot, by name; null once a name is taken twice. @internal */\n\tnamed: Map<string, Node | null>;\n\t/** Values of hydrated signals not created yet, by name. @internal */\n\tseeds?: Map<string, unknown>;\n}\n\nexport const createGraph = (client: RivaClient): Graph => ({\n\tclient,\n\tnodes: new WeakMap(),\n\tepoch: 0,\n\ttrack: undefined,\n\tdepth: 0,\n\tflushing: false,\n\tpending: new Set(),\n\tnamed: new Map(),\n});\n\n/** A signal's first value: what a snapshot seeded for its name, else its initial. */\nfunction initialOf(g: Graph, def: Signal<unknown>): unknown {\n\tconst { name } = def;\n\treturn def.ssr && name !== undefined && g.seeds?.has(name)\n\t\t? g.seeds.get(name)\n\t\t: def.initial;\n}\n\nexport function nodeOf(g: Graph, def: Def): Node {\n\tlet n = g.nodes.get(def);\n\tif (!n) {\n\t\tconst isSignal = def.kind === 'signal';\n\t\tn = {\n\t\t\tdef,\n\t\t\tvalue: isSignal ? initialOf(g, def) : undefined,\n\t\t\tver: 0,\n\t\t\tstamp: -1,\n\t\t\trefs: 0,\n\t\t\tobservers: new Set(),\n\t\t\tdeps: new Map(),\n\t\t\tlisteners: new Set(),\n\t\t\tseen: 0,\n\t\t\tbusy: false,\n\t\t\tinit: isSignal,\n\t\t};\n\t\tg.nodes.set(def, n);\n\t\tif (isSignal && def.ssr && def.name !== undefined)\n\t\t\tg.named.set(def.name, g.named.has(def.name) ? null : n);\n\t}\n\treturn n;\n}\n\nfunction retain(n: Node): void {\n\tif (n.refs++ === 0)\n\t\tfor (const d of n.deps.keys()) {\n\t\t\td.observers.add(n);\n\t\t\tretain(d);\n\t\t}\n}\n\nfunction release(n: Node): void {\n\tif (--n.refs === 0)\n\t\tfor (const d of n.deps.keys()) {\n\t\t\td.observers.delete(n);\n\t\t\trelease(d);\n\t\t}\n}\n\nexport function untracked<R>(g: Graph, fn: () => R): R {\n\tconst previous = g.track;\n\tg.track = undefined;\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tg.track = previous;\n\t}\n}\n\nfunction recompute(g: Graph, n: Node): void {\n\tconst def = n.def as Computed<unknown>;\n\tconst next = new Map<Node, number>();\n\tconst previous = g.track;\n\tg.track = next;\n\tlet value: unknown;\n\ttry {\n\t\tvalue = withClient(g.client, () =>\n\t\t\tdef.fn((d) => read(g, d as Readable<never>)),\n\t\t);\n\t} finally {\n\t\tg.track = previous;\n\t}\n\tif (n.refs > 0) {\n\t\tfor (const d of next.keys())\n\t\t\tif (!n.deps.has(d)) {\n\t\t\t\td.observers.add(n);\n\t\t\t\tretain(d);\n\t\t\t}\n\t\tfor (const d of n.deps.keys())\n\t\t\tif (!next.has(d)) {\n\t\t\t\td.observers.delete(n);\n\t\t\t\trelease(d);\n\t\t\t}\n\t}\n\tn.deps = next;\n\tif (!n.init || !def.equals(n.value, value)) {\n\t\tn.value = value;\n\t\tn.ver++;\n\t\tn.init = true;\n\t}\n}\n\n/** Brings a computed up to date, re-evaluating only when a source changed. */\nexport function refresh(g: Graph, n: Node): void {\n\tif (n.def.kind === 'signal' || n.stamp === g.epoch) return;\n\tif (n.busy)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_CYCLE',\n\t\t\t`Cycle detected: computed ${n.def.name ?? '(anonymous)'} reads itself.`,\n\t\t);\n\tconst epoch = g.epoch;\n\tn.busy = true;\n\ttry {\n\t\tlet stale = !n.init;\n\t\tif (!stale)\n\t\t\tfor (const [d, v] of n.deps) {\n\t\t\t\trefresh(g, d);\n\t\t\t\tif (d.ver !== v) {\n\t\t\t\t\tstale = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\tif (stale) recompute(g, n);\n\t\t// The epoch from before the run: a write the node made itself is rechecked.\n\t\tn.stamp = epoch;\n\t} finally {\n\t\tn.busy = false;\n\t}\n}\n\nexport function read<T>(g: Graph, def: Readable<T>): T {\n\tconst n = nodeOf(g, def as Def);\n\trefresh(g, n);\n\tg.track?.set(n, n.ver);\n\treturn n.value as T;\n}\n\nconst settle = (g: Graph): void => flush(g, refresh);\n\nexport function write<T>(\n\tg: Graph,\n\tdef: Signal<T>,\n\tvalue: T | ((prev: T) => T),\n): void {\n\tconst n = nodeOf(g, def as Def);\n\tconst next =\n\t\ttypeof value === 'function'\n\t\t\t? (value as (prev: T) => T)(n.value as T)\n\t\t\t: value;\n\tif (def.equals(n.value as T, next)) return;\n\tn.value = next;\n\tn.ver++;\n\tg.epoch++;\n\tcollect(g, n);\n\tsettle(g);\n}\n\nexport function subscribe<T>(\n\tg: Graph,\n\tdef: Readable<T>,\n\tlistener: Listener<T>,\n): () => void {\n\tconst n = nodeOf(g, def as Def);\n\tif (n.listeners.size === 0) refresh(g, n);\n\tif (n.listeners.size === 0) n.seen = n.ver;\n\tconst entry = listener as Listener<unknown>;\n\tconst own: Listener<unknown> = (v) => entry(v);\n\tn.listeners.add(own);\n\tretain(n);\n\tconst off = () => {\n\t\tif (!n.listeners.delete(own)) return;\n\t\trelease(n);\n\t};\n\t// A node that wrote its own source while evaluating is not fresh yet.\n\tif (n.def.kind === 'computed' && n.stamp !== g.epoch) {\n\t\tg.pending.add(n);\n\t\ttry {\n\t\t\tsettle(g);\n\t\t} catch (e) {\n\t\t\toff();\n\t\t\tthrow e;\n\t\t}\n\t}\n\treturn off;\n}\n\nexport function batch<R>(g: Graph, fn: () => R): R {\n\tg.depth++;\n\tlet result: R;\n\ttry {\n\t\tresult = fn();\n\t} catch (e) {\n\t\tg.depth--;\n\t\ttry {\n\t\t\tsettle(g);\n\t\t} catch (flushError) {\n\t\t\tif (\n\t\t\t\ttypeof e === 'object' &&\n\t\t\t\te !== null &&\n\t\t\t\tObject.isExtensible(e) &&\n\t\t\t\t!('cause' in e)\n\t\t\t)\n\t\t\t\tObject.defineProperty(e, 'cause', {\n\t\t\t\t\tvalue: flushError,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t}\n\t\tthrow e;\n\t}\n\tg.depth--;\n\tsettle(g);\n\treturn result;\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;AAIA,IAAM,WAAW;AAGV,SAAS,OAAO,CAAC,GAAU,GAAe;AAAA,EAChD,MAAM,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC;AAAA,EACxB,MAAM,QAAQ,CAAC,CAAC;AAAA,EAChB,SAAS,IAAI,MAAM,IAAI,EAAG,GAAG,IAAI,MAAM,IAAI,GAAG;AAAA,IAC7C,IAAI,EAAE,UAAU,OAAO;AAAA,MAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACzC,WAAW,KAAK,EAAE;AAAA,MACjB,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG;AAAA,QACjB,KAAK,IAAI,CAAC;AAAA,QACV,MAAM,KAAK,CAAC;AAAA,MACb;AAAA,EACF;AAAA;AASM,SAAS,KAAK,CAAC,GAAU,SAA4C;AAAA,EAC3E,IAAI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{
2
+ nodeOf
3
+ } from "./index-e4vzsfy1.js";
4
+ import {
5
+ stableKey2
6
+ } from "./index-vz93xwnj.js";
7
+ import {
8
+ computed2
9
+ } from "./index-5xnfwj57.js";
10
+ import {
11
+ isBrowser,
12
+ signal2
13
+ } from "./index-y6bzw104.js";
14
+ import {
15
+ RivaError2
16
+ } from "./index-2g2s3y31.js";
17
+
18
+ // src/query-entry.ts
19
+ var IDLE = Object.freeze({
20
+ status: "idle",
21
+ data: undefined,
22
+ error: undefined,
23
+ isFetching: false,
24
+ updatedAt: 0
25
+ });
26
+ var peek = (c, e) => nodeOf(c.client.graph, e.signal).value;
27
+ var view = (c, e) => c.client.untracked(() => c.client.get(e.out));
28
+ var committed = (c, e) => c.client.untracked(() => {
29
+ const d = peek(c, e).data;
30
+ const cache = e.def.options.cache;
31
+ return cache && d !== undefined ? cache.read(c.client, d, true) : d;
32
+ });
33
+ var unreadable = (c, e) => peek(c, e).data !== undefined && committed(c, e) === undefined;
34
+ var INCOMPLETE = "The cache cannot read the query's data after a fetch.";
35
+ var toStored = (c, e, data) => {
36
+ const cache = e.def.options.cache;
37
+ return cache && data !== undefined ? cache.write(c.client, data, peek(c, e).data, e.vars) : data;
38
+ };
39
+ function putStored(c, e, patch) {
40
+ const cache = e.def.options.cache;
41
+ const prev = peek(c, e).data;
42
+ put(c, e, patch);
43
+ if (cache && "data" in patch && prev !== undefined && prev !== patch.data)
44
+ cache.release(c.client, prev);
45
+ }
46
+ function putData(c, e, patch) {
47
+ if (!e.def.options.cache || !("data" in patch))
48
+ return void put(c, e, patch);
49
+ let error;
50
+ c.client.batch(() => {
51
+ try {
52
+ putStored(c, e, { ...patch, data: toStored(c, e, patch.data) });
53
+ } catch (x) {
54
+ error = x;
55
+ const { data: _, ...rest } = patch;
56
+ put(c, e, { ...rest, status: "error", error: x });
57
+ }
58
+ });
59
+ return error;
60
+ }
61
+ var put = (c, e, patch) => c.client.set(e.signal, { ...peek(c, e), ...patch });
62
+ var stale = (c, e, staleTime = e.def.options.staleTime) => peek(c, e).status !== "success" || e.invalidated || c.sched.now() - peek(c, e).updatedAt >= staleTime || unreadable(c, e);
63
+ function armGc(c, e) {
64
+ c.sched.clearTimeout(e.gc);
65
+ e.gc = undefined;
66
+ const ms = e.def.options.gcTime ?? (isBrowser() ? 300000 : Infinity);
67
+ if (e.observers || ms === Infinity)
68
+ return;
69
+ e.gc = c.sched.setTimeout(() => {
70
+ e.gc = undefined;
71
+ if (e.observers || e.run || nodeOf(c.client.graph, e.signal).refs || nodeOf(c.client.graph, e.lay).value.length)
72
+ return armGc(c, e);
73
+ if (c.entries.get(e.key) !== e)
74
+ return;
75
+ c.entries.delete(e.key);
76
+ const stored = peek(c, e).data;
77
+ if (stored !== undefined)
78
+ e.def.options.cache?.release(c.client, stored);
79
+ }, ms);
80
+ }
81
+ var sameState = (a, b) => {
82
+ const k = Object.keys(a);
83
+ return k.length === Object.keys(b).length && k.every((x) => a[x] === b[x]);
84
+ };
85
+ function entryOf(c, def, vars) {
86
+ const { client } = c;
87
+ const key = stableKey2(def.id, vars);
88
+ let e = c.entries.get(key);
89
+ if (e && e.def.options !== def.options) {
90
+ if (!isBrowser() || e.was === def.options)
91
+ throw new RivaError2("RIVA_KEY", `Two definitions share the id "${def.id}": define each query once (a module-level const) and import it, or pass a distinct id.`);
92
+ const d = peek(c, e).data;
93
+ if (d !== undefined)
94
+ e.def.options.cache?.release(client, d);
95
+ e.was = e.def.options;
96
+ e.def = def;
97
+ put(c, e, IDLE);
98
+ }
99
+ if (!e) {
100
+ const a = signal2(IDLE, { name: key });
101
+ const lay = signal2([], { name: `${key}#layers` });
102
+ const n = {
103
+ key,
104
+ def,
105
+ vars,
106
+ signal: a,
107
+ lay,
108
+ out: computed2((get) => {
109
+ const s = get(a);
110
+ const ls = get(lay);
111
+ const { cache, derive } = n.def.options;
112
+ if (!cache && !ls.length && !derive)
113
+ return s;
114
+ let data = cache && s.data !== undefined ? cache.read(client, s.data) : s.data;
115
+ for (const l of ls)
116
+ data = l(data);
117
+ const out = { ...s, data };
118
+ return derive ? derive(client, out, vars) : out;
119
+ }, { equals: sameState, name: key }),
120
+ observers: 0,
121
+ invalidated: false,
122
+ run: undefined,
123
+ gc: undefined,
124
+ poll: undefined
125
+ };
126
+ e = n;
127
+ c.entries.set(key, e);
128
+ c.seed?.(c, e);
129
+ armGc(c, e);
130
+ }
131
+ return e;
132
+ }
133
+
134
+ export { peek, view, committed, unreadable, INCOMPLETE, toStored, putStored, putData, put, stale, armGc, entryOf };
135
+
136
+ //# debugId=C4F54D92110AF17364756E2164756E21
137
+ //# sourceMappingURL=index-tn8ankny.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/query-entry.ts"],
4
+ "sourcesContent": [
5
+ "import type { RivaClient } from './client';\nimport { computed, type Readable } from './computed';\nimport type { ClientEvents, Scheduler } from './env';\nimport { RivaError } from './errors';\nimport { nodeOf } from './graph';\nimport { stableKey } from './key';\nimport type { Query, QueryState } from './query';\nimport { isBrowser } from './scope';\nimport { type Signal, signal } from './signal';\nimport type { SeedEntry } from './ssr/hydrate';\n\n// biome-ignore lint/suspicious/noExplicitAny: entries of every definition share one map\nexport type AnyQuery = Query<any, any>;\nexport type State = QueryState<unknown>;\n\nexport interface Inflight {\n\tpromise: Promise<unknown>;\n\t/** Replaced on a restart (invalidate while in flight); aborted and kept on a cancel. */\n\tctl: AbortController;\n\twaiters: number;\n\t/** Started by a prefetch, a poll or a refetch: a caller abort never cancels it. */\n\tpinned: boolean;\n\t/** Set by `setData`: the waiters resolve with it instead of rejecting. */\n\tset: { v: unknown } | undefined;\n\t/** The state to restore on cancel. */\n\tprev: State;\n}\n\n/** An optimistic write: maps the value below it to the value readers see. */\nexport type Lay = (prev: unknown) => unknown;\n\nexport interface Entry {\n\tkey: string;\n\tdef: AnyQuery;\n\t/** The definition a hot reload replaced: seen again, the id is shared. */\n\twas?: AnyQuery['options'];\n\tvars: unknown;\n\t/** The graph signal holding the state: the one notification mechanism. */\n\tsignal: Signal<State>;\n\t/** The optimistic layers over the signal's data, oldest first. */\n\tlay: Signal<Lay[]>;\n\t/** What readers see: the signal's data through the cache policy, under the layers. */\n\tout: Readable<State>;\n\tobservers: number;\n\tinvalidated: boolean;\n\trun: Inflight | undefined;\n\tgc: unknown;\n\tpoll: unknown;\n}\n\n/** What one client's query cache shares between its files. */\nexport interface Ctx {\n\tclient: RivaClient;\n\tsched: Scheduler;\n\tevents: ClientEvents;\n\tentries: Map<string, Entry>;\n\t/** Observers over every entry, to attach the window events once. */\n\tobserved: number;\n\tdetach: (() => void) | undefined;\n\t/** Called on a new entry: `@softistx/riva/ssr` seeds it from a snapshot. @internal */\n\tseed?: (c: Ctx, e: Entry) => void;\n\t/** Snapshot entries waiting for their entry, by key. @internal */\n\tpending?: Map<string, SeedEntry>;\n}\n\nconst IDLE: State = Object.freeze({\n\tstatus: 'idle',\n\tdata: undefined,\n\terror: undefined,\n\tisFetching: false,\n\tupdatedAt: 0,\n});\n\n/** The current state, untracked. */\nexport const peek = (c: Ctx, e: Entry): State =>\n\tnodeOf(c.client.graph, e.signal).value as State;\n\n/** The state as readers see it (data read through the cache policy), untracked. */\nexport const view = (c: Ctx, e: Entry): State =>\n\tc.client.untracked(() => c.client.get(e.out));\n\n/** The data without the entry's own layers, untracked. */\nexport const committed = (c: Ctx, e: Entry): unknown =>\n\tc.client.untracked(() => {\n\t\tconst d = peek(c, e).data;\n\t\tconst cache = e.def.options.cache;\n\t\treturn cache && d !== undefined ? cache.read(c.client, d, true) : d;\n\t});\n\n/** Data is stored that the cache policy cannot read: an evicted entity, a field the server left out. */\nexport const unreadable = (c: Ctx, e: Entry): boolean =>\n\tpeek(c, e).data !== undefined && committed(c, e) === undefined;\n\n/** The message of the error of a fetch whose data the cache cannot read back. */\nexport const INCOMPLETE =\n\t\"The cache cannot read the query's data after a fetch.\";\n\n/** The data as the entry stores it: through the cache policy, which may refuse it by throwing. */\nexport const toStored = (c: Ctx, e: Entry, data: unknown): unknown => {\n\tconst cache = e.def.options.cache;\n\treturn cache && data !== undefined\n\t\t? cache.write(c.client, data, peek(c, e).data, e.vars)\n\t\t: data;\n};\n\n/** Writes a patch whose `data` is already stored, then releases the data it replaced. */\nexport function putStored(c: Ctx, e: Entry, patch: Partial<State>): void {\n\tconst cache = e.def.options.cache;\n\tconst prev = peek(c, e).data;\n\tput(c, e, patch);\n\tif (cache && 'data' in patch && prev !== undefined && prev !== patch.data)\n\t\tcache.release(c.client, prev);\n}\n\n/**\n * Writes a patch that may carry new data, through the cache policy. A policy\n * that refuses the data leaves the old data and sets the error state; the\n * error is returned.\n */\nexport function putData(c: Ctx, e: Entry, patch: Partial<State>): unknown {\n\tif (!e.def.options.cache || !('data' in patch)) return void put(c, e, patch);\n\tlet error: unknown;\n\tc.client.batch(() => {\n\t\ttry {\n\t\t\tputStored(c, e, { ...patch, data: toStored(c, e, patch.data) });\n\t\t} catch (x) {\n\t\t\terror = x;\n\t\t\tconst { data: _, ...rest } = patch;\n\t\t\tput(c, e, { ...rest, status: 'error', error: x });\n\t\t}\n\t});\n\treturn error;\n}\n\n/** Writes a patch over the current state (one notification). */\nexport const put = (c: Ctx, e: Entry, patch: Partial<State>): void =>\n\tc.client.set(e.signal, { ...peek(c, e), ...patch });\n\n/** Whether the entry must be fetched: not a success, invalidated, or older than `staleTime`. */\nexport const stale = (\n\tc: Ctx,\n\te: Entry,\n\tstaleTime: number = e.def.options.staleTime,\n): boolean =>\n\tpeek(c, e).status !== 'success' ||\n\te.invalidated ||\n\tc.sched.now() - peek(c, e).updatedAt >= staleTime ||\n\tunreadable(c, e);\n\n/** Schedules the removal of an unobserved entry after `gcTime` (never on the server by default). */\nexport function armGc(c: Ctx, e: Entry): void {\n\tc.sched.clearTimeout(e.gc);\n\te.gc = undefined;\n\tconst ms = e.def.options.gcTime ?? (isBrowser() ? 300_000 : Infinity);\n\tif (e.observers || ms === Infinity) return;\n\te.gc = c.sched.setTimeout(() => {\n\t\te.gc = undefined;\n\t\t// A computed or listener still reading the signal keeps the entry alive.\n\t\tif (\n\t\t\te.observers ||\n\t\t\te.run ||\n\t\t\tnodeOf(c.client.graph, e.signal).refs ||\n\t\t\t(nodeOf(c.client.graph, e.lay).value as Lay[]).length\n\t\t)\n\t\t\treturn armGc(c, e);\n\t\tif (c.entries.get(e.key) !== e) return;\n\t\tc.entries.delete(e.key);\n\t\tconst stored = peek(c, e).data;\n\t\tif (stored !== undefined) e.def.options.cache?.release(c.client, stored);\n\t}, ms);\n}\n\n/** Shallow: the standard fields and whatever `derive` adds. */\nconst sameState = (a: State, b: State): boolean => {\n\tconst k = Object.keys(a) as Array<keyof State>;\n\treturn k.length === Object.keys(b).length && k.every((x) => a[x] === b[x]);\n};\n\nexport function entryOf(c: Ctx, def: AnyQuery, vars: unknown): Entry {\n\tconst { client } = c;\n\tconst key = stableKey(def.id, vars);\n\tlet e = c.entries.get(key);\n\tif (e && e.def.options !== def.options) {\n\t\t// Another definition under this id (a wrapper such as infinite() shares\n\t\t// its query's options, so it is the same definition): refused on the server, taken over by\n\t\t// the newest in a browser (a hot-reloaded module).\n\t\tif (!isBrowser() || e.was === def.options)\n\t\t\tthrow new RivaError(\n\t\t\t\t'RIVA_KEY',\n\t\t\t\t`Two definitions share the id \"${def.id}\": define each query once (a module-level const) and import it, or pass a distinct id.`,\n\t\t\t);\n\t\t// Drop what the old policy stored: the new one reads only its own data.\n\t\tconst d = peek(c, e).data;\n\t\tif (d !== undefined) e.def.options.cache?.release(client, d);\n\t\te.was = e.def.options;\n\t\te.def = def;\n\t\tput(c, e, IDLE);\n\t}\n\tif (!e) {\n\t\tconst a = signal<State>(IDLE, { name: key });\n\t\tconst lay = signal<Lay[]>([], { name: `${key}#layers` });\n\t\tconst n: Entry = {\n\t\t\tkey,\n\t\t\tdef,\n\t\t\tvars,\n\t\t\tsignal: a,\n\t\t\tlay,\n\t\t\tout: computed(\n\t\t\t\t(get) => {\n\t\t\t\t\tconst s = get(a);\n\t\t\t\t\tconst ls = get(lay);\n\t\t\t\t\tconst { cache, derive } = n.def.options;\n\t\t\t\t\tif (!cache && !ls.length && !derive) return s;\n\t\t\t\t\tlet data =\n\t\t\t\t\t\tcache && s.data !== undefined ? cache.read(client, s.data) : s.data;\n\t\t\t\t\tfor (const l of ls) data = l(data);\n\t\t\t\t\tconst out = { ...s, data };\n\t\t\t\t\treturn derive ? (derive(client, out, vars) as State) : out;\n\t\t\t\t},\n\t\t\t\t{ equals: sameState, name: key },\n\t\t\t),\n\t\t\tobservers: 0,\n\t\t\tinvalidated: false,\n\t\t\trun: undefined,\n\t\t\tgc: undefined,\n\t\t\tpoll: undefined,\n\t\t};\n\t\te = n;\n\t\tc.entries.set(key, e);\n\t\tc.seed?.(c, e);\n\t\tarmGc(c, e);\n\t}\n\treturn e;\n}\n\nexport type { QueryState };\n"
6
+ ],
7
+ "mappings": ";;;;;;;;;;;;;;;;;;AAiEA,IAAM,OAAc,OAAO,OAAO;AAAA,EACjC,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,WAAW;AACZ,CAAC;AAGM,IAAM,OAAO,CAAC,GAAQ,MAC5B,OAAO,EAAE,OAAO,OAAO,EAAE,MAAM,EAAE;AAG3B,IAAM,OAAO,CAAC,GAAQ,MAC5B,EAAE,OAAO,UAAU,MAAM,EAAE,OAAO,IAAI,EAAE,GAAG,CAAC;AAGtC,IAAM,YAAY,CAAC,GAAQ,MACjC,EAAE,OAAO,UAAU,MAAM;AAAA,EACxB,MAAM,IAAI,KAAK,GAAG,CAAC,EAAE;AAAA,EACrB,MAAM,QAAQ,EAAE,IAAI,QAAQ;AAAA,EAC5B,OAAO,SAAS,MAAM,YAAY,MAAM,KAAK,EAAE,QAAQ,GAAG,IAAI,IAAI;AAAA,CAClE;AAGK,IAAM,aAAa,CAAC,GAAQ,MAClC,KAAK,GAAG,CAAC,EAAE,SAAS,aAAa,UAAU,GAAG,CAAC,MAAM;AAG/C,IAAM,aACZ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AI;AAAA,IACJ,EAAE,QAAQ,IAAI,KAAK,CAAC;AAAA,IACpB,EAAE,OAAO,GAAG,CAAC;AAAA,IACb,MAAM,GAAG,CAAC;AAAA,EACX;AAAA,EACA,OAAO;AAAA;",
8
+ "debugId": "C4F54D92110AF17364756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,35 @@
1
+ import {
2
+ RivaError2
3
+ } from "./index-2g2s3y31.js";
4
+
5
+ // src/key.ts
6
+ var bad = (what) => {
7
+ throw new RivaError2("RIVA_KEY", `Cannot derive a cache key: variables hold ${what}. Use JSON-like values.`);
8
+ };
9
+ function ser(v, path) {
10
+ if (v === undefined)
11
+ return;
12
+ if (v instanceof Date)
13
+ v = Number.isNaN(+v) ? bad("an invalid Date") : v.toISOString();
14
+ if (typeof v === "function" || typeof v === "symbol" || typeof v === "bigint")
15
+ bad(`a ${typeof v}`);
16
+ if (typeof v === "number" && !Number.isFinite(v))
17
+ bad(`the number ${v}`);
18
+ if (!v || typeof v !== "object")
19
+ return JSON.stringify(v);
20
+ if (path.includes(v))
21
+ bad("a circular reference");
22
+ path.push(v);
23
+ const out = Array.isArray(v) ? `[${v.map((x) => ser(x, path) ?? "null")}]` : `{${Object.keys(v).sort().flatMap((k) => {
24
+ const s = ser(v[k], path);
25
+ return s === undefined ? [] : `${JSON.stringify(k)}:${s}`;
26
+ })}}`;
27
+ path.pop();
28
+ return out;
29
+ }
30
+ var stableKey2 = (id, vars) => `${id}:${ser(vars, []) ?? ""}`;
31
+
32
+ export { stableKey2 };
33
+
34
+ //# debugId=2CAF9A36BA8268F064756E2164756E21
35
+ //# sourceMappingURL=index-vz93xwnj.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/key.ts"],
4
+ "sourcesContent": [
5
+ "import { RivaError } from './errors';\n\nconst bad = (what: string): never => {\n\tthrow new RivaError(\n\t\t'RIVA_KEY',\n\t\t`Cannot derive a cache key: variables hold ${what}. Use JSON-like values.`,\n\t);\n};\n\nfunction ser(v: unknown, path: unknown[]): string | undefined {\n\tif (v === undefined) return;\n\tif (v instanceof Date)\n\t\tv = Number.isNaN(+v) ? bad('an invalid Date') : v.toISOString();\n\tif (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint')\n\t\tbad(`a ${typeof v}`);\n\tif (typeof v === 'number' && !Number.isFinite(v)) bad(`the number ${v}`);\n\tif (!v || typeof v !== 'object') return JSON.stringify(v);\n\tif (path.includes(v)) bad('a circular reference');\n\tpath.push(v);\n\tconst out = Array.isArray(v)\n\t\t? `[${v.map((x) => ser(x, path) ?? 'null')}]`\n\t\t: `{${Object.keys(v)\n\t\t\t\t.sort()\n\t\t\t\t.flatMap((k) => {\n\t\t\t\t\tconst s = ser((v as Record<string, unknown>)[k], path);\n\t\t\t\t\treturn s === undefined ? [] : `${JSON.stringify(k)}:${s}`;\n\t\t\t\t})}}`;\n\tpath.pop();\n\treturn out;\n}\n\n/** The cache key of a definition id and its variables: stable whatever the order of object keys. */\nexport const stableKey = (id: string, vars: unknown): string =>\n\t`${id}:${ser(vars, []) ?? ''}`;\n"
6
+ ],
7
+ "mappings": ";;;;;AAEA,IAAM,MAAM,CAAC,SAAwB;AAAA,EACpC,MAAM,IAAI,WACT,YACA,6CAA6C,6BAC9C;AAAA;AAGD,SAAS,GAAG,CAAC,GAAY,MAAqC;AAAA,EAC7D,IAAI,MAAM;AAAA,IAAW;AAAA,EACrB,IAAI,aAAa;AAAA,IAChB,IAAI,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI,iBAAiB,IAAI,EAAE,YAAY;AAAA,EAC/D,IAAI,OAAO,MAAM,cAAc,OAAO,MAAM,YAAY,OAAO,MAAM;AAAA,IACpE,IAAI,KAAK,OAAO,GAAG;AAAA,EACpB,IAAI,OAAO,MAAM,YAAY,CAAC,OAAO,SAAS,CAAC;AAAA,IAAG,IAAI,cAAc,GAAG;AAAA,EACvE,IAAI,CAAC,KAAK,OAAO,MAAM;AAAA,IAAU,OAAO,KAAK,UAAU,CAAC;AAAA,EACxD,IAAI,KAAK,SAAS,CAAC;AAAA,IAAG,IAAI,sBAAsB;AAAA,EAChD,KAAK,KAAK,CAAC;AAAA,EACX,MAAM,MAAM,MAAM,QAAQ,CAAC,IACxB,IAAI,EAAE,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,KAAK,MAAM,OACvC,IAAI,OAAO,KAAK,CAAC,EAChB,KAAK,EACL,QAAQ,CAAC,MAAM;AAAA,IACf,MAAM,IAAI,IAAK,EAA8B,IAAI,IAAI;AAAA,IACrD,OAAO,MAAM,YAAY,CAAC,IAAI,GAAG,KAAK,UAAU,CAAC,KAAK;AAAA,GACtD;AAAA,EACJ,KAAK,IAAI;AAAA,EACT,OAAO;AAAA;AAID,IAAM,aAAY,CAAC,IAAY,SACrC,GAAG,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;",
8
+ "debugId": "2CAF9A36BA8268F064756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,53 @@
1
+ import {
2
+ RivaScopeError2
3
+ } from "./index-2g2s3y31.js";
4
+
5
+ // src/scope.ts
6
+ var current;
7
+ var fallback;
8
+ var isBrowser = () => ("document" in globalThis);
9
+ var active = () => current ?? resolver?.() ?? (isBrowser() ? fallback : undefined);
10
+ var resolver;
11
+ var setResolver = (fn) => {
12
+ resolver = fn;
13
+ };
14
+ function resolve() {
15
+ const client = active();
16
+ if (!client)
17
+ throw new RivaScopeError2("No RivaClient in scope: read through client.get(def), or wrap the code in client.run(() => …). On the server, use the per-request client.");
18
+ return client;
19
+ }
20
+ function withClient(client, fn) {
21
+ const previous = current;
22
+ current = client;
23
+ try {
24
+ return fn();
25
+ } finally {
26
+ current = previous;
27
+ }
28
+ }
29
+ function setDefaultClient2(client) {
30
+ if (!isBrowser())
31
+ throw new RivaScopeError2("setDefaultClient is browser-only: a module-level client on the server would leak state between requests. Use the per-request client with client.run(() => …).");
32
+ fallback = client;
33
+ }
34
+
35
+ // src/signal.ts
36
+ function signal2(initial, opts = {}) {
37
+ const def = Object.freeze({
38
+ kind: "signal",
39
+ initial,
40
+ name: opts.name,
41
+ ssr: opts.ssr ?? false,
42
+ equals: opts.equals ?? Object.is,
43
+ get: () => resolve().get(def),
44
+ set: (value) => resolve().set(def, value),
45
+ subscribe: (listener) => resolve().subscribe(def, listener)
46
+ });
47
+ return def;
48
+ }
49
+
50
+ export { isBrowser, active, setResolver, resolve, withClient, setDefaultClient2, signal2 };
51
+
52
+ //# debugId=2DF92AAB3ED192D464756E2164756E21
53
+ //# sourceMappingURL=index-y6bzw104.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/scope.ts", "../src/signal.ts"],
4
+ "sourcesContent": [
5
+ "import type { RivaClient } from './client';\nimport { RivaScopeError } from './errors';\n\n// Transient execution context (the client of the running `client.run`) and the\n// browser's default client. The server never holds a default: it would leak\n// between requests.\nlet current: RivaClient | undefined;\nlet fallback: RivaClient | undefined;\n\n/** Browser detection, in one place so tests can drive it through `globalThis.document`. */\nexport const isBrowser = (): boolean => 'document' in globalThis;\n\n/** The client in scope, if any. */\nexport const active = (): RivaClient | undefined =>\n\tcurrent ?? resolver?.() ?? (isBrowser() ? fallback : undefined);\n\nlet resolver: (() => RivaClient | undefined) | undefined;\n\n/** Sets the ambient resolver `@softistx/riva/ssr` exposes. @internal */\nexport const setResolver = (fn: typeof resolver): void => {\n\tresolver = fn;\n};\n\n/** The client in scope, or a `RivaScopeError` naming the fix. */\nexport function resolve(): RivaClient {\n\tconst client = active();\n\tif (!client)\n\t\tthrow new RivaScopeError(\n\t\t\t'No RivaClient in scope: read through client.get(def), or wrap the code in client.run(() => …). On the server, use the per-request client.',\n\t\t);\n\treturn client;\n}\n\n/** Runs `fn` with `client` as the ambient scope, restoring the previous one after. */\nexport function withClient<R>(client: RivaClient, fn: () => R): R {\n\tconst previous = current;\n\tcurrent = client;\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tcurrent = previous;\n\t}\n}\n\n/** Sets the browser's default client. Throws on the server. */\nexport function setDefaultClient(client: RivaClient | undefined): void {\n\tif (!isBrowser())\n\t\tthrow new RivaScopeError(\n\t\t\t'setDefaultClient is browser-only: a module-level client on the server would leak state between requests. Use the per-request client with client.run(() => …).',\n\t\t);\n\tfallback = client;\n}\n",
6
+ "import { resolve } from './scope';\n\nexport type Listener<T> = (value: T) => void;\nexport type Unsubscribe = () => void;\n\nexport interface SignalOptions<T> {\n\tname?: string;\n\tequals?: (a: T, b: T) => boolean;\n\t/** Whether the value travels in an SSR snapshot (it needs a `name` too). Default false: opt in. */\n\tssr?: boolean;\n}\n\n/** A stateless definition: it holds no value, a `RivaClient` does. */\nexport interface Signal<T> {\n\treadonly kind: 'signal';\n\treadonly initial: T;\n\treadonly name: string | undefined;\n\treadonly ssr: boolean;\n\tequals(a: T, b: T): boolean;\n\t/** Reads through the ambient client. */\n\tget(): T;\n\tset(value: NoInfer<T> | ((prev: T) => T)): void;\n\tsubscribe(listener: Listener<T>): Unsubscribe;\n}\n\nexport function signal<T>(initial: T, opts: SignalOptions<T> = {}): Signal<T> {\n\tconst def: Signal<T> = Object.freeze({\n\t\tkind: 'signal',\n\t\tinitial,\n\t\tname: opts.name,\n\t\tssr: opts.ssr ?? false,\n\t\tequals: opts.equals ?? Object.is,\n\t\tget: () => resolve().get(def),\n\t\tset: (value: T | ((prev: T) => T)) => resolve().set(def, value),\n\t\tsubscribe: (listener: Listener<T>) => resolve().subscribe(def, listener),\n\t});\n\treturn def;\n}\n"
7
+ ],
8
+ "mappings": ";;;;;AAMA,IAAI;AACJ,IAAI;AAGG,IAAM,YAAY,OAAe,cAAc;AAG/C,IAAM,SAAS,MACrB,WAAW,WAAW,MAAM,UAAU,IAAI,WAAW;AAEtD,IAAI;AAGG,IAAM,cAAc,CAAC,OAA8B;AAAA,EACzD,WAAW;AAAA;AAIL,SAAS,OAAO,GAAe;AAAA,EACrC,MAAM,SAAS,OAAO;AAAA,EACtB,IAAI,CAAC;AAAA,IACJ,MAAM,IAAI,gBACT,2IACD;AAAA,EACD,OAAO;AAAA;AAID,SAAS,UAAa,CAAC,QAAoB,IAAgB;AAAA,EACjE,MAAM,WAAW;AAAA,EACjB,UAAU;AAAA,EACV,IAAI;AAAA,IACH,OAAO,GAAG;AAAA,IACT,QAAQ;AAAA,IACT,UAAU;AAAA;AAAA;AAKL,SAAS,iBAAgB,CAAC,QAAsC;AAAA,EACtE,IAAI,CAAC,UAAU;AAAA,IACd,MAAM,IAAI,gBACT,+JACD;AAAA,EACD,WAAW;AAAA;;;ACzBL,SAAS,OAAS,CAAC,SAAY,OAAyB,CAAC,GAAc;AAAA,EAC7E,MAAM,MAAiB,OAAO,OAAO;AAAA,IACpC,MAAM;AAAA,IACN;AAAA,IACA,MAAM,KAAK;AAAA,IACX,KAAK,KAAK,OAAO;AAAA,IACjB,QAAQ,KAAK,UAAU,OAAO;AAAA,IAC9B,KAAK,MAAM,QAAQ,EAAE,IAAI,GAAG;AAAA,IAC5B,KAAK,CAAC,UAAgC,QAAQ,EAAE,IAAI,KAAK,KAAK;AAAA,IAC9D,WAAW,CAAC,aAA0B,QAAQ,EAAE,UAAU,KAAK,QAAQ;AAAA,EACxE,CAAC;AAAA,EACD,OAAO;AAAA;",
9
+ "debugId": "2DF92AAB3ED192D464756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,48 @@
1
+ import { type Readable } from './computed';
2
+ import { type Duration } from './duration';
3
+ import { type ClientEvents, type Scheduler } from './env';
4
+ import * as graph from './graph';
5
+ import type { Query, QueryState, VarsArgs } from './query';
6
+ import { type QueryCache } from './query-cache';
7
+ import type { Listener, Signal, Unsubscribe } from './signal';
8
+ export type EffectFn = () => void | (() => void);
9
+ export interface SubscribeOptions {
10
+ /**
11
+ * Replaces the definition's `staleTime` when this observer decides whether
12
+ * to fetch on subscribing. Later invalidations and polls are unaffected.
13
+ */
14
+ staleTime?: Duration;
15
+ }
16
+ export interface ClientOptions {
17
+ /** Timers and clock; defaults to the host's. Inject a fake in tests. */
18
+ scheduler?: Scheduler;
19
+ /** Focus and reconnect events; defaults to the browser's, nothing on the server. */
20
+ events?: ClientEvents;
21
+ }
22
+ /** Holds every value. One per request on the server, one in the browser. */
23
+ export declare class RivaClient {
24
+ /** @internal */
25
+ readonly graph: graph.Graph;
26
+ /** @internal */
27
+ readonly queries: QueryCache;
28
+ /** @internal Per-client state of opt-in modules, by their own key. */
29
+ readonly slots: Map<unknown, unknown>;
30
+ constructor(options?: ClientOptions);
31
+ /** A query's state: a pure read, tracked in a computed or effect, never fetches. */
32
+ get<Vars, Data, S extends QueryState<unknown>>(def: Query<Vars, Data, S>, ...vars: VarsArgs<Vars>): S;
33
+ get<T>(def: Readable<T>): T;
34
+ set<T>(def: Signal<T>, value: NoInfer<T> | ((prev: T) => T)): void;
35
+ /** Observes a query: fetches when missing or stale, polls and refetches while observed. */
36
+ subscribe<Vars, Data, S extends QueryState<unknown>>(def: Query<Vars, Data, S>, vars: Vars, listener: Listener<S>, opts?: SubscribeOptions): Unsubscribe;
37
+ subscribe<Data, S extends QueryState<unknown>>(def: Query<void, Data, S>, listener: Listener<S>): Unsubscribe;
38
+ subscribe<T>(def: Readable<T>, listener: Listener<T>): Unsubscribe;
39
+ /** Re-runs `fn` when what it read changes; the returned cleanup runs before each re-run and on dispose. */
40
+ effect(fn: EffectFn): Unsubscribe;
41
+ /** Runs `fn` with this client as the ambient scope. */
42
+ run<R>(fn: () => R): R;
43
+ /** Defers notifications until the outermost batch ends. */
44
+ batch<R>(fn: () => R): R;
45
+ untracked<R>(fn: () => R): R;
46
+ }
47
+ export declare const createRivaClient: (options?: ClientOptions) => RivaClient;
48
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,KAAK,QAAQ,EAAQ,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E,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAEjE;IAED,2FAA2F;IAC3F,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,SAAS,UAAU,CAAC,OAAO,CAAC,EAClD,GAAG,EAAE,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,EACzB,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,IAAI,CAAC,EAAE,gBAAgB,GACrB,WAAW,CAAC;IACf,SAAS,CAAC,IAAI,EAAE,CAAC,SAAS,UAAU,CAAC,OAAO,CAAC,EAC5C,GAAG,EAAE,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,EACzB,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,GACnB,WAAW,CAAC;IACf,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC;IAsBnE,2GAA2G;IAC3G,MAAM,CAAC,EAAE,EAAE,QAAQ,GAAG,WAAW,CAkBhC;IAED,uDAAuD;IACvD,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAErB;IAED,2DAA2D;IAC3D,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAEvB;IAED,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAE3B;CACD;AAED,eAAO,MAAM,gBAAgB,aAAc,aAAa,KAAG,UACnC,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { Listener, Signal, Unsubscribe } from './signal';
2
+ /** A signal seen without its setter: what a store exposes for its state keys. */
3
+ export interface ReadonlySignal<T> extends Omit<Signal<T>, 'set' | 'equals'> {
4
+ }
5
+ export type Readable<T> = Signal<T> | ReadonlySignal<T> | Computed<T>;
6
+ export type Getter = <U>(def: Readable<U>) => U;
7
+ export interface ComputedOptions<T> {
8
+ name?: string;
9
+ equals?: (a: T, b: T) => boolean;
10
+ }
11
+ /** A stateless derived value: lazy, cached per client, tracked dynamically. */
12
+ export interface Computed<T> {
13
+ readonly kind: 'computed';
14
+ readonly name: string | undefined;
15
+ fn(get: Getter): T;
16
+ equals(a: T, b: T): boolean;
17
+ get(): T;
18
+ subscribe(listener: Listener<T>): Unsubscribe;
19
+ }
20
+ export declare function computed<T>(fn: (get: Getter) => T, opts?: ComputedOptions<T>): Computed<T>;
21
+ //# sourceMappingURL=computed.d.ts.map