@rocicorp/zero 1.11.0-canary.1 → 1.11.0-canary.2

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 (99) hide show
  1. package/out/replicache/src/btree/read.d.ts +12 -1
  2. package/out/replicache/src/btree/read.d.ts.map +1 -1
  3. package/out/replicache/src/btree/read.js +24 -12
  4. package/out/replicache/src/btree/read.js.map +1 -1
  5. package/out/replicache/src/db/write.js.map +1 -1
  6. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  7. package/out/replicache/src/replicache-impl.js +10 -0
  8. package/out/replicache/src/replicache-impl.js.map +1 -1
  9. package/out/replicache/src/transactions.d.ts.map +1 -1
  10. package/out/replicache/src/transactions.js +1 -1
  11. package/out/replicache/src/transactions.js.map +1 -1
  12. package/out/zero/package.js +1 -1
  13. package/out/zero/package.js.map +1 -1
  14. package/out/zero-cache/src/config/zero-config.d.ts +2 -0
  15. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  16. package/out/zero-cache/src/config/zero-config.js +12 -4
  17. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  18. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  19. package/out/zero-cache/src/server/replicator.js +1 -1
  20. package/out/zero-cache/src/server/replicator.js.map +1 -1
  21. package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
  22. package/out/zero-cache/src/services/change-source/common/replica-schema.js +2 -39
  23. package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
  24. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -2
  25. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  26. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +2 -2
  27. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  28. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +6 -6
  29. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  30. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  31. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  32. package/out/zero-cache/src/services/litestream/commands.js +3 -1
  33. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  34. package/out/zero-cache/src/services/litestream/config-v5.yml +1 -4
  35. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  36. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  37. package/out/zero-cache/src/services/replicator/incremental-sync.js +22 -5
  38. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  39. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  40. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts +4 -4
  41. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts.map +1 -1
  42. package/out/zero-cache/src/services/replicator/write-worker-client.js +2 -2
  43. package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
  44. package/out/zero-cache/src/services/replicator/write-worker.js +10 -4
  45. package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
  46. package/out/zero-cache/src/types/streams.d.ts +6 -6
  47. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  48. package/out/zero-cache/src/types/streams.js +6 -11
  49. package/out/zero-cache/src/types/streams.js.map +1 -1
  50. package/out/zero-client/src/client/context.d.ts +15 -0
  51. package/out/zero-client/src/client/context.d.ts.map +1 -1
  52. package/out/zero-client/src/client/context.js +44 -0
  53. package/out/zero-client/src/client/context.js.map +1 -1
  54. package/out/zero-client/src/client/inspector/lazy-inspector.js +2 -2
  55. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  56. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  57. package/out/zero-client/src/client/version.js +1 -1
  58. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  59. package/out/zero-client/src/client/zero-rep.js +2 -1
  60. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  61. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  62. package/out/zero-client/src/client/zero.js +48 -11
  63. package/out/zero-client/src/client/zero.js.map +1 -1
  64. package/out/zero-protocol/src/down.d.ts +29 -29
  65. package/out/zero-protocol/src/inspect-down.d.ts +81 -81
  66. package/out/zero-protocol/src/poke.d.ts +6 -6
  67. package/out/zero-react/src/use-query.d.ts.map +1 -1
  68. package/out/zero-react/src/use-query.js +24 -5
  69. package/out/zero-react/src/use-query.js.map +1 -1
  70. package/out/zero-solid/src/use-query.js +4 -1
  71. package/out/zero-solid/src/use-query.js.map +1 -1
  72. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  73. package/out/zql/src/ivm/array-view.js +5 -3
  74. package/out/zql/src/ivm/array-view.js.map +1 -1
  75. package/out/zql/src/ivm/deferred-input.d.ts +44 -0
  76. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -0
  77. package/out/zql/src/ivm/deferred-input.js +88 -0
  78. package/out/zql/src/ivm/deferred-input.js.map +1 -0
  79. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  80. package/out/zql/src/ivm/memory-source.js +5 -10
  81. package/out/zql/src/ivm/memory-source.js.map +1 -1
  82. package/out/zql/src/query/query-delegate-base.d.ts +6 -0
  83. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  84. package/out/zql/src/query/query-delegate-base.js +73 -10
  85. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  86. package/out/zql/src/query/query-delegate.d.ts +22 -0
  87. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  88. package/out/zql/src/query/query-impl.d.ts +12 -11
  89. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  90. package/out/zql/src/query/query-impl.js +383 -60
  91. package/out/zql/src/query/query-impl.js.map +1 -1
  92. package/out/zql/src/query/query-transitions.d.ts +171 -0
  93. package/out/zql/src/query/query-transitions.d.ts.map +1 -0
  94. package/out/zql/src/query/query-transitions.js +207 -0
  95. package/out/zql/src/query/query-transitions.js.map +1 -0
  96. package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
  97. package/out/zql/src/query/runnable-query-impl.js +21 -1
  98. package/out/zql/src/query/runnable-query-impl.js.map +1 -1
  99. package/package.json +1 -1
