@rocicorp/zero 1.11.0-canary.35 → 1.11.0-canary.37

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 (130) hide show
  1. package/out/zero/package.js +1 -1
  2. package/out/zero/package.js.map +1 -1
  3. package/out/zero-cache/src/config/zero-config.d.ts +28 -0
  4. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  5. package/out/zero-cache/src/config/zero-config.js +83 -0
  6. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  7. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  8. package/out/zero-cache/src/server/change-streamer.js +2 -1
  9. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  10. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  11. package/out/zero-cache/src/server/main.js +5 -1
  12. package/out/zero-cache/src/server/main.js.map +1 -1
  13. package/out/zero-cache/src/server/replicator.d.ts +4 -0
  14. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  15. package/out/zero-cache/src/server/replicator.js +18 -4
  16. package/out/zero-cache/src/server/replicator.js.map +1 -1
  17. package/out/zero-cache/src/server/runner/run-worker.d.ts.map +1 -1
  18. package/out/zero-cache/src/server/runner/run-worker.js +12 -6
  19. package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
  20. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  21. package/out/zero-cache/src/server/syncer.js +17 -1
  22. package/out/zero-cache/src/server/syncer.js.map +1 -1
  23. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +1 -1
  24. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  25. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +27 -7
  26. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
  27. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +124 -62
  28. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  29. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +9 -3
  30. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  31. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +19 -6
  32. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  33. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +8 -0
  34. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  35. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +131 -62
  36. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  37. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +124 -2
  38. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  39. package/out/zero-cache/src/services/change-streamer/change-streamer.js +33 -2
  40. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  41. package/out/zero-cache/src/services/change-streamer/drain-tracker.d.ts +24 -0
  42. package/out/zero-cache/src/services/change-streamer/drain-tracker.d.ts.map +1 -0
  43. package/out/zero-cache/src/services/change-streamer/drain-tracker.js +67 -0
  44. package/out/zero-cache/src/services/change-streamer/drain-tracker.js.map +1 -0
  45. package/out/zero-cache/src/services/change-streamer/restore-admission.d.ts +214 -0
  46. package/out/zero-cache/src/services/change-streamer/restore-admission.d.ts.map +1 -0
  47. package/out/zero-cache/src/services/change-streamer/restore-admission.js +294 -0
  48. package/out/zero-cache/src/services/change-streamer/restore-admission.js.map +1 -0
  49. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +13 -1
  50. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -1
  51. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +7 -6
  52. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  53. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +2 -2
  54. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
  55. package/out/zero-cache/src/services/change-streamer/snapshot.js +2 -2
  56. package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
  57. package/out/zero-cache/src/services/change-streamer/subscribe.d.ts +39 -0
  58. package/out/zero-cache/src/services/change-streamer/subscribe.d.ts.map +1 -1
  59. package/out/zero-cache/src/services/change-streamer/subscribe.js +19 -2
  60. package/out/zero-cache/src/services/change-streamer/subscribe.js.map +1 -1
  61. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +22 -1
  62. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  63. package/out/zero-cache/src/services/change-streamer/subscriber.js +41 -15
  64. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  65. package/out/zero-cache/src/services/http-service.d.ts +6 -0
  66. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  67. package/out/zero-cache/src/services/http-service.js +14 -2
  68. package/out/zero-cache/src/services/http-service.js.map +1 -1
  69. package/out/zero-cache/src/services/life-cycle.d.ts +33 -0
  70. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  71. package/out/zero-cache/src/services/life-cycle.js +56 -10
  72. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  73. package/out/zero-cache/src/services/litestream/commands.d.ts +8 -0
  74. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/litestream/commands.js +22 -1
  76. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  77. package/out/zero-cache/src/services/replicator/drain-handler.d.ts +74 -0
  78. package/out/zero-cache/src/services/replicator/drain-handler.d.ts.map +1 -0
  79. package/out/zero-cache/src/services/replicator/drain-handler.js +185 -0
  80. package/out/zero-cache/src/services/replicator/drain-handler.js.map +1 -0
  81. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +2 -1
  82. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/replicator/incremental-sync.js +66 -13
  84. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  85. package/out/zero-cache/src/services/replicator/replicator.d.ts +2 -1
  86. package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
  87. package/out/zero-cache/src/services/replicator/replicator.js +2 -2
  88. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  89. package/out/zero-cache/src/services/view-syncer/batch-pacer.d.ts +79 -0
  90. package/out/zero-cache/src/services/view-syncer/batch-pacer.d.ts.map +1 -0
  91. package/out/zero-cache/src/services/view-syncer/batch-pacer.js +249 -0
  92. package/out/zero-cache/src/services/view-syncer/batch-pacer.js.map +1 -0
  93. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +27 -1
  94. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  95. package/out/zero-cache/src/services/view-syncer/cvr.js +107 -17
  96. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  97. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +85 -3
  98. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  99. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +301 -20
  100. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  101. package/out/zero-cache/src/services/view-syncer/push-cost.d.ts +132 -0
  102. package/out/zero-cache/src/services/view-syncer/push-cost.d.ts.map +1 -0
  103. package/out/zero-cache/src/services/view-syncer/push-cost.js +164 -0
  104. package/out/zero-cache/src/services/view-syncer/push-cost.js.map +1 -0
  105. package/out/zero-cache/src/services/view-syncer/push-cutoff.d.ts +55 -0
  106. package/out/zero-cache/src/services/view-syncer/push-cutoff.d.ts.map +1 -0
  107. package/out/zero-cache/src/services/view-syncer/push-cutoff.js +56 -0
  108. package/out/zero-cache/src/services/view-syncer/push-cutoff.js.map +1 -0
  109. package/out/zero-cache/src/services/view-syncer/query-stats.d.ts +7 -0
  110. package/out/zero-cache/src/services/view-syncer/query-stats.d.ts.map +1 -1
  111. package/out/zero-cache/src/services/view-syncer/query-stats.js +20 -1
  112. package/out/zero-cache/src/services/view-syncer/query-stats.js.map +1 -1
  113. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +136 -5
  114. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  115. package/out/zero-cache/src/services/view-syncer/snapshotter.js +246 -18
  116. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  117. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +8 -2
  118. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  119. package/out/zero-cache/src/services/view-syncer/view-syncer.js +381 -16
  120. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  121. package/out/zero-cache/src/types/processes.d.ts +8 -0
  122. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  123. package/out/zero-cache/src/types/processes.js.map +1 -1
  124. package/out/zero-client/src/client/version.js +1 -1
  125. package/out/zero-react/src/use-query.js +1 -1
  126. package/out/zero-react/src/use-query.js.map +1 -1
  127. package/out/zero-server/src/queries/process-queries.d.ts.map +1 -1
  128. package/out/zero-server/src/queries/process-queries.js +1 -1
  129. package/out/zero-server/src/queries/process-queries.js.map +1 -1
  130. package/package.json +1 -1
@@ -17,6 +17,7 @@ export declare const MESSAGE_TYPES: {
17
17
  readonly notify: 'notify';
18
18
  readonly ready: 'ready';
19
19
  readonly backupWatermarkUpdate: 'backupWatermakUpdate';
20
+ readonly drainRequested: 'drainRequested';
20
21
  readonly profile: 'profile';
21
22
  readonly profileResponse: 'profileResponse';
22
23
  readonly stop: 'stop';
@@ -43,6 +44,13 @@ export type ProfileResponse = {
43
44
  };
44
45
  export type ProfileMessage = ['profile', ProfileRequest];
45
46
  export type ProfileResponseMessage = ['profileResponse', ProfileResponse];
47
+ /**
48
+ * Sent by a worker (and relayed by `main` to the runner) to request that
49
+ * the server drain itself for a restart, e.g. by a view-syncer's replicator
50
+ * that has been granted permission to restore a new replica. See
51
+ * `SelfDrain`.
52
+ */
53
+ export type DrainRequestedMessage = ['drainRequested', object];
46
54
  export type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];