@@ -57,14 +57,14 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
57
57
  clientID: string;
58
58
  };
59
59
  result: {
60
- data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
61
- } | {
62
60
  error: "app";
63
61
  message?: string | undefined;
64
62
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
65
63
  } | {
66
64
  error: "alreadyProcessed" | "oooMutation";
67
65
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
66
+ } | {
67
+ data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
68
68
  };
69
69
  };
70
70
  } | {
@@ -191,33 +191,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
191
191
  type: "attempt-start";
192
192
  attemptNumber: number;
193
193
  totalAttempts: number;
194
- } | {
195
- type: "connection-selected";
196
- attemptNumber: number;
197
- connection: string;
198
- cost: number;
199
- isRoot: boolean;
200
- } | {
201
- type: "plan-failed";
202
- attemptNumber: number;
203
- reason: string;
204
- } | {
205
- type: "best-plan-selected";
206
- bestAttemptNumber: number;
207
- totalCost: number;
208
- flipPattern: number;
209
- joinStates: {
210
- join: string;
211
- type: "flipped" | "semi" | "unflippable";
212
- }[];
213
- } | {
214
- type: "node-constraint";
215
- attemptNumber?: number | undefined;
216
- nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
217
- node: string;
218
- branchPattern: number[];
219
- constraint?: Record<string, unknown> | null | undefined;
220
- from: string;
221
194
  } | {
222
195
  type: "connection-costs";
223
196
  attemptNumber: number;
@@ -243,6 +216,12 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
243
216
  limit?: number | undefined;
244
217
  }>;
245
218
  }[];
219
+ } | {
220
+ type: "connection-selected";
221
+ attemptNumber: number;
222
+ connection: string;
223
+ cost: number;
224
+ isRoot: boolean;
246
225
  } | {
247
226
  type: "constraints-propagated";
248
227
  attemptNumber: number;
@@ -267,6 +246,19 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
267
246
  join: string;
268
247
  type: "flipped" | "semi" | "unflippable";
269
248
  }[];
249
+ } | {
250
+ type: "plan-failed";
251
+ attemptNumber: number;
252
+ reason: string;
253
+ } | {
254
+ type: "best-plan-selected";
255
+ bestAttemptNumber: number;
256
+ totalCost: number;
257
+ flipPattern: number;
258
+ joinStates: {
259
+ join: string;
260
+ type: "flipped" | "semi" | "unflippable";
261
+ }[];
270
262
  } | {
271
263
  type: "node-cost";
272
264
  attemptNumber?: number | undefined;
@@ -285,6 +277,14 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
285
277
  filters?: import("./ast.ts").Condition | undefined;
286
278
  ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
287
279
  joinType?: "flipped" | "semi" | "unflippable" | undefined;
280
+ } | {
281
+ type: "node-constraint";
282
+ attemptNumber?: number | undefined;
283
+ nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
284
+ node: string;
285
+ branchPattern: number[];
286
+ constraint?: Record<string, unknown> | null | undefined;
287
+ from: string;
288
288
  })[]>;
289
289
  }, undefined>;
290
290
  }, undefined>, v.ObjectType<Omit<{
@@ -100,6 +100,33 @@ export declare const inspectAnalyzeQueryDownSchema: v.ObjectType<Omit<{
100
100
  type: "attempt-start";
101
101
  attemptNumber: number;
102
102
  totalAttempts: number;
103
+ } | {
104
+ type: "connection-selected";
105
+ attemptNumber: number;
106
+ connection: string;
107
+ cost: number;
108
+ isRoot: boolean;
109
+ } | {
110
+ type: "plan-failed";
111
+ attemptNumber: number;
112
+ reason: string;
113
+ } | {
114
+ type: "best-plan-selected";
115
+ bestAttemptNumber: number;
116
+ totalCost: number;
117
+ flipPattern: number;
118
+ joinStates: {
119
+ join: string;
120
+ type: "flipped" | "semi" | "unflippable";
121
+ }[];
122
+ } | {
123
+ type: "node-constraint";
124
+ attemptNumber?: number | undefined;
125
+ nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
126
+ node: string;
127
+ branchPattern: number[];
128
+ constraint?: Record<string, unknown> | null | undefined;
129
+ from: string;
103
130
  } | {
104
131
  type: "connection-costs";
105
132
  attemptNumber: number;
@@ -125,12 +152,6 @@ export declare const inspectAnalyzeQueryDownSchema: v.ObjectType<Omit<{
125
152
  limit?: number | undefined;
126
153
  }>;
127
154
  }[];
128
- } | {
129
- type: "connection-selected";
130
- attemptNumber: number;
131
- connection: string;
132
- cost: number;
133
- isRoot: boolean;
134
155
  } | {
135
156
  type: "constraints-propagated";
136
157
  attemptNumber: number;
@@ -155,19 +176,6 @@ export declare const inspectAnalyzeQueryDownSchema: v.ObjectType<Omit<{
155
176
  join: string;
156
177
  type: "flipped" | "semi" | "unflippable";
157
178
  }[];
158
- } | {
159
- type: "plan-failed";
160
- attemptNumber: number;
161
- reason: string;
162
- } | {
163
- type: "best-plan-selected";
164
- bestAttemptNumber: number;
165
- totalCost: number;
166
- flipPattern: number;
167
- joinStates: {
168
- join: string;
169
- type: "flipped" | "semi" | "unflippable";
170
- }[];
171
179
  } | {
172
180
  type: "node-cost";
173
181
  attemptNumber?: number | undefined;
@@ -186,14 +194,6 @@ export declare const inspectAnalyzeQueryDownSchema: v.ObjectType<Omit<{
186
194
  filters?: import("./ast.ts").Condition | undefined;
187
195
  ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
188
196
  joinType?: "flipped" | "semi" | "unflippable" | undefined;
189
- } | {
190
- type: "node-constraint";
191
- attemptNumber?: number | undefined;
192
- nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
193
- node: string;
194
- branchPattern: number[];
195
- constraint?: Record<string, unknown> | null | undefined;
196
- from: string;
197
197
  })[]>;
198
198
  }, undefined>;
199
199
  }, undefined>;