47
55
  /**
48
56
  * Subscribes the `handler` to messages of the given `type` and returns a
@@ -1 +1 @@
1
- {"version":3,"file":"processes.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,UAAU,EAEhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,YAAY,MAAM,aAAa,CAAC;AAIvC;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa;aACxB,OAAO,EAAE,SAAS;aAClB,MAAM,EAAE,QAAQ;aAChB,iBAAiB,EAAE,mBAAmB;aACtC,SAAS,EAAE,WAAW;aACtB,MAAM,EAAE,QAAQ;aAChB,KAAK,EAAE,OAAO;aACd,qBAAqB,EAAE,sBAAsB;aAC7C,OAAO,EAAE,SAAS;aAClB,eAAe,EAAE,iBAAiB;aAClC,IAAI,EAAE,MAAM;aACZ,KAAK,EAAE,OAAO;aACd,IAAI,EAAE,MAAM;CACJ,CAAC;AAEX,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG,CAAC,mBAAmB,EAAE,iBAAiB,CAAC,CAAC;AAEhF,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3C,CAAC;AAEF,M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8BzD"}
@@ -1 +1 @@
1
- {"version":3,"file":"processes.js","names":[],"sources":["../../../../../zero-cache/src/types/processes.ts"],"sourcesContent":["import {\n type ChildProcess,\n fork,\n type SendHandle,\n type Serializable,\n} from 'node:child_process';\nimport EventEmitter from 'node:events';\nimport {platform} from 'node:os';\nimport {pid} from 'node:process';\n\n/**\n * Central registry of message type names, which are used to identify\n * the payload in {@link Message} objects sent between processes. The\n * payloads themselves are implementation specific and defined in each\n * component; only the type name is reserved here to avoid collisions.\n *\n * Receiving logic can call {@link getMessage()} with the name of\n * the message of interest to filter messages to those of interest.\n */\nexport const MESSAGE_TYPES = {\n handoff: 'handoff',\n status: 'status',\n clientGroupStatus: 'clientGroupStatus',\n subscribe: 'subscribe',\n notify: 'notify',\n ready: 'ready',\n backupWatermarkUpdate: 'backupWatermakUpdate',\n profile: 'profile',\n profileResponse: 'profileResponse',\n stop: 'stop',\n start: 'start',\n init: 'init',\n} as const;\n\nexport type ClientGroupStatus = {\n readonly clientGroupID: string;\n readonly active: boolean;\n readonly generation?: number | undefined;\n};\n\nexport type ClientGroupStatusMessage = ['clientGroupStatus', ClientGroupStatus];\n\nexport type ProfileRequest = {\n readonly id: string;\n readonly durationMs: number;\n readonly worker?: string | undefined;\n readonly workerIndex?: number | undefined;\n};\n\nexport type ProfileResponse = {\n readonly id: string;\n readonly name: string;\n readonly profile?: unknown | undefined;\n readonly error?: string | undefined;\n};\n\nexport type ProfileMessage = ['profile', ProfileRequest];\nexport type ProfileResponseMessage = ['profileResponse', ProfileResponse];\n\nexport type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];\n\nfunction getMessage<M extends Message<unknown>>(\n type: M[0],\n data: unknown,\n): M[1] | null {\n if (Array.isArray(data) && data.length === 2 && data[0] === type) {\n return data[1] as M[1];\n }\n return null;\n}\n\n/**\n * Subscribes the `handler` to messages of the given `type` and returns a\n * function that unsubscribes it. Use this (rather than\n * {@link Receiver.onMessageType()}) for handlers scoped to a request or\n * operation rather than to the lifetime of the {@link Worker}; the\n * `'message'` listener is otherwise retained by the Worker forever.\n */\nexport function subscribeToMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n): () => void {\n const listener = (data: unknown, sendHandle?: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n handler(msg, sendHandle);\n }\n };\n e.on('message', listener);\n return () => {\n e.off('message', listener);\n };\n}\n\nfunction onMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n subscribeToMessageType(e, type, handler);\n return e;\n}\n\nfunction onceMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n const listener = (data: unknown, sendHandle: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n e.off('message', listener);\n handler(msg, sendHandle);\n }\n };\n return e.on('message', listener);\n}\n\nexport interface Sender {\n send<M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ): boolean;\n\n kill(signal?: NodeJS.Signals): void;\n}\n\nexport interface Subprocess extends Sender, EventEmitter {\n pid?: number | undefined;\n}\n\nexport interface Receiver extends EventEmitter {\n /**\n * The receiving side of {@link Sender.send()} that is a wrapper around\n * {@link on}('message', ...) that invokes the `handler` for messages of\n * the specified `type`.\n */\n onMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n\n /**\n * The receiving side of {@link Sender.send()} that behaves like\n * {@link once}('message', ...) that invokes the `handler` for the next\n * message of the specified `type` and then unsubscribes.\n */\n onceMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n}\n\nexport interface Worker extends Subprocess, Receiver {}\n\n/**\n * Adds the {@link Receiver.onMessageType()} and {@link Receiver.onceMessageType()}\n * methods to convert the given `EventEmitter` to a `Receiver`.\n */\nfunction wrap<P extends EventEmitter>(proc: P): P & Receiver {\n return new Proxy(proc, {\n get(target: P, prop: string | symbol, receiver: unknown) {\n switch (prop) {\n case 'onMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onMessageType(target, type, handler);\n return receiver; // this\n };\n case 'onceMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onceMessageType(target, type, handler);\n return receiver; // this\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as P & Receiver;\n}\n\ntype Proc = Pick<ChildProcess, 'send' | 'kill' | 'pid'> & EventEmitter;\n\n/**\n * The parentWorker for forked processes, or `null` if the process was not forked.\n * (Analogous to the `parentPort: MessagePort | null` of the `\"workers\"` library).\n */\nexport const parentWorker: Worker | null = process.send\n ? wrap(process as Proc)\n : null;\n\nconst SINGLE_PROCESS = 'SINGLE_PROCESS';\nlet singleProcessOverride = false;\nexport function singleProcessMode(): boolean {\n return singleProcessOverride || (process.env[SINGLE_PROCESS] ?? '0') !== '0';\n}\n\nexport function setSingleProcessMode(enabled: boolean = true): void {\n singleProcessOverride = enabled;\n}\n\n/**\n * Determines whether a module loaded as a worker process entry point should\n * start its worker.\n *\n * Most workers are launched via {@link childWorker}, which in single-process\n * mode runs them in-process (no real fork) by invoking their exported\n * `runWorker` directly; those entry points must therefore *not* self-start in\n * single-process mode, or they would run twice.\n *\n * A worker launched via {@link forkChildWorker}, however, is *always* a real\n * forked OS process — even in single-process mode — and it inherits the\n * parent's `SINGLE_PROCESS` env. So {@link singleProcessMode} alone would\n * wrongly suppress its startup, leaving the parent to spin re-forking a child\n * that immediately exits. Such a forked child has a non-null\n * {@link parentWorker} (`process.send` is defined), which is the signal to\n * start regardless. A standalone direct launch (no parent, not single-process)\n * also starts.\n *\n * @param parent The entry point's {@link parentWorker} (non-null iff forked).\n * @param isSingleProcessMode The result of {@link singleProcessMode}.\n */\nexport function shouldStartWorker(\n parent: Worker | null,\n isSingleProcessMode: boolean,\n): boolean {\n return parent !== null || !isSingleProcessMode;\n}\n\n/**\n *\n * @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL\n */\nexport function childWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n args = workerArgs(args);\n\n if (singleProcessMode()) {\n const [parent, child] = inProcChannel();\n import(moduleUrl.href)\n .then(async ({default: runWorker}) => {\n try {\n await runWorker(parent, env ?? process.env, ...args);\n child.emit('close', 0);\n return;\n } catch (err) {\n child.emit('error', err);\n child.emit('close', -1);\n }\n })\n .catch(err => child.emit('error', err));\n return child;\n }\n return forkChildWorkerWithArgs(moduleUrl, env, args);\n}\n\nexport function forkChildWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n return forkChildWorkerWithArgs(moduleUrl, env, workerArgs(args));\n}\n\nfunction workerArgs(args: string[]): string[] {\n return [...args, ...process.argv.slice(2)];\n}\n\nfunction forkChildWorkerWithArgs(\n moduleUrl: URL,\n env: NodeJS.ProcessEnv | undefined,\n args: string[],\n): Worker {\n const child = fork(moduleUrl, args, {\n // For production / non-windows, set `detached` to `true` so that SIGINT is\n // not automatically propagated and graceful shutdown happens as intended.\n // For Win32, detached: true causes all subprocesses to open in separate\n // terminals and breaks inter-process kill signals, so set it to false.\n detached: platform() !== 'win32',\n serialization: 'advanced', // use structured clone for IPC\n env,\n });\n return wrap(child);\n}\n\n/**\n * Creates two connected `Worker` instances such that messages sent to one\n * via the {@link Worker.send()} method are received by the other's\n * `on('message', ...)` handler.\n *\n * This is analogous to the two `MessagePort`s of a `MessageChannel`, and\n * is useful for executing code written for inter-process communication\n * in a single process.\n */\nexport function inProcChannel(): [Worker, Worker] {\n const worker1 = new EventEmitter();\n const worker2 = new EventEmitter();\n\n const sendTo =\n (dest: EventEmitter) =>\n (\n message: Serializable,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n dest.emit('message', message, sendHandle);\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill =\n (dest: EventEmitter) =>\n (signal: NodeJS.Signals = 'SIGTERM') =>\n dest.emit(signal, signal);\n\n return [\n wrap(\n Object.assign(worker1, {send: sendTo(worker2), kill: kill(worker2), pid}),\n ),\n wrap(\n Object.assign(worker2, {send: sendTo(worker1), kill: kill(worker1), pid}),\n ),\n ];\n}\n\n/**\n * Creates a {@link Worker} facade that broadcasts `send()` to all provided\n * workers and aggregates their `'message'` events into one stream.\n *\n * This is useful for code that expects a single Worker for IPC (e.g.\n * `handleProfzRequest`) but needs to reach multiple child workers.\n */\nexport function broadcastWorker(workers: Worker[]): Worker {\n const emitter = new EventEmitter();\n\n for (const w of workers) {\n w.on('message', (message: Serializable, sendHandle?: SendHandle) =>\n emitter.emit('message', message, sendHandle),\n );\n }\n\n const send = <M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n for (const w of workers) {\n w.send(message, sendHandle);\n }\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill = (signal: NodeJS.Signals = 'SIGTERM') => {\n for (const w of workers) {\n w.kill(signal);\n }\n };\n\n return wrap(Object.assign(emitter, {send, kill, pid}));\n}\n"],"mappings":";;;;;AA6DA,SAAS,WACP,MACA,MACa;CACb,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,KAAK,OAAO,MAC1D,OAAO,KAAK;CAEd,OAAO;AACT;;;;;;;;AASA,SAAgB,uBACd,GACA,MACA,SACY;CACZ,MAAM,YAAY,MAAe,eAA4B;EAC3D,MAAM,MAAM,WAAW,MAAM,IAAI;EACjC,IAAI,KACF,QAAQ,KAAK,UAAU;CAE3B;CACA,EAAE,GAAG,WAAW,QAAQ;CACxB,aAAa;EACX,EAAE,IAAI,WAAW,QAAQ;CAC3B;AACF;AAEA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AS;EAAC;EAAM;EAAM;CAAG,CAAC,CAAC;AACvD"}
1
+ {"version":3,"file":"processes.js","names":[],"sources":["../../../../../zero-cache/src/types/processes.ts"],"sourcesContent":["import {\n type ChildProcess,\n fork,\n type SendHandle,\n type Serializable,\n} from 'node:child_process';\nimport EventEmitter from 'node:events';\nimport {platform} from 'node:os';\nimport {pid} from 'node:process';\n\n/**\n * Central registry of message type names, which are used to identify\n * the payload in {@link Message} objects sent between processes. The\n * payloads themselves are implementation specific and defined in each\n * component; only the type name is reserved here to avoid collisions.\n *\n * Receiving logic can call {@link getMessage()} with the name of\n * the message of interest to filter messages to those of interest.\n */\nexport const MESSAGE_TYPES = {\n handoff: 'handoff',\n status: 'status',\n clientGroupStatus: 'clientGroupStatus',\n subscribe: 'subscribe',\n notify: 'notify',\n ready: 'ready',\n backupWatermarkUpdate: 'backupWatermakUpdate',\n drainRequested: 'drainRequested',\n profile: 'profile',\n profileResponse: 'profileResponse',\n stop: 'stop',\n start: 'start',\n init: 'init',\n} as const;\n\nexport type ClientGroupStatus = {\n readonly clientGroupID: string;\n readonly active: boolean;\n readonly generation?: number | undefined;\n};\n\nexport type ClientGroupStatusMessage = ['clientGroupStatus', ClientGroupStatus];\n\nexport type ProfileRequest = {\n readonly id: string;\n readonly durationMs: number;\n readonly worker?: string | undefined;\n readonly workerIndex?: number | undefined;\n};\n\nexport type ProfileResponse = {\n readonly id: string;\n readonly name: string;\n readonly profile?: unknown | undefined;\n readonly error?: string | undefined;\n};\n\nexport type ProfileMessage = ['profile', ProfileRequest];\nexport type ProfileResponseMessage = ['profileResponse', ProfileResponse];\n\n/**\n * Sent by a worker (and relayed by `main` to the runner) to request that\n * the server drain itself for a restart, e.g. by a view-syncer's replicator\n * that has been granted permission to restore a new replica. See\n * `SelfDrain`.\n */\nexport type DrainRequestedMessage = ['drainRequested', object];\n\nexport type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];\n\nfunction getMessage<M extends Message<unknown>>(\n type: M[0],\n data: unknown,\n): M[1] | null {\n if (Array.isArray(data) && data.length === 2 && data[0] === type) {\n return data[1] as M[1];\n }\n return null;\n}\n\n/**\n * Subscribes the `handler` to messages of the given `type` and returns a\n * function that unsubscribes it. Use this (rather than\n * {@link Receiver.onMessageType()}) for handlers scoped to a request or\n * operation rather than to the lifetime of the {@link Worker}; the\n * `'message'` listener is otherwise retained by the Worker forever.\n */\nexport function subscribeToMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n): () => void {\n const listener = (data: unknown, sendHandle?: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n handler(msg, sendHandle);\n }\n };\n e.on('message', listener);\n return () => {\n e.off('message', listener);\n };\n}\n\nfunction onMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n subscribeToMessageType(e, type, handler);\n return e;\n}\n\nfunction onceMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n const listener = (data: unknown, sendHandle: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n e.off('message', listener);\n handler(msg, sendHandle);\n }\n };\n return e.on('message', listener);\n}\n\nexport interface Sender {\n send<M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ): boolean;\n\n kill(signal?: NodeJS.Signals): void;\n}\n\nexport interface Subprocess extends Sender, EventEmitter {\n pid?: number | undefined;\n}\n\nexport interface Receiver extends EventEmitter {\n /**\n * The receiving side of {@link Sender.send()} that is a wrapper around\n * {@link on}('message', ...) that invokes the `handler` for messages of\n * the specified `type`.\n */\n onMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n\n /**\n * The receiving side of {@link Sender.send()} that behaves like\n * {@link once}('message', ...) that invokes the `handler` for the next\n * message of the specified `type` and then unsubscribes.\n */\n onceMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n}\n\nexport interface Worker extends Subprocess, Receiver {}\n\n/**\n * Adds the {@link Receiver.onMessageType()} and {@link Receiver.onceMessageType()}\n * methods to convert the given `EventEmitter` to a `Receiver`.\n */\nfunction wrap<P extends EventEmitter>(proc: P): P & Receiver {\n return new Proxy(proc, {\n get(target: P, prop: string | symbol, receiver: unknown) {\n switch (prop) {\n case 'onMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onMessageType(target, type, handler);\n return receiver; // this\n };\n case 'onceMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onceMessageType(target, type, handler);\n return receiver; // this\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as P & Receiver;\n}\n\ntype Proc = Pick<ChildProcess, 'send' | 'kill' | 'pid'> & EventEmitter;\n\n/**\n * The parentWorker for forked processes, or `null` if the process was not forked.\n * (Analogous to the `parentPort: MessagePort | null` of the `\"workers\"` library).\n */\nexport const parentWorker: Worker | null = process.send\n ? wrap(process as Proc)\n : null;\n\nconst SINGLE_PROCESS = 'SINGLE_PROCESS';\nlet singleProcessOverride = false;\nexport function singleProcessMode(): boolean {\n return singleProcessOverride || (process.env[SINGLE_PROCESS] ?? '0') !== '0';\n}\n\nexport function setSingleProcessMode(enabled: boolean = true): void {\n singleProcessOverride = enabled;\n}\n\n/**\n * Determines whether a module loaded as a worker process entry point should\n * start its worker.\n *\n * Most workers are launched via {@link childWorker}, which in single-process\n * mode runs them in-process (no real fork) by invoking their exported\n * `runWorker` directly; those entry points must therefore *not* self-start in\n * single-process mode, or they would run twice.\n *\n * A worker launched via {@link forkChildWorker}, however, is *always* a real\n * forked OS process — even in single-process mode — and it inherits the\n * parent's `SINGLE_PROCESS` env. So {@link singleProcessMode} alone would\n * wrongly suppress its startup, leaving the parent to spin re-forking a child\n * that immediately exits. Such a forked child has a non-null\n * {@link parentWorker} (`process.send` is defined), which is the signal to\n * start regardless. A standalone direct launch (no parent, not single-process)\n * also starts.\n *\n * @param parent The entry point's {@link parentWorker} (non-null iff forked).\n * @param isSingleProcessMode The result of {@link singleProcessMode}.\n */\nexport function shouldStartWorker(\n parent: Worker | null,\n isSingleProcessMode: boolean,\n): boolean {\n return parent !== null || !isSingleProcessMode;\n}\n\n/**\n *\n * @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL\n */\nexport function childWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n args = workerArgs(args);\n\n if (singleProcessMode()) {\n const [parent, child] = inProcChannel();\n import(moduleUrl.href)\n .then(async ({default: runWorker}) => {\n try {\n await runWorker(parent, env ?? process.env, ...args);\n child.emit('close', 0);\n return;\n } catch (err) {\n child.emit('error', err);\n child.emit('close', -1);\n }\n })\n .catch(err => child.emit('error', err));\n return child;\n }\n return forkChildWorkerWithArgs(moduleUrl, env, args);\n}\n\nexport function forkChildWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n return forkChildWorkerWithArgs(moduleUrl, env, workerArgs(args));\n}\n\nfunction workerArgs(args: string[]): string[] {\n return [...args, ...process.argv.slice(2)];\n}\n\nfunction forkChildWorkerWithArgs(\n moduleUrl: URL,\n env: NodeJS.ProcessEnv | undefined,\n args: string[],\n): Worker {\n const child = fork(moduleUrl, args, {\n // For production / non-windows, set `detached` to `true` so that SIGINT is\n // not automatically propagated and graceful shutdown happens as intended.\n // For Win32, detached: true causes all subprocesses to open in separate\n // terminals and breaks inter-process kill signals, so set it to false.\n detached: platform() !== 'win32',\n serialization: 'advanced', // use structured clone for IPC\n env,\n });\n return wrap(child);\n}\n\n/**\n * Creates two connected `Worker` instances such that messages sent to one\n * via the {@link Worker.send()} method are received by the other's\n * `on('message', ...)` handler.\n *\n * This is analogous to the two `MessagePort`s of a `MessageChannel`, and\n * is useful for executing code written for inter-process communication\n * in a single process.\n */\nexport function inProcChannel(): [Worker, Worker] {\n const worker1 = new EventEmitter();\n const worker2 = new EventEmitter();\n\n const sendTo =\n (dest: EventEmitter) =>\n (\n message: Serializable,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n dest.emit('message', message, sendHandle);\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill =\n (dest: EventEmitter) =>\n (signal: NodeJS.Signals = 'SIGTERM') =>\n dest.emit(signal, signal);\n\n return [\n wrap(\n Object.assign(worker1, {send: sendTo(worker2), kill: kill(worker2), pid}),\n ),\n wrap(\n Object.assign(worker2, {send: sendTo(worker1), kill: kill(worker1), pid}),\n ),\n ];\n}\n\n/**\n * Creates a {@link Worker} facade that broadcasts `send()` to all provided\n * workers and aggregates their `'message'` events into one stream.\n *\n * This is useful for code that expects a single Worker for IPC (e.g.\n * `handleProfzRequest`) but needs to reach multiple child workers.\n */\nexport function broadcastWorker(workers: Worker[]): Worker {\n const emitter = new EventEmitter();\n\n for (const w of workers) {\n w.on('message', (message: Serializable, sendHandle?: SendHandle) =>\n emitter.emit('message', message, sendHandle),\n );\n }\n\n const send = <M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n for (const w of workers) {\n w.send(message, sendHandle);\n }\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill = (signal: NodeJS.Signals = 'SIGTERM') => {\n for (const w of workers) {\n w.kill(signal);\n }\n };\n\n return wrap(Object.assign(emitter, {send, kill, pid}));\n}\n"],"mappings":";;;;;AAsEA,SAAS,WACP,MACA,MACa;CACb,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,KAAK,OAAO,MAC1D,OAAO,KAAK;CAEd,OAAO;AACT;;;;;;;;AASA,SAAgB,uBACd,GACA,MACA,SACY;CACZ,MA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d,EAAE,KAAK,SAAS,UAAU;EAE5B,IAAI,UACF,SAAS,IAAI;EAEf,OAAO;CACT;CAEA,MAAM,QAAQ,SAAyB,cAAc;EACnD,KAAK,MAAM,KAAK,SACd,EAAE,KAAK,MAAM;CAEjB;CAEA,OAAO,KAAK,OAAO,OAAO,SAAS;EAAC;EAAM;EAAM;CAAG,CAAC,CAAC;AACvD"}
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * The current version of Zero.
4
4
  */
5
- var version = "1.11.0-canary.35";
5
+ var version = "1.11.0-canary.37";
6
6
  //#endregion
7
7
  export { version };
8
8
 
@@ -71,7 +71,7 @@ function useSuspenseQuery(query, options) {
71
71
  let ttl = DEFAULT_TTL_MS;
72
72
  let suspendUntil = "partial";
73
73
  if (typeof options === "boolean") enabled = options;
74
- else if (options) ({enabled = true, ttl = DEFAULT_TTL_MS, suspendUntil = "complete"} = options);
74
+ else if (options) ({enabled = true, ttl = DEFAULT_TTL_MS, suspendUntil = "partial"} = options);
75
75
  const zero = useZero();
76
76
  const q = useStableQuery(query, zero);
77
77
  const view = q ? viewStore.getView(zero, q, enabled, ttl) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#lastResultType","#lastData","#lastError","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useRef, useSyncExternalStore} from 'react';\nimport {deepEqual} from '../../shared/src/json.ts';\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\ntype StableQueryCache = {\n zero: unknown;\n context: unknown;\n /** The last input, so an unchanged one is an identity compare and nothing else. */\n rawQuery: object;\n /** The `CustomQuery` a query request names; undefined for a plain query. */\n customQuery: unknown;\n args: ReadonlyJSONValue | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n q: Query<any, any, any>;\n};\n\n/**\n * Resolves a query request against the Zero context, reusing the previous\n * result while the request means the same thing.\n *\n * Interning already makes an unchanged *plain* query come back as the same\n * object, so this is aimed at the query-request form -- `queries.issue({id})`\n * -- where every render allocates a fresh request and `addContextToQuery`\n * re-runs the definition. That costs argument validation (a zod parse of\n * byte-identical args) plus a walk of the builder chain, neither of which\n * interning removes: it makes rebuilding the chain cheap and gives the same\n * object back, but only after the work has been done again.\n *\n * A request resolves to the previous query when it names the same\n * `CustomQuery`, the same context, and deep-equal args. Those are exactly the\n * inputs the definition is allowed to depend on: a named query is re-derived\n * on the server from its name and args, so it has to be a pure function of\n * them, or client and server would build different queries.\n *\n * The ref is written during render. That is safe here because it is a pure\n * cache: an entry is derived only from the inputs, so a StrictMode double\n * render or a discarded concurrent render leaves it valid either way.\n */\nfunction useStableQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema,\n TReturn,\n TContext extends BaseDefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n zero: Zero<TSchema, undefined, TContext>,\n): Query<TTable, TSchema, TReturn> | undefined {\n const cacheRef = useRef<StableQueryCache | undefined>(undefined);\n\n // Deliberately kept rather than cleared: a query toggled off and back on\n // reuses what it had.\n if (!query) {\n return undefined;\n }\n\n const cache = cacheRef.current;\n if (cache && cache.zero === zero) {\n if (cache.rawQuery === query) {\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n if (\n 'query' in query &&\n cache.customQuery === query.query &&\n cache.context === zero.context &&\n deepEqual(cache.args, query.args)\n ) {\n // Same meaning, new wrapper object: remember it so the next render is\n // the identity compare above.\n cache.rawQuery = query;\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n }\n\n const q = addContextToQuery(query, zero.context);\n const isRequest = 'query' in query;\n cacheRef.current = {\n zero: zero,\n context: zero.context,\n rawQuery: query,\n customQuery: isRequest ? query.query : undefined,\n args: isRequest ? query.args : undefined,\n q,\n };\n return q;\n}\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' or 'cached' (in which case\n * results may be empty: a server-confirmed empty answer, from this\n * connection or a previous one, is something to render). This is useful\n * for suspending until there are partial optimistic local results, or\n * the query has completed loading from the 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 = useStableQuery(query, zero);\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 = useStableQuery(query, zero);\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 resultTypeCached = {type: 'cached'} 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 emptySnapshotSingularCached = [undefined, resultTypeCached] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralCached = [emptyArray, resultTypeCached] 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 case 'cached':\n return emptySnapshotSingularCached 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 case 'cached':\n return emptySnapshotPluralCached 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 case 'cached':\n return [data, resultTypeCached];\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 // Inputs of the previous #onData call. When a view flush delivers\n // reference-identical data with the same resultType and error, the previous\n // snapshot tuple is kept and React is not notified — building a fresh tuple\n // would defeat useSyncExternalStore's Object.is bailout and re-render every\n // subscriber with identical data. #lastResultType doubles as the \"has fired\n // before\" sentinel (data and error may both legitimately be undefined).\n #lastData: Immutable<HumanReadable<TReturn>> | undefined;\n #lastResultType: ResultType | undefined;\n #lastError: ErroredQuery | 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 const wasCached = this.#snapshot[1].type === 'cached';\n const changed =\n this.#lastResultType === undefined ||\n this.#lastData !== snap ||\n this.#lastResultType !== resultType ||\n this.#lastError !== error;\n this.#lastData = snap;\n this.#lastResultType = resultType;\n this.#lastError = error;\n\n if (changed) {\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 }\n\n // The resolver bookkeeping runs even when unchanged: after a\n // destroy/re-materialize cycle the resolvers are fresh but the new view\n // may deliver the same data/resultType as before the destroy.\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 const hasData = this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0;\n // A 'cached' result is the server-confirmed answer from a previous\n // session, so even an empty one is something to render. It never\n // satisfies `complete`; only a confirmation on this connection does.\n if (resultType === 'cached' || hasData) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n } else if (wasCached && resultType === 'unknown') {\n // The cached claim was revoked (the got key was evicted before this\n // connection confirmed the query) and the view is empty: there is\n // nothing to render again until rows or a confirmation arrive.\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n }\n\n if (changed) {\n for (const internals of this.#reactInternals) {\n internals();\n }\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 // `getView` calls this on every render, and forwarding an unchanged TTL\n // reaches the query manager, which re-derives the query's id from its AST\n // to find the entry. Nothing downstream distinguishes a repeat, so skip\n // it. A change in how the same duration is spelled ('60s' vs 60000) is\n // still a change here and still propagates, as it did before.\n if (this.#ttl === ttl) {\n return;\n }\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 non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qB;EAC1B,aAAa;GACX,KAAKL,gBAAgB,OAAO,SAAS;GAGrC,IAAI,KAAKA,gBAAgB,SAAS,GAChC,KAAKgB,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKd,gBAAgB,OAAO,GAC9B;IAGF,KAAKc,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKf,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EAMxB,IAAI,KAAKK,SAAS,KAChB;EAEF,KAAKA,OAAO;EACZ,KAAKW,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","#lastResultType","#lastData","#lastError","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useRef, useSyncExternalStore} from 'react';\nimport {deepEqual} from '../../shared/src/json.ts';\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\ntype StableQueryCache = {\n zero: unknown;\n context: unknown;\n /** The last input, so an unchanged one is an identity compare and nothing else. */\n rawQuery: object;\n /** The `CustomQuery` a query request names; undefined for a plain query. */\n customQuery: unknown;\n args: ReadonlyJSONValue | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n q: Query<any, any, any>;\n};\n\n/**\n * Resolves a query request against the Zero context, reusing the previous\n * result while the request means the same thing.\n *\n * Interning already makes an unchanged *plain* query come back as the same\n * object, so this is aimed at the query-request form -- `queries.issue({id})`\n * -- where every render allocates a fresh request and `addContextToQuery`\n * re-runs the definition. That costs argument validation (a zod parse of\n * byte-identical args) plus a walk of the builder chain, neither of which\n * interning removes: it makes rebuilding the chain cheap and gives the same\n * object back, but only after the work has been done again.\n *\n * A request resolves to the previous query when it names the same\n * `CustomQuery`, the same context, and deep-equal args. Those are exactly the\n * inputs the definition is allowed to depend on: a named query is re-derived\n * on the server from its name and args, so it has to be a pure function of\n * them, or client and server would build different queries.\n *\n * The ref is written during render. That is safe here because it is a pure\n * cache: an entry is derived only from the inputs, so a StrictMode double\n * render or a discarded concurrent render leaves it valid either way.\n */\nfunction useStableQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema,\n TReturn,\n TContext extends BaseDefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n zero: Zero<TSchema, undefined, TContext>,\n): Query<TTable, TSchema, TReturn> | undefined {\n const cacheRef = useRef<StableQueryCache | undefined>(undefined);\n\n // Deliberately kept rather than cleared: a query toggled off and back on\n // reuses what it had.\n if (!query) {\n return undefined;\n }\n\n const cache = cacheRef.current;\n if (cache && cache.zero === zero) {\n if (cache.rawQuery === query) {\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n if (\n 'query' in query &&\n cache.customQuery === query.query &&\n cache.context === zero.context &&\n deepEqual(cache.args, query.args)\n ) {\n // Same meaning, new wrapper object: remember it so the next render is\n // the identity compare above.\n cache.rawQuery = query;\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n }\n\n const q = addContextToQuery(query, zero.context);\n const isRequest = 'query' in query;\n cacheRef.current = {\n zero: zero,\n context: zero.context,\n rawQuery: query,\n customQuery: isRequest ? query.query : undefined,\n args: isRequest ? query.args : undefined,\n q,\n };\n return q;\n}\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' or 'cached' (in which case\n * results may be empty: a server-confirmed empty answer, from this\n * connection or a previous one, is something to render). This is useful\n * for suspending until there are partial optimistic local results, or\n * the query has completed loading from the 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 = useStableQuery(query, zero);\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 = 'partial',\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 = useStableQuery(query, zero);\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 resultTypeCached = {type: 'cached'} 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 emptySnapshotSingularCached = [undefined, resultTypeCached] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralCached = [emptyArray, resultTypeCached] 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 case 'cached':\n return emptySnapshotSingularCached 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 case 'cached':\n return emptySnapshotPluralCached 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 case 'cached':\n return [data, resultTypeCached];\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 // Inputs of the previous #onData call. When a view flush delivers\n // reference-identical data with the same resultType and error, the previous\n // snapshot tuple is kept and React is not notified — building a fresh tuple\n // would defeat useSyncExternalStore's Object.is bailout and re-render every\n // subscriber with identical data. #lastResultType doubles as the \"has fired\n // before\" sentinel (data and error may both legitimately be undefined).\n #lastData: Immutable<HumanReadable<TReturn>> | undefined;\n #lastResultType: ResultType | undefined;\n #lastError: ErroredQuery | 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 const wasCached = this.#snapshot[1].type === 'cached';\n const changed =\n this.#lastResultType === undefined ||\n this.#lastData !== snap ||\n this.#lastResultType !== resultType ||\n this.#lastError !== error;\n this.#lastData = snap;\n this.#lastResultType = resultType;\n this.#lastError = error;\n\n if (changed) {\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 }\n\n // The resolver bookkeeping runs even when unchanged: after a\n // destroy/re-materialize cycle the resolvers are fresh but the new view\n // may deliver the same data/resultType as before the destroy.\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 const hasData = this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0;\n // A 'cached' result is the server-confirmed answer from a previous\n // session, so even an empty one is something to render. It never\n // satisfies `complete`; only a confirmation on this connection does.\n if (resultType === 'cached' || hasData) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n } else if (wasCached && resultType === 'unknown') {\n // The cached claim was revoked (the got key was evicted before this\n // connection confirmed the query) and the view is empty: there is\n // nothing to render again until rows or a confirmation arrive.\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n }\n\n if (changed) {\n for (const internals of this.#reactInternals) {\n internals();\n }\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 // `getView` calls this on every render, and forwarding an unchanged TTL\n // reaches the query manager, which re-derives the query's id from its AST\n // to find the entry. Nothing downstream distinguishes a repeat, so skip\n // it. A change in how the same duration is spelled ('60s' vs 60000) is\n // still a change here and still propagates, as it did before.\n if (this.#ttl === ttl) {\n return;\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAS,eAQP,OAGA,MAC6C;CAC7C,MAAM,WAAW,OAAqC,KAAA,CAAS;CAI/D,IAAI,CAAC,OACH;CAGF,MAAM,QAAQ,SAAS;CACvB,IAAI,SAAS,MAAM,SAAS,MAAM;EAChC,IAAI,MAAM,aAAa,OACrB,OAAO,MAAM;EAEf,IACE,WAAW,SACX,MAAM,gBAAgB,MAAM,SAC5B,MAAM,YAAY,KAAK,WACvB,UAAU,MAAM,MAAM,MAAM,IAAI,GAChC;GAGA,MAAM,WAAW;GACjB,OAAO,MAAM;EACf;CACF;CAEA,MAAM,IAAI,kBAAkB,OAAO,KAAK,OAAO;CAC/C,MAAM,YAAY,WAAW;CAC7B,SAAS,UAAU;EACX;EACN,SAAS,KAAK;EACd,UAAU;EACV,aAAa,YAAY,MAAM,QAAQ,KAAA;EACvC,MAAM,YAAY,MAAM,OAAO,KAAA;EAC/B;CACF;CACA,OAAO;AACT;AA2CA,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,eAAe,OAAO,IAAI;CACpC,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,MAA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,qBAAqB;EAC1B,aAAa;GACX,KAAKL,gBAAgB,OAAO,SAAS;GAGrC,IAAI,KAAKA,gBAAgB,SAAS,GAChC,KAAKgB,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKd,gBAAgB,OAAO,GAC9B;IAGF,KAAKc,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKf,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EAMxB,IAAI,KAAKK,SAAS,KAChB;EAEF,KAAKA,OAAO;EACZ,KAAKW,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 +1 @@
1
- {"version":3,"file":"process-queries.d.ts","sourceRoot":"","sources":["../../../../../zero-server/src/queries/process-queries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,kBAAkB,CAAC;AAG/C,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8BAA8B,CAAC;AAW/D,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,4CAA4C,CAAC;AAE9E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAG9D,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,iCAAiC,CAAC;AAG9D;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CAAC,CAA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vD,OAAO,EAAE,OAAO,CAAC;CAClB,GACD;IACE,yDAAyD;IACzD,KAAK,EAAE,iBAAiB,CAAC;IACzB,kDAAkD;IAClD,IAAI,EAAE,iBAAiB,CAAC;CACzB,CACJ,CAAC;AAuBF;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,EACjD,KAAK,EAAE,sBAAsB,CAAC,CAAC,CAAC,GAC/B,OAAO,CAAC,aAAa,CAAC,CAAC;AAE1B;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,EACjD,cAAc,EAAE,mBAAmB,EACnC,MAAM,EAAE,CAAC,EACT,OAAO,EAAE,OAAO,EAChB,QAAQ,CAAC,EAAE,QAAQ,GAClB,OAAO,CAAC,aAAa,CAAC,CAAC;AAE1B;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,EACjD,cAAc,EAAE,mBAAmB,EACnC,MAAM,EAAE,CAAC,EACT,QAAQ,EAAE,iBAAiB,EAC3B,QAAQ,CAAC,EAAE,QAAQ,GAClB,OAAO,CAAC,aAAa,CAAC,CAAC;AA6K1B;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB,GAAG,CAChC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,iBAAiB,GAAG,SAAS,KAChC,QAAQ,CAAC;AAEd,qDAAqD;AACrD,MAAM,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AAEzD,MAAM,MAAM,yBAAyB,GAAG,CACtC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,SAAS,iBAAiB,EAAE,KAC/B,YAAY,CAAC;IAAC,KAAK,EAAE,QAAQ,CAAA;CAAC,GAAG,QAAQ,CAAC,CAAC"}
@@ -69,7 +69,7 @@ async function transform(args, apiName) {
69
69
  let body;
70
70
  if (args.type === "request") body = await args.request.json();
71
71
  else body = args.jsonBody;
72
- parsed = parse(body, transformRequestMessageSchema);
72
+ parsed = parse(body, transformRequestMessageSchema, "strip");
73
73
  queryIDs = parsed[1].map((r) => r.id);
74
74
  } catch (error) {
75
75
  lc.error?.(`Failed to parse ${apiName} request`, error);
@@ -1 +1 @@
1
- {"version":3,"file":"process-queries.js","names":[],"sources":["../../../../../zero-server/src/queries/process-queries.ts"],"sourcesContent":["import type {LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport type {MaybePromise} from '../../../shared/src/types.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {mapAST} from '../../../zero-protocol/src/ast.ts';\nimport {\n transformRequestMessageSchema,\n type TransformRequestMessage,\n type TransformResponseBody,\n} from '../../../zero-protocol/src/custom-queries.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport type {QueryResponse} from '../../../zero-protocol/src/query-server.ts';\nimport {clientToServer} from '../../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {QueryParseError} from '../../../zql/src/query/error.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {AnyQuery} from '../../../zql/src/query/query.ts';\nimport {createLogContext} from '../logging.ts';\n\n/**\n * Invokes the callback `cb` for each query in the request or JSON body.\n * The callback should return a Query or Promise<Query> that is the transformed result.\n *\n * This function will call `cb` in parallel for each query found in the request.\n *\n * If you need to limit concurrency, you can use a library like `p-limit` to wrap the `cb` function.\n * @deprecated Use {@linkcode handleQueryRequest} instead.\n */\nexport function handleGetQueriesRequest<S extends Schema>(\n cb: (\n name: string,\n args: readonly ReadonlyJSONValue[],\n ) => MaybePromise<{query: AnyQuery} | AnyQuery>,\n schema: S,\n requestOrJsonBody: Request | ReadonlyJSONValue,\n logLevel: LogLevel = 'info',\n): Promise<QueryResponse> {\n return transform(\n normalizeLegacyQueryRequestArgs(cb, schema, requestOrJsonBody, logLevel),\n 'getQueries',\n );\n}\n\n/**\n * Invokes the callback `cb` for each query in the request or JSON body.\n * The callback should return a Query or Promise<Query> that is the transformed result.\n *\n * This function will call `cb` in parallel for each query found in the request.\n *\n * If you need to limit concurrency, you can use a library like `p-limit` to wrap the `cb` function.\n * @deprecated Use {@linkcode handleQueryRequest} instead.\n */\nexport function handleTransformRequest<S extends Schema>(\n cb: (\n name: string,\n args: readonly ReadonlyJSONValue[],\n ) => MaybePromise<{query: AnyQuery} | AnyQuery>,\n schema: S,\n requestOrJsonBody: Request | ReadonlyJSONValue,\n logLevel: LogLevel = 'info',\n): Promise<QueryResponse> {\n return transform(\n normalizeLegacyQueryRequestArgs(cb, schema, requestOrJsonBody, logLevel),\n 'transform',\n );\n}\n\n/**\n * Parsed query params accepted by {@linkcode handleQueryRequest} when the\n * incoming request URL has already been handled by your framework.\n */\nexport type QuerySearchParams = URLSearchParams | Record<string, string>;\n\nexport type HandleQueryRequestArgs<S extends Schema> = {\n /** Callback that transforms each requested query into a `Query`. */\n handler: QueryRequestHandler;\n /** Schema used when building the returned ASTs. */\n schema: S;\n /**\n * Authenticated user ID. Null or undefined means the user is logged out.\n */\n userID: string | null | undefined;\n /** Optional log level for request parsing and execution. */\n logLevel?: LogLevel | undefined;\n} & (\n | {\n /** Fetch request containing the `/query` JSON body. */\n request: Request;\n }\n | {\n /** Parsed query params from the `/query` request URL. */\n query: QuerySearchParams;\n /** Parsed JSON body from the `/query` request. */\n body: ReadonlyJSONValue;\n }\n);\n\ntype NormalizedQueryRequestArgs<S extends Schema> = {\n readonly schema: S;\n readonly handler: LegacyQueryRequestHandler;\n // Note: semantics of undefined differ from HandleQueryRequestArgs.userID.\n // Here, undefined means the app didn't provide a user ID - we do not know if\n // the user is logged in or not. This is legacy behavior needed to support\n // deprecated signatures of handleQueryRequest which did not receive userID\n // from app.\n readonly userID: string | null | undefined;\n readonly logLevel: LogLevel;\n} & (\n | {\n readonly type: 'request';\n readonly request: Request;\n }\n | {\n readonly type: 'body';\n readonly jsonBody: ReadonlyJSONValue;\n }\n);\n\n/**\n * Process a `/query` request from a Fetch `Request`.\n */\nexport function handleQueryRequest<S extends Schema>(\n input: HandleQueryRequestArgs<S>,\n): Promise<QueryResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleQueryRequest({handler, schema, request, userID, logLevel})`.\n */\nexport function handleQueryRequest<S extends Schema>(\n transformQuery: QueryRequestHandler,\n schema: S,\n request: Request,\n logLevel?: LogLevel,\n): Promise<QueryResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleQueryRequest({handler, schema, body, userID, logLevel})`.\n */\nexport function handleQueryRequest<S extends Schema>(\n transformQuery: QueryRequestHandler,\n schema: S,\n jsonBody: ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<QueryResponse>;\n\nexport function handleQueryRequest<S extends Schema>(\n inputOrTransformQuery: HandleQueryRequestArgs<S> | QueryRequestHandler,\n schema?: S,\n requestOrJsonBody?: Request | ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<QueryResponse> {\n const normalized =\n typeof inputOrTransformQuery === 'object' &&\n 'handler' in inputOrTransformQuery\n ? normalizeQueryRequestInput(inputOrTransformQuery)\n : normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(inputOrTransformQuery),\n schema,\n requestOrJsonBody,\n logLevel,\n );\n\n return transform(normalized, 'query');\n}\n\nfunction normalizeQueryRequestInput<S extends Schema>(\n input: HandleQueryRequestArgs<S>,\n): NormalizedQueryRequestArgs<S> {\n return 'request' in input\n ? normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(input.handler),\n input.schema,\n input.request,\n input.logLevel,\n input.userID ?? null,\n )\n : normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(input.handler),\n input.schema,\n input.body,\n input.logLevel,\n input.userID ?? null,\n );\n}\n\nfunction normalizeLegacyQueryRequestArgs<S extends Schema>(\n handler: LegacyQueryRequestHandler,\n schema: S | undefined,\n requestOrJsonBody: Request | ReadonlyJSONValue | undefined,\n logLevel: LogLevel | undefined,\n userID?: string | null,\n): NormalizedQueryRequestArgs<S> {\n assert(\n typeof schema !== 'undefined',\n 'Schema must be provided when using handleQueryRequest',\n );\n\n if (requestOrJsonBody instanceof Request) {\n return {\n type: 'request',\n handler,\n schema,\n request: requestOrJsonBody,\n userID,\n logLevel: logLevel ?? 'info',\n };\n }\n\n assert(\n typeof requestOrJsonBody !== 'undefined',\n 'JSON body cannot be undefined',\n );\n\n return {\n type: 'body',\n handler,\n schema,\n jsonBody: requestOrJsonBody,\n userID,\n logLevel: logLevel ?? 'info',\n };\n}\n\nasync function transform<S extends Schema>(\n args: NormalizedQueryRequestArgs<S>,\n apiName: 'query' | 'transform' | 'getQueries',\n): Promise<QueryResponse> {\n const lc = createLogContext(args.logLevel).withContext('TransformRequest');\n let parsed: TransformRequestMessage;\n let queryIDs: string[] = [];\n try {\n let body: ReadonlyJSONValue;\n if (args.type === 'request') {\n body = await args.request.json();\n } else {\n body = args.jsonBody;\n }\n\n parsed = v.parse(body, transformRequestMessageSchema);\n\n queryIDs = parsed[1].map(r => r.id);\n } catch (error) {\n lc.error?.(`Failed to parse ${apiName} request`, error);\n\n const message = `Failed to parse ${apiName} request: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n queryIDs,\n ...(details ? {details} : {}),\n };\n }\n\n try {\n const nameMapper = clientToServer(args.schema.tables);\n\n const responses: TransformResponseBody = await Promise.all(\n parsed[1].map(async req => {\n let finalQuery: AnyQuery;\n try {\n const result = await args.handler(req.name, req.args);\n finalQuery = 'query' in result ? result.query : result;\n } catch (error) {\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n error: error instanceof QueryParseError ? 'parse' : 'app',\n id: req.id,\n name: req.name,\n message,\n ...(details ? {details} : {}),\n };\n }\n\n try {\n const q = asQueryInternals(finalQuery);\n const ast = mapAST(q.ast, nameMapper);\n\n return {\n id: req.id,\n name: req.name,\n ast,\n };\n } catch (error) {\n lc.error?.('Failed to map AST', error);\n throw error;\n }\n }),\n );\n\n return {\n kind: 'QueryResponse',\n queries: responses,\n ...(typeof args.userID !== 'undefined' ? {userID: args.userID} : {}),\n } as const satisfies QueryResponse;\n } catch (e) {\n const message = getErrorMessage(e);\n const details = getErrorDetails(e);\n\n return {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message,\n queryIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\n/**\n * A function that transforms a query by name and arguments into a Query object.\n *\n * @param name - The name of the query (can be dot-separated for nested queries)\n * @param args - The arguments to pass to the query (can be undefined)\n * @returns A Query object\n */\nexport type QueryRequestHandler = (\n name: string,\n args: ReadonlyJSONValue | undefined,\n) => AnyQuery;\n\n/** @deprecated Use `QueryRequestHandler` instead. */\nexport type TransformQueryFunction = QueryRequestHandler;\n\nexport type LegacyQueryRequestHandler = (\n name: string,\n args: readonly ReadonlyJSONValue[],\n) => MaybePromise<{query: AnyQuery} | AnyQuery>;\n\nfunction wrapQueryRequestHandler(\n handler: QueryRequestHandler,\n): LegacyQueryRequestHandler {\n return (name, args) => handler(name, args[0]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,wBACd,IAIA,QACA,mBACA,WAAqB,QACG;CACxB,OAAO,UACL,gCAAgC,IAAI,QAAQ,mBAAmB,QAAQ,GACvE,YACF;AACF;;;;;;;;;;AAWA,SAAgB,uBACd,IAIA,QACA,mBACA,WAAqB,QACG;CACxB,OAAO,UACL,gCAAgC,IAAI,QAAQ,mBAAmB,QAAQ,GACvE,WACF;AACF;AAkFA,SAAgB,mBACd,uBACA,QACA,mBACA,UACwB;CAYxB,OAAO,UAVL,OAAO,0BAA0B,YACjC,aAAa,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AAM;EAqCpD,OAAO;GACL,MAAM;GACN,SAAS,MArCoC,QAAQ,IACrD,OAAO,GAAG,IAAI,OAAM,QAAO;IACzB,IAAI;IACJ,IAAI;KACF,MAAM,SAAS,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI;KACpD,aAAa,WAAW,SAAS,OAAO,QAAQ;IAClD,SAAS,OAAO;KACd,MAAM,UAAU,gBAAgB,KAAK;KACrC,MAAM,UAAU,gBAAgB,KAAK;KAErC,OAAO;MACL,OAAO,iBAAiB,kBAAkB,UAAU;MACpD,IAAI,IAAI;MACR,MAAM,IAAI;MACV;MACA,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC;KAC7B;IACF;IAEA,IAAI;KAEF,MAAM,MAAM,OADF,iBAAiB,UACR,EAAE,KAAK,UAAU;KAEpC,OAAO;MACL,IAAI,IAAI;MACR,MAAM,IAAI;MACV;KACF;IACF,SAAS,OAAO;KACd,GAAG,QAAQ,qBAAqB,KAAK;KACrC,MAAM;IACR;GACF,CAAC,CACH;GAKE,GAAI,OAAO,KAAK,WAAW,cAAc,EAAC,QAAQ,KAAK,OAAM,IAAI,CAAC;EACpE;CACF,SAAS,GAAG;EACV,MAAM,UAAU,gBAAgB,CAAC;EACjC,MAAM,UAAU,gBAAgB,CAAC;EAEjC,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ;GACR;GACA;GACA,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC;EAC7B;CACF;AACF;AAsBA,SAAS,wBACP,SAC2B;CAC3B,QAAQ,MAAM,SAAS,QAAQ,MAAM,KAAK,EAAE;AAC9C"}
1
+ {"version":3,"file":"process-queries.js","names":[],"sources":["../../../../../zero-server/src/queries/process-queries.ts"],"sourcesContent":["import type {LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport type {MaybePromise} from '../../../shared/src/types.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {mapAST} from '../../../zero-protocol/src/ast.ts';\nimport {\n transformRequestMessageSchema,\n type TransformRequestMessage,\n type TransformResponseBody,\n} from '../../../zero-protocol/src/custom-queries.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport type {QueryResponse} from '../../../zero-protocol/src/query-server.ts';\nimport {clientToServer} from '../../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {QueryParseError} from '../../../zql/src/query/error.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {AnyQuery} from '../../../zql/src/query/query.ts';\nimport {createLogContext} from '../logging.ts';\n\n/**\n * Invokes the callback `cb` for each query in the request or JSON body.\n * The callback should return a Query or Promise<Query> that is the transformed result.\n *\n * This function will call `cb` in parallel for each query found in the request.\n *\n * If you need to limit concurrency, you can use a library like `p-limit` to wrap the `cb` function.\n * @deprecated Use {@linkcode handleQueryRequest} instead.\n */\nexport function handleGetQueriesRequest<S extends Schema>(\n cb: (\n name: string,\n args: readonly ReadonlyJSONValue[],\n ) => MaybePromise<{query: AnyQuery} | AnyQuery>,\n schema: S,\n requestOrJsonBody: Request | ReadonlyJSONValue,\n logLevel: LogLevel = 'info',\n): Promise<QueryResponse> {\n return transform(\n normalizeLegacyQueryRequestArgs(cb, schema, requestOrJsonBody, logLevel),\n 'getQueries',\n );\n}\n\n/**\n * Invokes the callback `cb` for each query in the request or JSON body.\n * The callback should return a Query or Promise<Query> that is the transformed result.\n *\n * This function will call `cb` in parallel for each query found in the request.\n *\n * If you need to limit concurrency, you can use a library like `p-limit` to wrap the `cb` function.\n * @deprecated Use {@linkcode handleQueryRequest} instead.\n */\nexport function handleTransformRequest<S extends Schema>(\n cb: (\n name: string,\n args: readonly ReadonlyJSONValue[],\n ) => MaybePromise<{query: AnyQuery} | AnyQuery>,\n schema: S,\n requestOrJsonBody: Request | ReadonlyJSONValue,\n logLevel: LogLevel = 'info',\n): Promise<QueryResponse> {\n return transform(\n normalizeLegacyQueryRequestArgs(cb, schema, requestOrJsonBody, logLevel),\n 'transform',\n );\n}\n\n/**\n * Parsed query params accepted by {@linkcode handleQueryRequest} when the\n * incoming request URL has already been handled by your framework.\n */\nexport type QuerySearchParams = URLSearchParams | Record<string, string>;\n\nexport type HandleQueryRequestArgs<S extends Schema> = {\n /** Callback that transforms each requested query into a `Query`. */\n handler: QueryRequestHandler;\n /** Schema used when building the returned ASTs. */\n schema: S;\n /**\n * Authenticated user ID. Null or undefined means the user is logged out.\n */\n userID: string | null | undefined;\n /** Optional log level for request parsing and execution. */\n logLevel?: LogLevel | undefined;\n} & (\n | {\n /** Fetch request containing the `/query` JSON body. */\n request: Request;\n }\n | {\n /** Parsed query params from the `/query` request URL. */\n query: QuerySearchParams;\n /** Parsed JSON body from the `/query` request. */\n body: ReadonlyJSONValue;\n }\n);\n\ntype NormalizedQueryRequestArgs<S extends Schema> = {\n readonly schema: S;\n readonly handler: LegacyQueryRequestHandler;\n // Note: semantics of undefined differ from HandleQueryRequestArgs.userID.\n // Here, undefined means the app didn't provide a user ID - we do not know if\n // the user is logged in or not. This is legacy behavior needed to support\n // deprecated signatures of handleQueryRequest which did not receive userID\n // from app.\n readonly userID: string | null | undefined;\n readonly logLevel: LogLevel;\n} & (\n | {\n readonly type: 'request';\n readonly request: Request;\n }\n | {\n readonly type: 'body';\n readonly jsonBody: ReadonlyJSONValue;\n }\n);\n\n/**\n * Process a `/query` request from a Fetch `Request`.\n */\nexport function handleQueryRequest<S extends Schema>(\n input: HandleQueryRequestArgs<S>,\n): Promise<QueryResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleQueryRequest({handler, schema, request, userID, logLevel})`.\n */\nexport function handleQueryRequest<S extends Schema>(\n transformQuery: QueryRequestHandler,\n schema: S,\n request: Request,\n logLevel?: LogLevel,\n): Promise<QueryResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleQueryRequest({handler, schema, body, userID, logLevel})`.\n */\nexport function handleQueryRequest<S extends Schema>(\n transformQuery: QueryRequestHandler,\n schema: S,\n jsonBody: ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<QueryResponse>;\n\nexport function handleQueryRequest<S extends Schema>(\n inputOrTransformQuery: HandleQueryRequestArgs<S> | QueryRequestHandler,\n schema?: S,\n requestOrJsonBody?: Request | ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<QueryResponse> {\n const normalized =\n typeof inputOrTransformQuery === 'object' &&\n 'handler' in inputOrTransformQuery\n ? normalizeQueryRequestInput(inputOrTransformQuery)\n : normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(inputOrTransformQuery),\n schema,\n requestOrJsonBody,\n logLevel,\n );\n\n return transform(normalized, 'query');\n}\n\nfunction normalizeQueryRequestInput<S extends Schema>(\n input: HandleQueryRequestArgs<S>,\n): NormalizedQueryRequestArgs<S> {\n return 'request' in input\n ? normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(input.handler),\n input.schema,\n input.request,\n input.logLevel,\n input.userID ?? null,\n )\n : normalizeLegacyQueryRequestArgs(\n wrapQueryRequestHandler(input.handler),\n input.schema,\n input.body,\n input.logLevel,\n input.userID ?? null,\n );\n}\n\nfunction normalizeLegacyQueryRequestArgs<S extends Schema>(\n handler: LegacyQueryRequestHandler,\n schema: S | undefined,\n requestOrJsonBody: Request | ReadonlyJSONValue | undefined,\n logLevel: LogLevel | undefined,\n userID?: string | null,\n): NormalizedQueryRequestArgs<S> {\n assert(\n typeof schema !== 'undefined',\n 'Schema must be provided when using handleQueryRequest',\n );\n\n if (requestOrJsonBody instanceof Request) {\n return {\n type: 'request',\n handler,\n schema,\n request: requestOrJsonBody,\n userID,\n logLevel: logLevel ?? 'info',\n };\n }\n\n assert(\n typeof requestOrJsonBody !== 'undefined',\n 'JSON body cannot be undefined',\n );\n\n return {\n type: 'body',\n handler,\n schema,\n jsonBody: requestOrJsonBody,\n userID,\n logLevel: logLevel ?? 'info',\n };\n}\n\nasync function transform<S extends Schema>(\n args: NormalizedQueryRequestArgs<S>,\n apiName: 'query' | 'transform' | 'getQueries',\n): Promise<QueryResponse> {\n const lc = createLogContext(args.logLevel).withContext('TransformRequest');\n let parsed: TransformRequestMessage;\n let queryIDs: string[] = [];\n try {\n let body: ReadonlyJSONValue;\n if (args.type === 'request') {\n body = await args.request.json();\n } else {\n body = args.jsonBody;\n }\n\n // Strip, so a newer zero-cache can add fields to the request.\n parsed = v.parse(body, transformRequestMessageSchema, 'strip');\n\n queryIDs = parsed[1].map(r => r.id);\n } catch (error) {\n lc.error?.(`Failed to parse ${apiName} request`, error);\n\n const message = `Failed to parse ${apiName} request: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n queryIDs,\n ...(details ? {details} : {}),\n };\n }\n\n try {\n const nameMapper = clientToServer(args.schema.tables);\n\n const responses: TransformResponseBody = await Promise.all(\n parsed[1].map(async req => {\n let finalQuery: AnyQuery;\n try {\n const result = await args.handler(req.name, req.args);\n finalQuery = 'query' in result ? result.query : result;\n } catch (error) {\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n error: error instanceof QueryParseError ? 'parse' : 'app',\n id: req.id,\n name: req.name,\n message,\n ...(details ? {details} : {}),\n };\n }\n\n try {\n const q = asQueryInternals(finalQuery);\n const ast = mapAST(q.ast, nameMapper);\n\n return {\n id: req.id,\n name: req.name,\n ast,\n };\n } catch (error) {\n lc.error?.('Failed to map AST', error);\n throw error;\n }\n }),\n );\n\n return {\n kind: 'QueryResponse',\n queries: responses,\n ...(typeof args.userID !== 'undefined' ? {userID: args.userID} : {}),\n } as const satisfies QueryResponse;\n } catch (e) {\n const message = getErrorMessage(e);\n const details = getErrorDetails(e);\n\n return {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message,\n queryIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\n/**\n * A function that transforms a query by name and arguments into a Query object.\n *\n * @param name - The name of the query (can be dot-separated for nested queries)\n * @param args - The arguments to pass to the query (can be undefined)\n * @returns A Query object\n */\nexport type QueryRequestHandler = (\n name: string,\n args: ReadonlyJSONValue | undefined,\n) => AnyQuery;\n\n/** @deprecated Use `QueryRequestHandler` instead. */\nexport type TransformQueryFunction = QueryRequestHandler;\n\nexport type LegacyQueryRequestHandler = (\n name: string,\n args: readonly ReadonlyJSONValue[],\n) => MaybePromise<{query: AnyQuery} | AnyQuery>;\n\nfunction wrapQueryRequestHandler(\n handler: QueryRequestHandler,\n): LegacyQueryRequestHandler {\n return (name, args) => handler(name, args[0]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,wBACd,IAIA,QACA,mBACA,WAAqB,QACG;CACxB,OAAO,UACL,gCAAgC,IAAI,QAAQ,mBAAmB,QAAQ,GACvE,YACF;AACF;;;;;;;;;;AAWA,SAAgB,uBACd,IAIA,QACA,mBACA,WAAqB,QACG;CACxB,OAAO,UACL,gCAAgC,IAAI,QAAQ,mBAAmB,QAAQ,GACvE,WACF;AACF;AAkFA,SAAgB,mBACd,uBACA,QACA,mBACA,UACwB;CAYxB,OAAO,UAVL,OAAO,0BAA0B,YACjC,aAAa,wBACT,2BAA2B,qBAAqB,IAChD,gCACE,wBAAwB,qBAAqB,GAC7C,QACA,mBACA,QACF,GAEuB,OAAO;AACtC;AAEA,SAAS,2BACP,OAC+B;CAC/B,OAAO,aAAa,QAChB,gCACE,wBAAwB,MAAM,OAAO,GACrC,MAAM,QACN,MAAM,SACN,MAAM,UACN,MAAM,UAAU,IAClB,IACA,gCACE,wBAAwB,MAAM,OAAO,GACrC,MAAM,QACN,MAAM,MACN,MAAM,UACN,MAAM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ErC,OAAO;MACL,OAAO,iBAAiB,kBAAkB,UAAU;MACpD,IAAI,IAAI;MACR,MAAM,IAAI;MACV;MACA,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC;KAC7B;IACF;IAEA,IAAI;KAEF,MAAM,MAAM,OADF,iBAAiB,UACR,EAAE,KAAK,UAAU;KAEpC,OAAO;MACL,IAAI,IAAI;MACR,MAAM,IAAI;MACV;KACF;IACF,SAAS,OAAO;KACd,GAAG,QAAQ,qBAAqB,KAAK;KACrC,MAAM;IACR;GACF,CAAC,CACH;GAKE,GAAI,OAAO,KAAK,WAAW,cAAc,EAAC,QAAQ,KAAK,OAAM,IAAI,CAAC;EACpE;CACF,SAAS,GAAG;EACV,MAAM,UAAU,gBAAgB,CAAC;EACjC,MAAM,UAAU,gBAAgB,CAAC;EAEjC,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ;GACR;GACA;GACA,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC;EAC7B;CACF;AACF;AAsBA,SAAS,wBACP,SAC2B;CAC3B,QAAQ,MAAM,SAAS,QAAQ,MAAM,KAAK,EAAE;AAC9C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocicorp/zero",
3
- "version": "1.11.0-canary.35",
3
+ "version": "1.11.0-canary.37",
4
4
  "description": "Zero is a web framework for serverless web development.",
5
5
  "homepage": "https://zero.rocicorp.dev",
6
6
  "bugs": {