@@ -266,6 +266,33 @@ export declare const inspectDownBodySchema: v.UnionType<[v.ObjectType<Omit<{
266
266
  type: "attempt-start";
267
267
  attemptNumber: number;
268
268
  totalAttempts: number;
269
+ } | {
270
+ type: "connection-selected";
271
+ attemptNumber: number;
272
+ connection: string;
273
+ cost: number;
274
+ isRoot: boolean;
275
+ } | {
276
+ type: "plan-failed";
277
+ attemptNumber: number;
278
+ reason: string;
279
+ } | {
280
+ type: "best-plan-selected";
281
+ bestAttemptNumber: number;
282
+ totalCost: number;
283
+ flipPattern: number;
284
+ joinStates: {
285
+ join: string;
286
+ type: "flipped" | "semi" | "unflippable";
287
+ }[];
288
+ } | {
289
+ type: "node-constraint";
290
+ attemptNumber?: number | undefined;
291
+ nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
292
+ node: string;
293
+ branchPattern: number[];
294
+ constraint?: Record<string, unknown> | null | undefined;
295
+ from: string;
269
296
  } | {
270
297
  type: "connection-costs";
271
298
  attemptNumber: number;
@@ -291,12 +318,6 @@ export declare const inspectDownBodySchema: v.UnionType<[v.ObjectType<Omit<{
291
318
  limit?: number | undefined;
292
319
  }>;
293
320
  }[];
294
- } | {
295
- type: "connection-selected";
296
- attemptNumber: number;
297
- connection: string;
298
- cost: number;
299
- isRoot: boolean;
300
321
  } | {
301
322
  type: "constraints-propagated";
302
323
  attemptNumber: number;
@@ -321,19 +342,6 @@ export declare const inspectDownBodySchema: v.UnionType<[v.ObjectType<Omit<{
321
342
  join: string;
322
343
  type: "flipped" | "semi" | "unflippable";
323
344
  }[];
324
- } | {
325
- type: "plan-failed";
326
- attemptNumber: number;
327
- reason: string;
328
- } | {
329
- type: "best-plan-selected";
330
- bestAttemptNumber: number;
331
- totalCost: number;
332
- flipPattern: number;
333
- joinStates: {
334
- join: string;
335
- type: "flipped" | "semi" | "unflippable";
336
- }[];
337
345
  } | {
338
346
  type: "node-cost";
339
347
  attemptNumber?: number | undefined;
@@ -352,14 +360,6 @@ export declare const inspectDownBodySchema: v.UnionType<[v.ObjectType<Omit<{
352
360
  filters?: import("./ast.ts").Condition | undefined;
353
361
  ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
354
362
  joinType?: "flipped" | "semi" | "unflippable" | undefined;
355
- } | {
356
- type: "node-constraint";
357
- attemptNumber?: number | undefined;
358
- nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
359
- node: string;
360
- branchPattern: number[];
361
- constraint?: Record<string, unknown> | null | undefined;
362
- from: string;
363
363
  })[]>;
364
364
  }, undefined>;
365
365
  }, undefined>, v.ObjectType<Omit<{
@@ -429,6 +429,33 @@ export declare const inspectDownMessageSchema: v.TupleType<[v.Type<"inspect">, v
429
429
  type: "attempt-start";
430
430
  attemptNumber: number;
431
431
  totalAttempts: number;
432
+ } | {
433
+ type: "connection-selected";
434
+ attemptNumber: number;
435
+ connection: string;
436
+ cost: number;
437
+ isRoot: boolean;
438
+ } | {
439
+ type: "plan-failed";
440
+ attemptNumber: number;
441
+ reason: string;
442
+ } | {
443
+ type: "best-plan-selected";
444
+ bestAttemptNumber: number;
445
+ totalCost: number;
446
+ flipPattern: number;
447
+ joinStates: {
448
+ join: string;
449
+ type: "flipped" | "semi" | "unflippable";
450
+ }[];
451
+ } | {
452
+ type: "node-constraint";
453
+ attemptNumber?: number | undefined;
454
+ nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
455
+ node: string;
456
+ branchPattern: number[];
457
+ constraint?: Record<string, unknown> | null | undefined;
458
+ from: string;
432
459
  } | {
433
460
  type: "connection-costs";
434
461
  attemptNumber: number;
@@ -454,12 +481,6 @@ export declare const inspectDownMessageSchema: v.TupleType<[v.Type<"inspect">, v
454
481
  limit?: number | undefined;
455
482
  }>;
456
483
  }[];
457
- } | {
458
- type: "connection-selected";
459
- attemptNumber: number;
460
- connection: string;
461
- cost: number;
462
- isRoot: boolean;
463
484
  } | {
464
485
  type: "constraints-propagated";
465
486
  attemptNumber: number;
@@ -484,19 +505,6 @@ export declare const inspectDownMessageSchema: v.TupleType<[v.Type<"inspect">, v
484
505
  join: string;
485
506
  type: "flipped" | "semi" | "unflippable";
486
507
  }[];
487
- } | {
488
- type: "plan-failed";
489
- attemptNumber: number;
490
- reason: string;
491
- } | {
492
- type: "best-plan-selected";
493
- bestAttemptNumber: number;
494
- totalCost: number;
495
- flipPattern: number;
496
- joinStates: {
497
- join: string;
498
- type: "flipped" | "semi" | "unflippable";
499
- }[];
500
508
  } | {
501
509
  type: "node-cost";
502
510
  attemptNumber?: number | undefined;
@@ -515,14 +523,6 @@ export declare const inspectDownMessageSchema: v.TupleType<[v.Type<"inspect">, v
515
523
  filters?: import("./ast.ts").Condition | undefined;
516
524
  ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
517
525
  joinType?: "flipped" | "semi" | "unflippable" | undefined;
518
- } | {
519
- type: "node-constraint";
520
- attemptNumber?: number | undefined;
521
- nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
522
- node: string;
523
- branchPattern: number[];
524
- constraint?: Record<string, unknown> | null | undefined;
525
- from: string;
526
526
  })[]>;
527
527
  }, undefined>;
528
528
  }, undefined>, v.ObjectType<Omit<{
@@ -85,14 +85,14 @@ export declare const pokePartBodySchema: v.ObjectType<{
85
85
  clientID: string;
86
86
  };
87
87
  result: {
88
+ data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
89
+ } | {
88
90
  error: "app";
89
91
  message?: string | undefined;
90
92
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
91
93
  } | {
92
94
  error: "alreadyProcessed" | "oooMutation";
93
95
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
94
- } | {
95
- data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
96
96
  };
97
97
  };
98
98
  } | {
@@ -156,14 +156,14 @@ export declare const pokePartsSchema: v.ArrayType<v.ObjectType<{
156
156
  clientID: string;
157
157
  };
158
158
  result: {
159
+ data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
160
+ } | {
159
161
  error: "app";
160
162
  message?: string | undefined;
161
163
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
162
164
  } | {
163
165
  error: "alreadyProcessed" | "oooMutation";
164
166
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
165
- } | {
166
- data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
167
167
  };
168
168
  };
169
169
  } | {
@@ -240,14 +240,14 @@ export declare const pokePartMessageSchema: v.TupleType<[v.Type<"pokePart">, v.O
240
240
  clientID: string;
241
241
  };
242
242
  result: {
243
+ data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
244
+ } | {
243
245
  error: "app";
244
246
  message?: string | undefined;
245
247
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
246
248
  } | {
247
249
  error: "alreadyProcessed" | "oooMutation";
248
250
  details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
249
- } | {
250
- data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
251
251
  };
252
252
  };
253
253
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.d.ts","sourceRoot":"","sources":["../../../../zero-react/src/use-query.tsx"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAEV,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EACd,aAAa,EAEb,KAAK,EACL,aAAa,EACb,OAAO,EACP,KAAK,EAEL,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EAEjB,GAAG,EAEH,IAAI,EACL,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,WAAW,CAAC,OAAO,IAAI,SAAS;IAC1C,aAAa,CAAC,OAAO,CAAC;IACtB,kBAAkB,GAAG,EAAE;CACxB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,gBAAgB,CAAC,OAAO,IAAI,SAAS;IAC/C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AAa,SAAS;;IAcpB,cAIC;IAED,OAAO,CACL,MAAM,SAAS,MAAM,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,EAC/C,OAAO,SAAS,iBAAiB,EACjC,OAAO,EACP,EAAE,SAAS,iBAAiB,GAAG,SAAS,EACxC,QAAQ,SAAS,kBAAkB,EAEnC,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,QAAQ,CAAC,EACjC,CAAC,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,EAClC,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,GAAG,GACP;QACD,WAAW,EAAE,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;QACxC,uBAAuB,EAAE,CAAC,SAAS,EAAE,MAAM,IAAI,KAAK,MAAM,IAAI,CAAC;QAC/D,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,CAAC;QAC9B,eAAe,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QACrC,eAAe,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QACrC,QAAQ,EAAE,OAAO,CAAC;QAClB,QAAQ,EAAE,OAAO,CAAC;KACnB,CA2CA;CACF"}
@@ -146,6 +146,17 @@ function makeError(retry, error) {
146
146
  * Swapping `useState` to `useRef` has similar problems.
147
147
  */
148
148
  var ViewStore = class {
149
+ /**
150
+ * Client id, then query hash.
151
+ *
152
+ * Nested rather than keyed by the two joined together, because this is
153
+ * looked up on every render of every `useQuery`. Joining them builds a
154
+ * string that V8 has to hash from scratch, where both halves on their own
155
+ * are strings it has already hashed and cached -- `hash()` is memoized on an
156
+ * interned query, so the same string comes back each render. Measured over a
157
+ * rebuild-and-look-up of one chain, that is the difference between 202ns and
158
+ * 123ns; the join cost more than rebuilding and hashing the whole query.
159
+ */
149
160
  #views = /* @__PURE__ */ new Map();
150
161
  constructor() {}
151
162
  getView(zero, q, enabled, ttl) {
@@ -159,15 +170,23 @@ var ViewStore = class {
159
170
  complete: false,
160
171
  nonEmpty: false
161
172
  };
162
- const hash = qi.hash() + zero.clientID;
163
- let existing = this.#views.get(hash);
173
+ const { clientID } = zero;
174
+ const hash = qi.hash();
175
+ let byHash = this.#views.get(clientID);
176
+ let existing = byHash?.get(hash);
164
177
  if (!existing) {
165
178
  existing = new ViewWrapper(q, zero, ttl, (view) => {
166
- const currentView = this.#views.get(hash);
179
+ const views = this.#views.get(clientID);
180
+ const currentView = views?.get(hash);
167
181
  if (currentView && currentView !== view) return;
168
- this.#views.delete(hash);
182
+ views?.delete(hash);
183
+ if (views?.size === 0) this.#views.delete(clientID);
169
184
  });
170
- this.#views.set(hash, existing);
185
+ if (!byHash) {
186
+ byHash = /* @__PURE__ */ new Map();
187
+ this.#views.set(clientID, byHash);
188
+ }
189
+ byHash.set(hash, existing);
171
190
  } else existing.updateTTL(ttl);
172
191
  return existing;
173
192
  }
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useSyncExternalStore} from 'react';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' (in which case results may be\n * empty). This is useful for suspending until there are partial\n * optimistic local results, or the query has completed loading from the\n * server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<ViewStore, Map<string, AnyViewWrapper>>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n return allViews.get(store)?.size ?? 0;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n #views = new Map<string, AnyViewWrapper>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const hash = qi.hash() + zero.clientID;\n let existing = this.#views.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const currentView = this.#views.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n this.#views.delete(hash);\n });\n this.#views.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n if (\n this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0\n ) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;AAwEA,IAAM,WAAY,MAAgD;AAClE,IAAM,UAAyC,WAC3C,YACA,MAAK;CACH,MAAM;AACR;AAsCJ,SAAgB,SAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CAAC,UAAU,MAAM,MAAM,kBAAkB;CAG5C,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,KAAA;CAI5D,OAAO,qBACL,MAAM,2BAA2B,oBACjC,MAAM,eACH,qBACH,MAAM,eACH,mBACL;AACF;AAsCA,SAAgB,iBAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,eAAuC;CAC3C,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CACC,UAAU,MACV,MAAM,gBACN,eAAe,cACb;CAGN,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,I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B,cAAwC;EACjE,KAAKJ,gBAAgB,IAAI,SAAS;EAKlC,IAAI,KAAKa,kBAAkB,KAAA,GAAW;GACpC,aAAa,KAAKA,aAAa;GAC/B,KAAKA,gBAAgB,KAAA;EACvB;EACA,KAAKR,qBAAqB;EAC1B,aAAa;GACX,KAAKL,gBAAgB,OAAO,SAAS;GAGrC,IAAI,KAAKA,gBAAgB,SAAS,GAChC,KAAKa,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKX,gBAAgB,OAAO,GAC9B;IAGF,KAAKW,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKZ,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EACxB,KAAKK,OAAO;EACZ,KAAKQ,OAAO,UAAU,GAAG;CAC3B;CAEA,IAAI,WAAW;EACb,OAAO,KAAKJ;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;CAEA,IAAI,WAAW;EACb,OAAO,KAAKC;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;AACF"}
1
+ {"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useSyncExternalStore} from 'react';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' (in which case results may be\n * empty). This is useful for suspending until there are partial\n * optimistic local results, or the query has completed loading from the\n * server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<\n ViewStore,\n Map<string, Map<string, AnyViewWrapper>>\n>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n let size = 0;\n for (const byHash of allViews.get(store)?.values() ?? []) {\n size += byHash.size;\n }\n return size;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n /**\n * Client id, then query hash.\n *\n * Nested rather than keyed by the two joined together, because this is\n * looked up on every render of every `useQuery`. Joining them builds a\n * string that V8 has to hash from scratch, where both halves on their own\n * are strings it has already hashed and cached -- `hash()` is memoized on an\n * interned query, so the same string comes back each render. Measured over a\n * rebuild-and-look-up of one chain, that is the difference between 202ns and\n * 123ns; the join cost more than rebuilding and hashing the whole query.\n */\n #views = new Map<string, Map<string, AnyViewWrapper>>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const {clientID} = zero;\n const hash = qi.hash();\n let byHash = this.#views.get(clientID);\n let existing = byHash?.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const views = this.#views.get(clientID);\n const currentView = views?.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n views?.delete(hash);\n if (views?.size === 0) {\n // Nothing is left for this client, so drop its map rather than\n // keeping one per client id the page has ever seen.\n this.#views.delete(clientID);\n }\n });\n if (!byHash) {\n byHash = new Map();\n this.#views.set(clientID, byHash);\n }\n byHash.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n if (\n this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0\n ) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;AAwEA,IAAM,WAAY,MAAgD;AAClE,IAAM,UAAyC,WAC3C,YACA,MAAK;CACH,MAAM;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,GAChC,KAAKa,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKX,gBAAgB,OAAO,GAC9B;IAGF,KAAKW,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKZ,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EACxB,KAAKK,OAAO;EACZ,KAAKQ,OAAO,UAAU,GAAG;CAC3B;CAEA,IAAI,WAAW;EACb,OAAO,KAAKJ;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;CAEA,IAAI,WAAW;EACb,OAAO,KAAKC;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;AACF"}
@@ -31,7 +31,10 @@ function useQuery(querySignal, options) {
31
31
  if (!query) return void 0;
32
32
  return asQueryInternals(query);
33
33
  });
34
- const hash = createMemo(() => qi()?.hash() + zero().clientID);
34
+ const hash = createMemo(() => {
35
+ const internals = qi();
36
+ return internals === void 0 ? void 0 : internals.hash() + zero().clientID;
37
+ });
35
38
  const ttl = createMemo(() => normalize(options)?.ttl ?? 3e5);
36
39
  const initialTTL = ttl();
37
40
  const view = createMemo(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.js","names":[],"sources":["../../../../zero-solid/src/use-query.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n on,\n onCleanup,\n untrack,\n type Accessor,\n} from 'solid-js';\nimport {createStore} from 'solid-js/store';\nimport {\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {createSolidViewFactory, UNKNOWN, type State} from './solid-view.ts';\nimport {useZero} from './use-zero.ts';\nimport {\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type DefaultContext,\n type DefaultSchema,\n type Falsy,\n type HumanReadable,\n type PullRow,\n type QueryOrQueryRequest,\n type QueryResultDetails,\n type ReadonlyJSONValue,\n type TTL,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn>>,\n Accessor<QueryResultDetails & {}>,\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn> | undefined>,\n Accessor<QueryResultDetails & {}>,\n];\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode UseQueryOptions} instead.\n */\nexport type CreateQueryOptions = {\n ttl?: TTL | undefined;\n};\n\nexport type UseQueryOptions = {\n ttl?: TTL | undefined;\n};\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode useQuery} instead.\n */\nexport function createQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: CreateQueryOptions | Accessor<CreateQueryOptions>,\n): QueryResult<TReturn> {\n return useQuery(querySignal, options);\n}\n\n// Overload 1: Query - returns QueryResult<TReturn>\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n const [state, setState] = createStore<State>([\n {\n '': undefined,\n },\n UNKNOWN,\n ]);\n const initialRefetchKey = 0;\n const [refetchKey, setRefetchKey] = createSignal(initialRefetchKey);\n\n const refetch = () => {\n setRefetchKey(k => k + 1);\n };\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // Handle possibly falsy queries\n const q = createMemo(() => {\n const query = querySignal();\n if (!query) return undefined;\n return addContextToQuery(query, zero().context);\n });\n\n const qi = createMemo(() => {\n const query = q();\n if (!query) return undefined;\n return asQueryInternals(query);\n });\n\n const hash = createMemo(() => qi()?.hash() + zero().clientID);\n const ttl = createMemo(() => normalize(options)?.ttl ?? DEFAULT_TTL_MS);\n\n const initialTTL = ttl();\n\n const view = createMemo(() => {\n // Depend on hash instead of query to avoid recreating the view when the\n // query object changes but the hash is the same.\n const currentHash = hash();\n refetchKey();\n\n // If query is falsy, don't create a view and reset state to undefined\n if (currentHash === undefined) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const untrackedQuery = untrack(q);\n if (!untrackedQuery) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const v = zero().materialize(\n untrackedQuery,\n createSolidViewFactory(setState, refetch),\n {\n ttl: initialTTL,\n },\n );\n\n onCleanup(() => v.destroy());\n\n return v;\n });\n\n // Update TTL on existing view when it changes.\n createEffect(\n on(\n ttl,\n currentTTL => {\n view()?.updateTTL(currentTTL);\n },\n {defer: true},\n ),\n );\n\n return [() => state[0][''] as HumanReadable<TReturn>, () => state[1]];\n}\n\nfunction normalize<T>(options?: T | Accessor<T | undefined>): T | undefined {\n return typeof options === 'function' ? (options as Accessor<T>)() : options;\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,SAAgB,YAQd,aAGA,SACsB;CACtB,OAAO,SAAS,aAAa,OAAO;AACtC;AAkCA,SAAgB,SAQd,aAIA,SACkD;CAClD,MAAM,CAAC,OAAO,YAAY,YAAmB,CAC3C,EACE,IAAI,KAAA,EACN,GACA,OACF,CAAC;CAED,MAAM,CAAC,YAAY,iBAAiB,aAAa,CAAiB;CAElE,MAAM,gBAAgB;EACpB,eAAc,MAAK,IAAI,CAAC;CAC1B;CAEA,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,iBAAiB;EACzB,MAAM,QAAQ,YAAY;EAC1B,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,kBAAkB,OAAO,KAAK,EAAE,OAAO;CAChD,CAAC;CAED,MAAM,KAAK,iBAAiB;EAC1B,MAAM,QAAQ,EAAE;EAChB,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,iBAAiB,KAAK;CAC/B,CAAC;CAED,MAAM,OAAO,iBAAiB,GAAG,GAAG,KAAK,IAAI,KAAK,EAAE,QAAQ;CAC5D,MAAM,MAAM,iBAAiB,UAAU,OAAO,GAAG,OAAA,GAAqB;CAEtE,MAAM,aAAa,IAAI;CAEvB,MAAM,OAAO,iBAAiB;EAG5B,MAAM,cAAc,KAAK;EACzB,WAAW;EAGX,IAAI,gBAAgB,KAAA,GAAW;GAC7B,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,iBAAiB,QAAQ,CAAC;EAChC,IAAI,CAAC,gBAAgB;GACnB,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,IAAI,KAAK,EAAE,YACf,gBACA,uBAAuB,UAAU,OAAO,GACxC,EACE,KAAK,WACP,CACF;EAEA,gBAAgB,EAAE,QAAQ,CAAC;EAE3B,OAAO;CACT,CAAC;CAGD,aACE,GACE,MACA,eAAc;EACZ,KAAK,GAAG,UAAU,UAAU;CAC9B,GACA,EAAC,OAAO,KAAI,CACd,CACF;CAEA,OAAO,OAAO,MAAM,GAAG,WAAqC,MAAM,EAAE;AACtE;AAEA,SAAS,UAAa,SAAsD;CAC1E,OAAO,OAAO,YAAY,aAAc,QAAwB,IAAI;AACtE"}
1
+ {"version":3,"file":"use-query.js","names":[],"sources":["../../../../zero-solid/src/use-query.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n on,\n onCleanup,\n untrack,\n type Accessor,\n} from 'solid-js';\nimport {createStore} from 'solid-js/store';\nimport {\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {createSolidViewFactory, UNKNOWN, type State} from './solid-view.ts';\nimport {useZero} from './use-zero.ts';\nimport {\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type DefaultContext,\n type DefaultSchema,\n type Falsy,\n type HumanReadable,\n type PullRow,\n type QueryOrQueryRequest,\n type QueryResultDetails,\n type ReadonlyJSONValue,\n type TTL,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn>>,\n Accessor<QueryResultDetails & {}>,\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn> | undefined>,\n Accessor<QueryResultDetails & {}>,\n];\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode UseQueryOptions} instead.\n */\nexport type CreateQueryOptions = {\n ttl?: TTL | undefined;\n};\n\nexport type UseQueryOptions = {\n ttl?: TTL | undefined;\n};\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode useQuery} instead.\n */\nexport function createQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: CreateQueryOptions | Accessor<CreateQueryOptions>,\n): QueryResult<TReturn> {\n return useQuery(querySignal, options);\n}\n\n// Overload 1: Query - returns QueryResult<TReturn>\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n const [state, setState] = createStore<State>([\n {\n '': undefined,\n },\n UNKNOWN,\n ]);\n const initialRefetchKey = 0;\n const [refetchKey, setRefetchKey] = createSignal(initialRefetchKey);\n\n const refetch = () => {\n setRefetchKey(k => k + 1);\n };\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // Handle possibly falsy queries\n const q = createMemo(() => {\n const query = querySignal();\n if (!query) return undefined;\n return addContextToQuery(query, zero().context);\n });\n\n const qi = createMemo(() => {\n const query = q();\n if (!query) return undefined;\n return asQueryInternals(query);\n });\n\n // Undefined rather than the string `undefined` + the client id: this feeds\n // the guard below, and concatenating a missing hash produced a string that\n // was never equal to undefined, leaving that guard unreachable.\n const hash = createMemo(() => {\n const internals = qi();\n return internals === undefined\n ? undefined\n : internals.hash() + zero().clientID;\n });\n const ttl = createMemo(() => normalize(options)?.ttl ?? DEFAULT_TTL_MS);\n\n const initialTTL = ttl();\n\n const view = createMemo(() => {\n // Depend on hash instead of query to avoid recreating the view when the\n // query object changes but the hash is the same.\n const currentHash = hash();\n refetchKey();\n\n // If query is falsy, don't create a view and reset state to undefined\n if (currentHash === undefined) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const untrackedQuery = untrack(q);\n if (!untrackedQuery) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const v = zero().materialize(\n untrackedQuery,\n createSolidViewFactory(setState, refetch),\n {\n ttl: initialTTL,\n },\n );\n\n onCleanup(() => v.destroy());\n\n return v;\n });\n\n // Update TTL on existing view when it changes.\n createEffect(\n on(\n ttl,\n currentTTL => {\n view()?.updateTTL(currentTTL);\n },\n {defer: true},\n ),\n );\n\n return [() => state[0][''] as HumanReadable<TReturn>, () => state[1]];\n}\n\nfunction normalize<T>(options?: T | Accessor<T | undefined>): T | undefined {\n return typeof options === 'function' ? (options as Accessor<T>)() : options;\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,SAAgB,YAQd,aAGA,SACsB;CACtB,OAAO,SAAS,aAAa,OAAO;AACtC;AAkCA,SAAgB,SAQd,aAIA,SACkD;CAClD,MAAM,CAAC,OAAO,YAAY,YAAmB,CAC3C,EACE,IAAI,KAAA,EACN,GACA,OACF,CAAC;CAED,MAAM,CAAC,YAAY,iBAAiB,aAAa,CAAiB;CAElE,MAAM,gBAAgB;EACpB,eAAc,MAAK,IAAI,CAAC;CAC1B;CAEA,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,iBAAiB;EACzB,MAAM,QAAQ,YAAY;EAC1B,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,kBAAkB,OAAO,KAAK,EAAE,OAAO;CAChD,CAAC;CAED,MAAM,KAAK,iBAAiB;EAC1B,MAAM,QAAQ,EAAE;EAChB,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,iBAAiB,KAAK;CAC/B,CAAC;CAKD,MAAM,OAAO,iBAAiB;EAC5B,MAAM,YAAY,GAAG;EACrB,OAAO,cAAc,KAAA,IACjB,KAAA,IACA,UAAU,KAAK,IAAI,KAAK,EAAE;CAChC,CAAC;CACD,MAAM,MAAM,iBAAiB,UAAU,OAAO,GAAG,OAAA,GA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