@rocicorp/zero 1.5.0-canary.4 → 1.6.0-canary.1

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 (165) hide show
  1. package/out/replicache/src/btree/node.d.ts +3 -0
  2. package/out/replicache/src/btree/node.d.ts.map +1 -1
  3. package/out/replicache/src/btree/node.js +114 -1
  4. package/out/replicache/src/btree/node.js.map +1 -1
  5. package/out/replicache/src/btree/write.d.ts +7 -0
  6. package/out/replicache/src/btree/write.d.ts.map +1 -1
  7. package/out/replicache/src/btree/write.js +50 -0
  8. package/out/replicache/src/btree/write.js.map +1 -1
  9. package/out/replicache/src/db/write.d.ts +8 -0
  10. package/out/replicache/src/db/write.d.ts.map +1 -1
  11. package/out/replicache/src/db/write.js +15 -0
  12. package/out/replicache/src/db/write.js.map +1 -1
  13. package/out/replicache/src/kv/sqlite-store.d.ts +2 -5
  14. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  15. package/out/replicache/src/kv/sqlite-store.js +21 -24
  16. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  17. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  18. package/out/replicache/src/replicache-impl.js.map +1 -1
  19. package/out/replicache/src/sync/patch.d.ts +15 -0
  20. package/out/replicache/src/sync/patch.d.ts.map +1 -1
  21. package/out/replicache/src/sync/patch.js +85 -26
  22. package/out/replicache/src/sync/patch.js.map +1 -1
  23. package/out/shared/src/testing.d.ts +3 -0
  24. package/out/shared/src/testing.d.ts.map +1 -0
  25. package/out/zero/package.js +5 -6
  26. package/out/zero/package.js.map +1 -1
  27. package/out/zero-cache/src/auth/write-authorizer.js +1 -1
  28. package/out/zero-cache/src/config/zero-config.d.ts +4 -0
  29. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  30. package/out/zero-cache/src/config/zero-config.js +8 -0
  31. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  32. package/out/zero-cache/src/server/inspector-delegate.d.ts +3 -2
  33. package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
  34. package/out/zero-cache/src/server/inspector-delegate.js +19 -9
  35. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  36. package/out/zero-cache/src/server/runner/run-worker.js +1 -1
  37. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +7 -6
  38. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  39. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  40. package/out/zero-cache/src/services/change-source/pg/change-source.js +62 -70
  41. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  42. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +0 -8
  43. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +30 -53
  45. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +57 -0
  47. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -0
  48. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +162 -0
  49. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -0
  50. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +1 -1
  51. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  52. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  53. package/out/zero-cache/src/services/change-source/pg/schema/init.js +19 -1
  54. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  55. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +17 -3
  56. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  57. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +43 -16
  58. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  59. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -3
  60. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  61. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +2 -2
  62. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  63. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +10 -1
  64. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +13 -3
  66. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  67. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +6 -11
  68. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/change-streamer/change-streamer.js +0 -1
  70. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  71. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
  72. package/out/zero-cache/src/services/change-streamer/forwarder.js +2 -2
  73. package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
  74. package/out/zero-cache/src/services/change-streamer/storer.d.ts +12 -5
  75. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  76. package/out/zero-cache/src/services/change-streamer/storer.js +43 -21
  77. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  78. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +4 -5
  79. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  80. package/out/zero-cache/src/services/change-streamer/subscriber.js +18 -16
  81. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  82. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/litestream/commands.js +3 -2
  84. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  85. package/out/zero-cache/src/services/litestream/config.yml +1 -0
  86. package/out/zero-cache/src/services/mutagen/pusher.d.ts +2 -2
  87. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js +7 -0
  88. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js.map +1 -1
  89. package/out/zero-cache/src/services/view-syncer/cvr-store.js +2 -2
  90. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  91. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
  92. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  93. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/view-syncer/view-syncer.js +5 -6
  95. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  96. package/out/zero-cache/src/types/streams.d.ts +4 -0
  97. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  98. package/out/zero-cache/src/types/streams.js +13 -10
  99. package/out/zero-cache/src/types/streams.js.map +1 -1
  100. package/out/zero-cache/src/workers/connection.js +3 -3
  101. package/out/zero-cache/src/workers/connection.js.map +1 -1
  102. package/out/zero-client/src/client/inspector/inspector.d.ts.map +1 -1
  103. package/out/zero-client/src/client/inspector/inspector.js +15 -2
  104. package/out/zero-client/src/client/inspector/inspector.js.map +1 -1
  105. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts +9 -3
  106. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts.map +1 -1
  107. package/out/zero-client/src/client/inspector/lazy-inspector.js +27 -6
  108. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  109. package/out/zero-client/src/client/inspector/query.d.ts.map +1 -1
  110. package/out/zero-client/src/client/inspector/query.js +3 -3
  111. package/out/zero-client/src/client/inspector/query.js.map +1 -1
  112. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  113. package/out/zero-client/src/client/ivm-branch.js +16 -2
  114. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  115. package/out/zero-client/src/client/options.d.ts +12 -4
  116. package/out/zero-client/src/client/options.d.ts.map +1 -1
  117. package/out/zero-client/src/client/options.js.map +1 -1
  118. package/out/zero-client/src/client/query-manager.d.ts +8 -1
  119. package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
  120. package/out/zero-client/src/client/query-manager.js +28 -3
  121. package/out/zero-client/src/client/query-manager.js.map +1 -1
  122. package/out/zero-client/src/client/version.js +1 -1
  123. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  124. package/out/zero-client/src/client/zero.js +12 -11
  125. package/out/zero-client/src/client/zero.js.map +1 -1
  126. package/out/zero-protocol/src/down.d.ts +1 -1
  127. package/out/zero-protocol/src/inspect-down.d.ts +15 -4
  128. package/out/zero-protocol/src/inspect-down.d.ts.map +1 -1
  129. package/out/zero-protocol/src/inspect-down.js +11 -1
  130. package/out/zero-protocol/src/inspect-down.js.map +1 -1
  131. package/out/zero-protocol/src/protocol-version.d.ts +1 -1
  132. package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
  133. package/out/zero-protocol/src/protocol-version.js.map +1 -1
  134. package/out/zero-react/src/use-query.d.ts.map +1 -1
  135. package/out/zero-react/src/use-query.js.map +1 -1
  136. package/out/zero-react/src/zero-provider.d.ts +6 -0
  137. package/out/zero-react/src/zero-provider.d.ts.map +1 -1
  138. package/out/zero-react/src/zero-provider.js +21 -1
  139. package/out/zero-react/src/zero-provider.js.map +1 -1
  140. package/out/zero-solid/src/use-zero.d.ts +6 -0
  141. package/out/zero-solid/src/use-zero.d.ts.map +1 -1
  142. package/out/zero-solid/src/use-zero.js +24 -4
  143. package/out/zero-solid/src/use-zero.js.map +1 -1
  144. package/out/zql/src/builder/builder.js +2 -2
  145. package/out/zql/src/ivm/constraint.d.ts.map +1 -1
  146. package/out/zql/src/ivm/constraint.js.map +1 -1
  147. package/out/zql/src/ivm/flipped-join.d.ts +9 -0
  148. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  149. package/out/zql/src/ivm/flipped-join.js +56 -69
  150. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  151. package/out/zql/src/ivm/memory-source.d.ts +24 -3
  152. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  153. package/out/zql/src/ivm/memory-source.js +162 -7
  154. package/out/zql/src/ivm/memory-source.js.map +1 -1
  155. package/out/zql/src/ivm/operator.d.ts +26 -0
  156. package/out/zql/src/ivm/operator.d.ts.map +1 -1
  157. package/out/zql/src/ivm/operator.js.map +1 -1
  158. package/out/zqlite/src/query-builder.d.ts +14 -2
  159. package/out/zqlite/src/query-builder.d.ts.map +1 -1
  160. package/out/zqlite/src/query-builder.js +32 -1
  161. package/out/zqlite/src/query-builder.js.map +1 -1
  162. package/out/zqlite/src/table-source.d.ts.map +1 -1
  163. package/out/zqlite/src/table-source.js +4 -4
  164. package/out/zqlite/src/table-source.js.map +1 -1
  165. package/package.json +5 -6
@@ -51,9 +51,9 @@ var Query = class {
51
51
  const n = merged[name].quantile(percentile);
52
52
  return Number.isNaN(n) ? null : n;
53
53
  };
54
- this.hydrateClient = percentile("query-materialization-client", .5);
55
- this.hydrateServer = percentile("query-materialization-server", .5);
56
- this.hydrateTotal = percentile("query-materialization-end-to-end", .5);
54
+ this.hydrateClient = clientMetrics?.["query-materialization-client"] ?? null;
55
+ this.hydrateServer = serverMetrics?.["query-hydration-server-ms"] ?? null;
56
+ this.hydrateTotal = clientMetrics?.["query-materialization-end-to-end"] ?? null;
57
57
  this.updateClientP50 = percentile("query-update-client", .5);
58
58
  this.updateClientP95 = percentile("query-update-client", .95);
59
59
  this.updateServerP50 = percentile("query-update-server", .5);
@@ -1 +1 @@
1
- {"version":3,"file":"query.js","names":["#socket","#serverAST"],"sources":["../../../../../../zero-client/src/client/inspector/query.ts"],"sourcesContent":["import {astToZQL} from '../../../../ast-to-zql/src/ast-to-zql.ts';\nimport type {ReadonlyJSONValue} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport type {AnalyzeQueryResult} from '../../../../zero-protocol/src/analyze-query-result.ts';\nimport type {AST} from '../../../../zero-protocol/src/ast.ts';\nimport {\n type InspectQueryRow,\n inspectAnalyzeQueryDownSchema,\n} from '../../../../zero-protocol/src/inspect-down.ts';\nimport type {AnalyzeQueryOptions} from '../../../../zero-protocol/src/inspect-up.ts';\nimport {type TTL, normalizeTTL} from '../../../../zql/src/query/ttl.ts';\nimport {\n type ExtendedInspectorDelegate,\n type GetWebSocket,\n type Metrics,\n mergeMetrics,\n rpc,\n} from './lazy-inspector.ts';\n\nexport class Query {\n readonly #socket: GetWebSocket;\n\n readonly name: string | null;\n readonly args: ReadonlyArray<ReadonlyJSONValue> | null;\n readonly got: boolean;\n readonly ttl: TTL;\n readonly inactivatedAt: Date | null;\n readonly rowCount: number;\n readonly deleted: boolean;\n readonly id: string;\n readonly clientID: string;\n readonly metrics: Metrics | null;\n readonly clientZQL: string | null;\n readonly serverZQL: string | null;\n readonly #serverAST: AST | null;\n\n readonly hydrateClient: number | null;\n readonly hydrateServer: number | null;\n readonly hydrateTotal: number | null;\n\n readonly updateClientP50: number | null;\n readonly updateClientP95: number | null;\n readonly updateServerP50: number | null;\n readonly updateServerP95: number | null;\n\n constructor(\n row: InspectQueryRow,\n delegate: ExtendedInspectorDelegate,\n socket: GetWebSocket,\n ) {\n this.#socket = socket;\n\n const {ast, queryID, inactivatedAt} = row;\n // Use own properties to make this more useful in dev tools. For example, in\n // Chrome dev tools, if you do console.table(queries) you'll see the\n // properties in the table, if these were getters you would not see them in the table.\n this.clientID = row.clientID;\n this.id = queryID;\n this.inactivatedAt =\n inactivatedAt === null ? null : new Date(inactivatedAt);\n this.ttl = normalizeTTL(row.ttl);\n this.name = row.name;\n this.args = row.args;\n this.got = row.got;\n this.rowCount = row.rowCount;\n this.deleted = row.deleted;\n this.#serverAST = ast;\n this.serverZQL = ast ? ast.table + astToZQL(ast) : null;\n const clientAST = delegate.getAST(queryID);\n this.clientZQL = clientAST ? clientAST.table + astToZQL(clientAST) : null;\n\n // Merge client and server metrics\n const clientMetrics = delegate.getQueryMetrics(queryID);\n const serverMetrics = row.metrics;\n\n const merged = mergeMetrics(clientMetrics, serverMetrics);\n this.metrics = merged;\n\n const percentile = (\n name: keyof typeof merged,\n percentile: number,\n ): number | null => {\n if (!merged?.[name]) {\n return null;\n }\n const n = merged[name].quantile(percentile);\n return Number.isNaN(n) ? null : n;\n };\n\n // Extract hydration metrics (median values) - handle NaN by defaulting to 0\n this.hydrateClient = percentile('query-materialization-client', 0.5);\n this.hydrateServer = percentile('query-materialization-server', 0.5);\n this.hydrateTotal = percentile('query-materialization-end-to-end', 0.5);\n\n // Extract update metrics (P50 and P95) - handle NaN by defaulting to 0\n this.updateClientP50 = percentile('query-update-client', 0.5);\n this.updateClientP95 = percentile('query-update-client', 0.95);\n\n this.updateServerP50 = percentile('query-update-server', 0.5);\n this.updateServerP95 = percentile('query-update-server', 0.95);\n }\n\n async analyze(options?: AnalyzeQueryOptions): Promise<AnalyzeQueryResult> {\n const details =\n this.name && this.args\n ? {\n name: this.name,\n args: this.args,\n }\n : {value: must(this.#serverAST, 'AST is required for unnamed queries')};\n\n return rpc(\n await this.#socket(),\n {\n op: 'analyze-query',\n ...details,\n options,\n },\n inspectAnalyzeQueryDownSchema,\n );\n }\n}\n"],"mappings":";;;;;;AAmBA,IAAa,QAAb,MAAmB;CACjB;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CAEA,YACE,KACA,UACA,QACA;AACA,QAAA,SAAe;EAEf,MAAM,EAAC,KAAK,SAAS,kBAAiB;AAItC,OAAK,WAAW,IAAI;AACpB,OAAK,KAAK;AACV,OAAK,gBACH,kBAAkB,OAAO,OAAO,IAAI,KAAK,cAAc;AACzD,OAAK,MAAM,aAAa,IAAI,IAAI;AAChC,OAAK,OAAO,IAAI;AAChB,OAAK,OAAO,IAAI;AAChB,OAAK,MAAM,IAAI;AACf,OAAK,WAAW,IAAI;AACpB,OAAK,UAAU,IAAI;AACnB,QAAA,YAAkB;AAClB,OAAK,YAAY,MAAM,IAAI,QAAQ,SAAS,IAAI,GAAG;EACnD,MAAM,YAAY,SAAS,OAAO,QAAQ;AAC1C,OAAK,YAAY,YAAY,UAAU,QAAQ,SAAS,UAAU,GAAG;EAGrE,MAAM,gBAAgB,SAAS,gBAAgB,QAAQ;EACvD,MAAM,gBAAgB,IAAI;EAE1B,MAAM,SAAS,aAAa,eAAe,cAAc;AACzD,OAAK,UAAU;EAEf,MAAM,cACJ,MACA,eACkB;AAClB,OAAI,CAAC,SAAS,MACZ,QAAO;GAET,MAAM,IAAI,OAAO,MAAM,SAAS,WAAW;AAC3C,UAAO,OAAO,MAAM,EAAE,GAAG,OAAO;;AAIlC,OAAK,gBAAgB,WAAW,gCAAgC,GAAI;AACpE,OAAK,gBAAgB,WAAW,gCAAgC,GAAI;AACpE,OAAK,eAAe,WAAW,oCAAoC,GAAI;AAGvE,OAAK,kBAAkB,WAAW,uBAAuB,GAAI;AAC7D,OAAK,kBAAkB,WAAW,uBAAuB,IAAK;AAE9D,OAAK,kBAAkB,WAAW,uBAAuB,GAAI;AAC7D,OAAK,kBAAkB,WAAW,uBAAuB,IAAK;;CAGhE,MAAM,QAAQ,SAA4D;EACxE,MAAM,UACJ,KAAK,QAAQ,KAAK,OACd;GACE,MAAM,KAAK;GACX,MAAM,KAAK;GACZ,GACD,EAAC,OAAO,KAAK,MAAA,WAAiB,sCAAsC,EAAC;AAE3E,SAAO,IACL,MAAM,MAAA,QAAc,EACpB;GACE,IAAI;GACJ,GAAG;GACH;GACD,EACD,8BACD"}
1
+ {"version":3,"file":"query.js","names":["#socket","#serverAST"],"sources":["../../../../../../zero-client/src/client/inspector/query.ts"],"sourcesContent":["import {astToZQL} from '../../../../ast-to-zql/src/ast-to-zql.ts';\nimport type {ReadonlyJSONValue} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport type {AnalyzeQueryResult} from '../../../../zero-protocol/src/analyze-query-result.ts';\nimport type {AST} from '../../../../zero-protocol/src/ast.ts';\nimport {\n type InspectQueryRow,\n inspectAnalyzeQueryDownSchema,\n} from '../../../../zero-protocol/src/inspect-down.ts';\nimport type {AnalyzeQueryOptions} from '../../../../zero-protocol/src/inspect-up.ts';\nimport {type TTL, normalizeTTL} from '../../../../zql/src/query/ttl.ts';\nimport {\n type ExtendedInspectorDelegate,\n type GetWebSocket,\n type Metrics,\n mergeMetrics,\n rpc,\n} from './lazy-inspector.ts';\n\nexport class Query {\n readonly #socket: GetWebSocket;\n\n readonly name: string | null;\n readonly args: ReadonlyArray<ReadonlyJSONValue> | null;\n readonly got: boolean;\n readonly ttl: TTL;\n readonly inactivatedAt: Date | null;\n readonly rowCount: number;\n readonly deleted: boolean;\n readonly id: string;\n readonly clientID: string;\n readonly metrics: Metrics | null;\n readonly clientZQL: string | null;\n readonly serverZQL: string | null;\n readonly #serverAST: AST | null;\n\n readonly hydrateClient: number | null;\n readonly hydrateServer: number | null;\n readonly hydrateTotal: number | null;\n\n readonly updateClientP50: number | null;\n readonly updateClientP95: number | null;\n readonly updateServerP50: number | null;\n readonly updateServerP95: number | null;\n\n constructor(\n row: InspectQueryRow,\n delegate: ExtendedInspectorDelegate,\n socket: GetWebSocket,\n ) {\n this.#socket = socket;\n\n const {ast, queryID, inactivatedAt} = row;\n // Use own properties to make this more useful in dev tools. For example, in\n // Chrome dev tools, if you do console.table(queries) you'll see the\n // properties in the table, if these were getters you would not see them in the table.\n this.clientID = row.clientID;\n this.id = queryID;\n this.inactivatedAt =\n inactivatedAt === null ? null : new Date(inactivatedAt);\n this.ttl = normalizeTTL(row.ttl);\n this.name = row.name;\n this.args = row.args;\n this.got = row.got;\n this.rowCount = row.rowCount;\n this.deleted = row.deleted;\n this.#serverAST = ast;\n this.serverZQL = ast ? ast.table + astToZQL(ast) : null;\n const clientAST = delegate.getAST(queryID);\n this.clientZQL = clientAST ? clientAST.table + astToZQL(clientAST) : null;\n\n // Merge client and server metrics\n const clientMetrics = delegate.getQueryMetrics(queryID);\n const serverMetrics = row.metrics;\n\n const merged = mergeMetrics(clientMetrics, serverMetrics);\n this.metrics = merged;\n\n const percentile = (\n name: keyof typeof merged,\n percentile: number,\n ): number | null => {\n if (!merged?.[name]) {\n return null;\n }\n const n = merged[name].quantile(percentile);\n return Number.isNaN(n) ? null : n;\n };\n\n // Hydration times are plain numbers (performance.now()-based durations), so\n // read them directly instead of going through the TDigest percentile path.\n this.hydrateClient =\n clientMetrics?.['query-materialization-client'] ?? null;\n this.hydrateServer = serverMetrics?.['query-hydration-server-ms'] ?? null;\n this.hydrateTotal =\n clientMetrics?.['query-materialization-end-to-end'] ?? null;\n\n // Extract update metrics (P50 and P95) - handle NaN by defaulting to 0\n this.updateClientP50 = percentile('query-update-client', 0.5);\n this.updateClientP95 = percentile('query-update-client', 0.95);\n\n this.updateServerP50 = percentile('query-update-server', 0.5);\n this.updateServerP95 = percentile('query-update-server', 0.95);\n }\n\n async analyze(options?: AnalyzeQueryOptions): Promise<AnalyzeQueryResult> {\n const details =\n this.name && this.args\n ? {\n name: this.name,\n args: this.args,\n }\n : {value: must(this.#serverAST, 'AST is required for unnamed queries')};\n\n return rpc(\n await this.#socket(),\n {\n op: 'analyze-query',\n ...details,\n options,\n },\n inspectAnalyzeQueryDownSchema,\n );\n }\n}\n"],"mappings":";;;;;;AAmBA,IAAa,QAAb,MAAmB;CACjB;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CAEA,YACE,KACA,UACA,QACA;AACA,QAAA,SAAe;EAEf,MAAM,EAAC,KAAK,SAAS,kBAAiB;AAItC,OAAK,WAAW,IAAI;AACpB,OAAK,KAAK;AACV,OAAK,gBACH,kBAAkB,OAAO,OAAO,IAAI,KAAK,cAAc;AACzD,OAAK,MAAM,aAAa,IAAI,IAAI;AAChC,OAAK,OAAO,IAAI;AAChB,OAAK,OAAO,IAAI;AAChB,OAAK,MAAM,IAAI;AACf,OA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;AAG3E,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,iCAAiC,CAAC;AAC1D,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,+CAA+C,CAAC;AASnF,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAC,YAAY,EAAC,MAAM,uCAAuC,CAAC;AASnE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,eAAe;;IAI1B,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;gBAGrB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EACnC,IAAI,CAAC,EAAE,IAAI,EACX,OAAO,GAAE,GAAG,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,CAAa;IAO5D,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;IAejD,KAAK;IAUL;;;OAGG;IACH,OAAO,CAAC,YAAY,EAAE,IAAI,GAAG,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW;IAmBzE;;OAEG;IACG,UAAU,CACd,KAAK,EAAE,SAAS,EAChB,WAAW,EAAE,IAAI,EACjB,WAAW,CAAC,EAAE,eAAe,GAC5B,OAAO,CAAC,eAAe,CAAC;IAc3B;;;;;;;OAOG;IACH,IAAI;CAcL;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,KAAK,iBAkBb"}
@@ -29,6 +29,7 @@ import { sourceNameFromKey } from "./keys.js";
29
29
  var IVMSourceBranch = class IVMSourceBranch {
30
30
  #sources;
31
31
  #tables;
32
+ #advanceError;
32
33
  hash;
33
34
  constructor(tables, hash, sources = /* @__PURE__ */ new Map()) {
34
35
  this.#tables = tables;
@@ -36,6 +37,7 @@ var IVMSourceBranch = class IVMSourceBranch {
36
37
  this.hash = hash;
37
38
  }
38
39
  getSource(name) {
40
+ this.#throwIfInvalid();
39
41
  if (this.#sources.has(name)) return this.#sources.get(name);
40
42
  const schema = this.#tables[name];
41
43
  const source = schema ? new MemorySource(name, schema.columns, schema.primaryKey) : void 0;
@@ -45,19 +47,30 @@ var IVMSourceBranch = class IVMSourceBranch {
45
47
  clear() {
46
48
  this.#sources.clear();
47
49
  }
50
+ #throwIfInvalid() {
51
+ if (this.#advanceError) throw this.#advanceError;
52
+ }
48
53
  /**
49
54
  * Mutates the current branch, advancing it to the new head
50
55
  * by applying the given diffs.
51
56
  */
52
57
  advance(expectedHead, newHead, diffs) {
58
+ this.#throwIfInvalid();
53
59
  assert(this.hash === expectedHead, () => `Expected head must match the main head. Got: ${this.hash}, expected: ${expectedHead}`);
54
- applyDiffs(diffs, this);
55
- this.hash = newHead;
60
+ try {
61
+ applyDiffs(diffs, this);
62
+ this.hash = newHead;
63
+ } catch (e) {
64
+ this.#advanceError = e;
65
+ this.clear();
66
+ throw e;
67
+ }
56
68
  }
57
69
  /**
58
70
  * Fork the branch and patch it up to match the desired head.
59
71
  */
60
72
  async forkToHead(store, desiredHead, readOptions) {
73
+ this.#throwIfInvalid();
61
74
  const fork = this.fork();
62
75
  if (fork.hash === desiredHead) return fork;
63
76
  await patchBranch(desiredHead, store, fork, readOptions);
@@ -73,6 +86,7 @@ var IVMSourceBranch = class IVMSourceBranch {
73
86
  * The mutations modify the fork rather than original branch.
74
87
  */
75
88
  fork() {
89
+ this.#throwIfInvalid();
76
90
  return new IVMSourceBranch(this.#tables, this.hash, new Map(wrapIterable(this.#sources.entries()).map(([name, source]) => [name, source?.fork()])));
77
91
  }
78
92
  };
@@ -1 +1 @@
1
- {"version":3,"file":"ivm-branch.js","names":["#sources","#tables"],"sources":["../../../../../zero-client/src/client/ivm-branch.ts"],"sourcesContent":["import type {\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from '../../../replicache/src/btree/node.ts';\nimport type {LazyStore} from '../../../replicache/src/dag/lazy-store.ts';\nimport {type Read, type Store} from '../../../replicache/src/dag/store.ts';\nimport {readFromHash} from '../../../replicache/src/db/read.ts';\nimport * as FormatVersion from '../../../replicache/src/format-version-enum.ts';\nimport type {Hash} from '../../../replicache/src/hash.ts';\nimport type {ZeroReadOptions} from '../../../replicache/src/replicache-options.ts';\nimport {diffBinarySearch} from '../../../replicache/src/subscriptions.ts';\nimport type {DiffsMap} from '../../../replicache/src/sync/diff.ts';\nimport {diff} from '../../../replicache/src/sync/diff.ts';\nimport {using, withRead} from '../../../replicache/src/with-transactions.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {wrapIterable} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport {MemorySource} from '../../../zql/src/ivm/memory-source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {ENTITIES_KEY_PREFIX, sourceNameFromKey} from './keys.ts';\n\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\n/**\n * Replicache needs to rebase mutations onto different\n * commits of it's b-tree. These mutations can have reads\n * in them and those reads must be run against the IVM sources.\n *\n * To ensure the reads get the correct state, the IVM\n * sources need to reflect the state of the commit\n * being rebased onto. `IVMSourceBranch` allows us to:\n * 1. fork the IVM sources\n * 2. patch them up to match the desired head\n * 3. run the reads against the forked sources\n *\n * (2) is expected to be a cheap operation as there should only\n * ever be a few outstanding diffs to apply given Zero is meant\n * to be run in a connected state.\n */\nexport class IVMSourceBranch {\n readonly #sources: Map<string, MemorySource | undefined>;\n readonly #tables: Record<string, TableSchema>;\n hash: Hash | undefined;\n\n constructor(\n tables: Record<string, TableSchema>,\n hash?: Hash,\n sources: Map<string, MemorySource | undefined> = new Map(),\n ) {\n this.#tables = tables;\n this.#sources = sources;\n this.hash = hash;\n }\n\n getSource(name: string): MemorySource | undefined {\n if (this.#sources.has(name)) {\n return this.#sources.get(name);\n }\n\n const schema = this.#tables[name];\n const source = schema\n ? new MemorySource(name, schema.columns, schema.primaryKey)\n : undefined;\n this.#sources.set(name, source);\n return source;\n }\n\n clear() {\n this.#sources.clear();\n }\n\n /**\n * Mutates the current branch, advancing it to the new head\n * by applying the given diffs.\n */\n advance(expectedHead: Hash | undefined, newHead: Hash, diffs: NoIndexDiff) {\n assert(\n this.hash === expectedHead,\n () =>\n `Expected head must match the main head. Got: ${this.hash}, expected: ${expectedHead}`,\n );\n\n applyDiffs(diffs, this);\n this.hash = newHead;\n }\n\n /**\n * Fork the branch and patch it up to match the desired head.\n */\n async forkToHead(\n store: LazyStore,\n desiredHead: Hash,\n readOptions?: ZeroReadOptions,\n ): Promise<IVMSourceBranch> {\n const fork = this.fork();\n\n if (fork.hash === desiredHead) {\n return fork;\n }\n\n await patchBranch(desiredHead, store, fork, readOptions);\n fork.hash = desiredHead;\n return fork;\n }\n\n /**\n * Creates a new IVMSourceBranch that is a copy of the current one.\n * This is a cheap operation since the b-trees are shared until a write is performed\n * and then only the modified nodes are copied.\n *\n * IVM branches are forked when we need to rebase mutations.\n * The mutations modify the fork rather than original branch.\n */\n fork() {\n return new IVMSourceBranch(\n this.#tables,\n this.hash,\n new Map(\n wrapIterable(this.#sources.entries()).map(([name, source]) => [\n name,\n source?.fork(),\n ]),\n ),\n );\n }\n}\n\nexport async function initFromStore(\n branch: IVMSourceBranch,\n hash: Hash,\n store: Store,\n) {\n const diffs: InternalDiffOperation[] = [];\n await withRead(store, async dagRead => {\n const read = await readFromHash(hash, dagRead, FormatVersion.Latest);\n for await (const entry of read.map.scan(ENTITIES_KEY_PREFIX)) {\n if (!entry[0].startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n diffs.push({\n op: 'add',\n key: entry[0],\n newValue: entry[1],\n });\n }\n });\n\n branch.advance(undefined, hash, diffs);\n}\n\nasync function patchBranch(\n desiredHead: Hash,\n store: LazyStore,\n fork: IVMSourceBranch,\n readOptions: ZeroReadOptions | undefined,\n) {\n const diffs = await computeDiffs(\n must(fork.hash),\n desiredHead,\n store,\n readOptions,\n );\n if (!diffs) {\n return;\n }\n applyDiffs(diffs, fork);\n}\n\nasync function computeDiffs(\n startHash: Hash,\n endHash: Hash,\n store: LazyStore,\n readOptions: ZeroReadOptions | undefined,\n): Promise<InternalDiff | undefined> {\n const readFn = (dagRead: Read) =>\n diff(\n startHash,\n endHash,\n dagRead,\n {\n shouldComputeDiffs: () => true,\n shouldComputeDiffsForIndex(_name) {\n return false;\n },\n },\n FormatVersion.Latest,\n );\n\n let diffs: DiffsMap;\n if (readOptions?.openLazySourceRead) {\n diffs = await using(store.read(readOptions.openLazySourceRead), readFn);\n } else if (readOptions?.openLazyRead) {\n diffs = await readFn(readOptions.openLazyRead);\n } else {\n diffs = await withRead(store, readFn);\n }\n\n return diffs.get('');\n}\n\nfunction applyDiffs(diffs: NoIndexDiff, branch: IVMSourceBranch) {\n for (\n let i = diffBinarySearch(diffs, ENTITIES_KEY_PREFIX, diff => diff.key);\n i < diffs.length;\n i++\n ) {\n const diff = diffs[i];\n const {key} = diff;\n if (!key.startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n const name = sourceNameFromKey(key);\n const source = must(branch.getSource(name));\n switch (diff.op) {\n case 'del':\n consume(source.push(makeSourceChangeRemove(diff.oldValue as Row)));\n break;\n case 'add':\n consume(source.push(makeSourceChangeAdd(diff.newValue as Row)));\n break;\n case 'change':\n consume(\n source.push(\n makeSourceChangeEdit(diff.newValue as Row, diff.oldValue as Row),\n ),\n );\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,kBAAb,MAAa,gBAAgB;CAC3B;CACA;CACA;CAEA,YACE,QACA,MACA,0BAAiD,IAAI,KAAK,EAC1D;AACA,QAAA,SAAe;AACf,QAAA,UAAgB;AAChB,OAAK,OAAO;;CAGd,UAAU,MAAwC;AAChD,MAAI,MAAA,QAAc,IAAI,KAAK,CACzB,QAAO,MAAA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GAAG;;AAGtB,SAAS,WAAW,OAAoB,QAAyB;AAC/D,MACE,IAAI,IAAI,iBAAiB,OAAA,OAA4B,SAAQ,KAAK,IAAI,EACtE,IAAI,MAAM,QACV,KACA;EACA,MAAM,OAAO,MAAM;EACnB,MAAM,EAAC,QAAO;AACd,MAAI,CAAC,IAAI,WAAA,KAA+B,CACtC;EAEF,MAAM,OAAO,kBAAkB,IAAI;EACnC,MAAM,SAAS,KAAK,OAAO,UAAU,KAAK,CAAC;AAC3C,UAAQ,KAAK,IAAb;GACE,KAAK;AACH,YAAQ,OAAO,KAAK,uBAAuB,KAAK,SAAgB,CAAC,CAAC;AAClE;GACF,KAAK;AACH,YAAQ,OAAO,KAAK,oBAAoB,KAAK,SAAgB,CAAC,CAAC;AAC/D;GACF,KAAK;AACH,YACE,OAAO,KACL,qBAAqB,KAAK,UAAiB,KAAK,SAAgB,CACjE,CACF;AACD"}
1
+ {"version":3,"file":"ivm-branch.js","names":["#sources","#tables","#throwIfInvalid","#advanceError"],"sources":["../../../../../zero-client/src/client/ivm-branch.ts"],"sourcesContent":["import type {\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from '../../../replicache/src/btree/node.ts';\nimport type {LazyStore} from '../../../replicache/src/dag/lazy-store.ts';\nimport {type Read, type Store} from '../../../replicache/src/dag/store.ts';\nimport {readFromHash} from '../../../replicache/src/db/read.ts';\nimport * as FormatVersion from '../../../replicache/src/format-version-enum.ts';\nimport type {Hash} from '../../../replicache/src/hash.ts';\nimport type {ZeroReadOptions} from '../../../replicache/src/replicache-options.ts';\nimport {diffBinarySearch} from '../../../replicache/src/subscriptions.ts';\nimport type {DiffsMap} from '../../../replicache/src/sync/diff.ts';\nimport {diff} from '../../../replicache/src/sync/diff.ts';\nimport {using, withRead} from '../../../replicache/src/with-transactions.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {wrapIterable} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport {MemorySource} from '../../../zql/src/ivm/memory-source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {ENTITIES_KEY_PREFIX, sourceNameFromKey} from './keys.ts';\n\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\n/**\n * Replicache needs to rebase mutations onto different\n * commits of it's b-tree. These mutations can have reads\n * in them and those reads must be run against the IVM sources.\n *\n * To ensure the reads get the correct state, the IVM\n * sources need to reflect the state of the commit\n * being rebased onto. `IVMSourceBranch` allows us to:\n * 1. fork the IVM sources\n * 2. patch them up to match the desired head\n * 3. run the reads against the forked sources\n *\n * (2) is expected to be a cheap operation as there should only\n * ever be a few outstanding diffs to apply given Zero is meant\n * to be run in a connected state.\n */\nexport class IVMSourceBranch {\n readonly #sources: Map<string, MemorySource | undefined>;\n readonly #tables: Record<string, TableSchema>;\n #advanceError: unknown;\n hash: Hash | undefined;\n\n constructor(\n tables: Record<string, TableSchema>,\n hash?: Hash,\n sources: Map<string, MemorySource | undefined> = new Map(),\n ) {\n this.#tables = tables;\n this.#sources = sources;\n this.hash = hash;\n }\n\n getSource(name: string): MemorySource | undefined {\n this.#throwIfInvalid();\n\n if (this.#sources.has(name)) {\n return this.#sources.get(name);\n }\n\n const schema = this.#tables[name];\n const source = schema\n ? new MemorySource(name, schema.columns, schema.primaryKey)\n : undefined;\n this.#sources.set(name, source);\n return source;\n }\n\n clear() {\n this.#sources.clear();\n }\n\n #throwIfInvalid() {\n if (this.#advanceError) {\n throw this.#advanceError;\n }\n }\n\n /**\n * Mutates the current branch, advancing it to the new head\n * by applying the given diffs.\n */\n advance(expectedHead: Hash | undefined, newHead: Hash, diffs: NoIndexDiff) {\n this.#throwIfInvalid();\n\n assert(\n this.hash === expectedHead,\n () =>\n `Expected head must match the main head. Got: ${this.hash}, expected: ${expectedHead}`,\n );\n\n try {\n applyDiffs(diffs, this);\n this.hash = newHead;\n } catch (e) {\n this.#advanceError = e;\n this.clear();\n throw e;\n }\n }\n\n /**\n * Fork the branch and patch it up to match the desired head.\n */\n async forkToHead(\n store: LazyStore,\n desiredHead: Hash,\n readOptions?: ZeroReadOptions,\n ): Promise<IVMSourceBranch> {\n this.#throwIfInvalid();\n\n const fork = this.fork();\n\n if (fork.hash === desiredHead) {\n return fork;\n }\n\n await patchBranch(desiredHead, store, fork, readOptions);\n fork.hash = desiredHead;\n return fork;\n }\n\n /**\n * Creates a new IVMSourceBranch that is a copy of the current one.\n * This is a cheap operation since the b-trees are shared until a write is performed\n * and then only the modified nodes are copied.\n *\n * IVM branches are forked when we need to rebase mutations.\n * The mutations modify the fork rather than original branch.\n */\n fork() {\n this.#throwIfInvalid();\n\n return new IVMSourceBranch(\n this.#tables,\n this.hash,\n new Map(\n wrapIterable(this.#sources.entries()).map(([name, source]) => [\n name,\n source?.fork(),\n ]),\n ),\n );\n }\n}\n\nexport async function initFromStore(\n branch: IVMSourceBranch,\n hash: Hash,\n store: Store,\n) {\n const diffs: InternalDiffOperation[] = [];\n await withRead(store, async dagRead => {\n const read = await readFromHash(hash, dagRead, FormatVersion.Latest);\n for await (const entry of read.map.scan(ENTITIES_KEY_PREFIX)) {\n if (!entry[0].startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n diffs.push({\n op: 'add',\n key: entry[0],\n newValue: entry[1],\n });\n }\n });\n\n branch.advance(undefined, hash, diffs);\n}\n\nasync function patchBranch(\n desiredHead: Hash,\n store: LazyStore,\n fork: IVMSourceBranch,\n readOptions: ZeroReadOptions | undefined,\n) {\n const diffs = await computeDiffs(\n must(fork.hash),\n desiredHead,\n store,\n readOptions,\n );\n if (!diffs) {\n return;\n }\n applyDiffs(diffs, fork);\n}\n\nasync function computeDiffs(\n startHash: Hash,\n endHash: Hash,\n store: LazyStore,\n readOptions: ZeroReadOptions | undefined,\n): Promise<InternalDiff | undefined> {\n const readFn = (dagRead: Read) =>\n diff(\n startHash,\n endHash,\n dagRead,\n {\n shouldComputeDiffs: () => true,\n shouldComputeDiffsForIndex(_name) {\n return false;\n },\n },\n FormatVersion.Latest,\n );\n\n let diffs: DiffsMap;\n if (readOptions?.openLazySourceRead) {\n diffs = await using(store.read(readOptions.openLazySourceRead), readFn);\n } else if (readOptions?.openLazyRead) {\n diffs = await readFn(readOptions.openLazyRead);\n } else {\n diffs = await withRead(store, readFn);\n }\n\n return diffs.get('');\n}\n\nfunction applyDiffs(diffs: NoIndexDiff, branch: IVMSourceBranch) {\n for (\n let i = diffBinarySearch(diffs, ENTITIES_KEY_PREFIX, diff => diff.key);\n i < diffs.length;\n i++\n ) {\n const diff = diffs[i];\n const {key} = diff;\n if (!key.startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n const name = sourceNameFromKey(key);\n const source = must(branch.getSource(name));\n switch (diff.op) {\n case 'del':\n consume(source.push(makeSourceChangeRemove(diff.oldValue as Row)));\n break;\n case 'add':\n consume(source.push(makeSourceChangeAdd(diff.newValue as Row)));\n break;\n case 'change':\n consume(\n source.push(\n makeSourceChangeEdit(diff.newValue as Row, diff.oldValue as Row),\n ),\n );\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,kBAAb,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CAEA,YACE,QACA,MACA,0BAAiD,IAAI,KAAK,EAC1D;AACA,QAAA,SAAe;AACf,QAAA,UAAgB;AAChB,OAAK,OAAO;;CAGd,UAAU,MAAwC;AAChD,QAAA,gBAAsB;AAEtB,MAAI,MAAA,QAAc,IAAI,KAAK,CACzB,QAAO,MAAA,QAAc,IAAI,KAAK;EAGhC,MAAM,SAAS,MAAA,OAAa;EAC5B,MAAM,SAAS,SACX,IAAI,aAAa,MAAM,OAAO,SAAS,OAAO,WAAW,GACzD,KAAA;AACJ,QAAA,QAAc,IAAI,MAAM,OAAO;AAC/B,SAAO;;CAG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AI,GAAG;;AAGtB,SAAS,WAAW,OAAoB,QAAyB;AAC/D,MACE,IAAI,IAAI,iBAAiB,OAAA,OAA4B,SAAQ,KAAK,IAAI,EACtE,IAAI,MAAM,QACV,KACA;EACA,MAAM,OAAO,MAAM;EACnB,MAAM,EAAC,QAAO;AACd,MAAI,CAAC,IAAI,WAAA,KAA+B,CACtC;EAEF,MAAM,OAAO,kBAAkB,IAAI;EACnC,MAAM,SAAS,KAAK,OAAO,UAAU,KAAK,CAAC;AAC3C,UAAQ,KAAK,IAAb;GACE,KAAK;AACH,YAAQ,OAAO,KAAK,uBAAuB,KAAK,SAAgB,CAAC,CAAC;AAClE;GACF,KAAK;AACH,YAAQ,OAAO,KAAK,oBAAoB,KAAK,SAAgB,CAAC,CAAC;AAC/D;GACF,KAAK;AACH,YACE,OAAO,KACL,qBAAqB,KAAK,UAAiB,KAAK,SAAgB,CACjE,CACF;AACD"}
@@ -208,16 +208,24 @@ export type ZeroOptions<S extends BaseDefaultSchema = DefaultSchema, MD extends
208
208
  onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;
209
209
  /**
210
210
  * `onClientStateNotFound` is called when this client is no longer able
211
- * to sync with the zero-cache due to missing synchronization state. This
211
+ * to sync with zero-cache due to missing synchronization state. This
212
212
  * can be because:
213
213
  * - the local persistent synchronization state has been garbage collected.
214
214
  * This can happen if the client has no pending mutations and has not been
215
215
  * used for a while (e.g. the client's tab has been hidden for a long time).
216
- * - the zero-cache fails to find the server side synchronization state for
216
+ * - zero-cache fails to find the server side synchronization state for
217
217
  * this client.
218
+ * - zero-cache rejects this client's persisted synchronization state,
219
+ * requiring the local Replicache database to be reset.
218
220
  *
219
- * The default behavior is to reload the page (using `location.reload()`).
220
- * Provide your own function to prevent the page from reloading automatically.
221
+ * The current `Zero` instance should be treated as dead and replaced, not
222
+ * reconnected.
223
+ *
224
+ * The default behavior for the Zero client is to reload the page
225
+ * (using `location.reload()`). The React and SolidJS providers will replace
226
+ * the client in-place, without a full page reload.
227
+ *
228
+ * Provide your own function to prevent this functionality.
221
229
  */
222
230
  onClientStateNotFound?: (() => void) | undefined;
223
231
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAE,OAAO,EAAC,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,qCAAqC,CAAC;AACvE,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AACnD,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,aAAa,EACd,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,6CAA6C,CAAC;AACpF,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,aAAa,CAAC;AACnD,OAAO,EAAC,sBAAsB,EAAC,MAAM,gCAAgC,CAAC;AAEtE;;GAEG;AACH,MAAM,MAAM,WAAW,CACrB,CAAC,SAAS,iBAAiB,GAAG,aAAa,EAC3C,EAAE,SAAS,iBAAiB,GAAG,SAAS,GAAG,SAAS,EACpD,CAAC,SAAS,kBAAkB,GAAG,cAAc,IAC3C;IACF;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAErC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEnC;;;;;;;;;;;;;;;;;OAiBG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEjC;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEnC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAEhC;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,QAAQ,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sB,CAAC,mBAAmB,CAAC;CAClD,GAAG,sBAAsB,CAAC,GAC3B,CAAC;IACC,IAAI,EAAE,sBAAsB,CAAC,yBAAyB,CAAC;CACxD,GAAG,sBAAsB,CAAC,CAAC;AAEhC,eAAO,MAAM,4BAA4B,EAAE,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAKzE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel, LogSink} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * Destination for Zero's log output. When omitted, logs are written with\n * `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@linkcode LogSink} to redirect logs — for example, to\n * `process.stderr` in a CLI so that the tool's structured stdout output\n * isn't polluted by log lines.\n *\n * Note: this overrides only the console sink. When analytics logging is\n * enabled, the Datadog sink is still installed alongside this one.\n */\n logSink?: LogSink | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with the zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - the zero-cache fails to find the server side synchronization state for\n * this client.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from reloading automatically.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AAuYA,IAAa,+BACX,aACE,gBACA,qBACA,0BACD"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel, LogSink} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * Destination for Zero's log output. When omitted, logs are written with\n * `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@linkcode LogSink} to redirect logs — for example, to\n * `process.stderr` in a CLI so that the tool's structured stdout output\n * isn't polluted by log lines.\n *\n * Note: this overrides only the console sink. When analytics logging is\n * enabled, the Datadog sink is still installed alongside this one.\n */\n logSink?: LogSink | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - zero-cache fails to find the server side synchronization state for\n * this client.\n * - zero-cache rejects this client's persisted synchronization state,\n * requiring the local Replicache database to be reset.\n *\n * The current `Zero` instance should be treated as dead and replaced, not\n * reconnected.\n *\n * The default behavior for the Zero client is to reload the page\n * (using `location.reload()`). The React and SolidJS providers will replace\n * the client in-place, without a full page reload.\n *\n * Provide your own function to prevent this functionality.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AA+YA,IAAa,+BACX,aACE,gBACA,qBACA,0BACD"}
@@ -15,11 +15,17 @@ import type { ClientErrorKind } from './client-error-kind.ts';
15
15
  import type { ClientError } from './error.ts';
16
16
  import { type ZeroError } from './error.ts';
17
17
  import type { InspectorDelegate } from './inspector/inspector.ts';
18
+ import type { QueryClientMetrics } from './inspector/lazy-inspector.ts';
18
19
  import type { MutationTracker } from './mutation-tracker.ts';
19
20
  import type { ReadTransaction } from './replicache-types.ts';
20
21
  type ClientMetric = {
21
22
  [K in keyof ClientMetricMap]: TDigest;
22
23
  };
24
+ type PerQueryClientMetric = {
25
+ 'query-materialization-client': number | undefined;
26
+ 'query-materialization-end-to-end': number | undefined;
27
+ 'query-update-client': TDigest;
28
+ };
23
29
  /**
24
30
  * Tracks what queries the client is currently subscribed to on the server.
25
31
  * Sends `changeDesiredQueries` message to server when this changes.
@@ -29,6 +35,7 @@ export declare class QueryManager implements InspectorDelegate {
29
35
  #private;
30
36
  constructor(lc: LogContext, mutationTracker: MutationTracker, clientID: ClientID, tables: Record<string, TableSchema>, send: (change: ChangeDesiredQueriesMessage) => void, experimentalWatch: ReplicacheImpl['experimentalWatch'], recentQueriesMaxSize: number, queryChangeThrottleMs: number, slowMaterializeThreshold: number, onFatalError: (error: ZeroError) => void);
31
37
  getAST(queryID: string): AST | undefined;
38
+ setQueryEvictedCallback(cb: (hash: string, ast: AST, metrics: QueryClientMetrics) => void): void;
32
39
  mapClientASTToServer(ast: AST): AST;
33
40
  /**
34
41
  * Get the queries that need to be registered with the server.
@@ -61,7 +68,7 @@ export declare class QueryManager implements InspectorDelegate {
61
68
  */
62
69
  get metrics(): ClientMetric;
63
70
  addMetric<K extends keyof ClientMetricMap>(metric: K, value: number, ...args: ClientMetricMap[K]): void;
64
- getQueryMetrics(queryID: string): ClientMetric | undefined;
71
+ getQueryMetrics(queryID: string): PerQueryClientMetric | undefined;
65
72
  /**
66
73
  * For testing only: returns all query hashes currently registered.
67
74
  */
@@ -1 +1 @@
1
- {"version":3,"file":"query-manager.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/query-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,4CAA4C,CAAC;AAC/E,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,qCAAqC,CAAC;AAKlE,OAAO,EAAC,OAAO,EAAC,MAAM,gCAAgC,CAAC;AACvD,OAAO,EAGL,KAAK,GAAG,EACT,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,sDAAsD,CAAC;AACtG,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8CAA8C,CAAC;AAK/E,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,6CAA6C,CAAC;AAUlF,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0CAA0C,CAAC;AAC1E,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,4CAA4C,CAAC;AAChF,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,iCAAiC,CAAC;AACnE,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAuB,KAAK,GAAG,EAAC,MAAM,+BAA+B,CAAC;AAC7E,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AAC5D,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAC,KAAK,SAAS,EAAC,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAEhE,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAA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AE,MAAM,GAAG,oBAAoB,GAAG,SAAS;IAIlE;;OAEG;IACH,uBAAuB,IAAI,QAAQ,CAAC,MAAM,CAAC;CAG5C"}
@@ -1,4 +1,4 @@
1
- import { assert } from "../../../shared/src/asserts.js";
1
+ import { assert, unreachable } from "../../../shared/src/asserts.js";
2
2
  import { must } from "../../../shared/src/must.js";
3
3
  import { mapAST, normalizeAST } from "../../../zero-protocol/src/ast.js";
4
4
  import { TransformFailed } from "../../../zero-protocol/src/error-kind-enum.js";
@@ -38,6 +38,7 @@ var QueryManager = class {
38
38
  #queryMetrics = /* @__PURE__ */ new Map();
39
39
  #slowMaterializeThreshold;
40
40
  #closedError;
41
+ #queryEvictedCallback;
41
42
  constructor(lc, mutationTracker, clientID, tables, send, experimentalWatch, recentQueriesMaxSize, queryChangeThrottleMs, slowMaterializeThreshold, onFatalError) {
42
43
  this.#lc = lc.withContext("QueryManager");
43
44
  this.#clientID = clientID;
@@ -78,6 +79,9 @@ var QueryManager = class {
78
79
  const ast = this.#queries.get(queryID)?.normalized;
79
80
  return ast && mapAST(ast, this.#serverToClient);
80
81
  }
82
+ setQueryEvictedCallback(cb) {
83
+ this.#queryEvictedCallback = cb;
84
+ }
81
85
  mapClientASTToServer(ast) {
82
86
  return mapAST(ast, this.#clientToServer);
83
87
  }
@@ -262,6 +266,8 @@ var QueryManager = class {
262
266
  if (this.#recentQueries.size > this.#recentQueriesMaxSize) {
263
267
  const lruQueryID = this.#recentQueries.values().next().value;
264
268
  assert(lruQueryID, "Expected LRU query ID to exist");
269
+ const evictedAST = this.getAST(lruQueryID);
270
+ const evictedMetrics = this.#queryMetrics.get(lruQueryID);
265
271
  this.#queries.delete(lruQueryID);
266
272
  this.#recentQueries.delete(lruQueryID);
267
273
  this.#queryMetrics.delete(lruQueryID);
@@ -269,6 +275,9 @@ var QueryManager = class {
269
275
  op: "del",
270
276
  hash: lruQueryID
271
277
  });
278
+ assert(evictedAST, "Expected evicted AST to exist");
279
+ assert(evictedMetrics, "Expected evicted metrics to exist");
280
+ this.#queryEvictedCallback?.(lruQueryID, evictedAST, evictedMetrics);
272
281
  }
273
282
  }
274
283
  }
@@ -288,10 +297,19 @@ var QueryManager = class {
288
297
  }
289
298
  let existing = this.#queryMetrics.get(queryID);
290
299
  if (!existing) {
291
- existing = newMetrics();
300
+ existing = newPerQueryMetrics();
292
301
  this.#queryMetrics.set(queryID, existing);
293
302
  }
294
- existing[metric].add(value);
303
+ switch (metric) {
304
+ case "query-update-client":
305
+ existing["query-update-client"].add(value);
306
+ break;
307
+ case "query-materialization-client":
308
+ case "query-materialization-end-to-end":
309
+ existing[metric] = value;
310
+ break;
311
+ default: unreachable(metric);
312
+ }
295
313
  }
296
314
  getQueryMetrics(queryID) {
297
315
  return this.#queryMetrics.get(queryID);
@@ -310,6 +328,13 @@ function newMetrics() {
310
328
  "query-update-client": new TDigest()
311
329
  };
312
330
  }
331
+ function newPerQueryMetrics() {
332
+ return {
333
+ "query-materialization-client": void 0,
334
+ "query-materialization-end-to-end": void 0,
335
+ "query-update-client": new TDigest()
336
+ };
337
+ }
313
338
  //#endregion
314
339
  export { QueryManager };
315
340
 
@@ -1 +1 @@
1
- {"version":3,"file":"query-manager.js","names":["#clientID","#clientToServer","#serverToClient","#send","#onFatalError","#queries","#recentQueriesMaxSize","#recentQueries","#gotQueries","#mutationTracker","#pendingQueryChanges","#queryChangeThrottleMs","#lc","#metrics","#queryMetrics","#slowMaterializeThreshold","#pendingRemovals","#fireGotCallbacks","#closedError","#add","#queueQueryChange","#updateEntry","#remove","#scheduleBatch","#batchTimer"],"sources":["../../../../../zero-client/src/client/query-manager.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReplicacheImpl} from '../../../replicache/src/replicache-impl.ts';\nimport type {ClientID} from '../../../replicache/src/sync/ids.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {TDigest} from '../../../shared/src/tdigest.ts';\nimport {\n mapAST,\n normalizeAST,\n type AST,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {ChangeDesiredQueriesMessage} from '../../../zero-protocol/src/change-desired-queries.ts';\nimport type {ErroredQuery} 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 {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {UpQueriesPatchOp} from '../../../zero-protocol/src/queries-patch.ts';\nimport {\n hashOfAST,\n hashOfNameAndArgs,\n} from '../../../zero-protocol/src/query-hash.ts';\nimport {\n clientToServer,\n serverToClient,\n type NameMapper,\n} from '../../../zero-schema/src/name-mapper.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport type {ClientMetricMap} from '../../../zql/src/query/metrics-delegate.ts';\nimport type {CustomQueryID} from '../../../zql/src/query/named.ts';\nimport type {GotCallback} from '../../../zql/src/query/query-delegate.ts';\nimport {clampTTL, compareTTL, type TTL} from '../../../zql/src/query/ttl.ts';\nimport type {ClientErrorKind} from './client-error-kind.ts';\nimport type {ClientError} from './error.ts';\nimport {type ZeroError} from './error.ts';\nimport type {InspectorDelegate} from './inspector/inspector.ts';\nimport {desiredQueriesPrefixForClient, GOT_QUERIES_KEY_PREFIX} from './keys.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\nimport type {ReadTransaction} from './replicache-types.ts';\n\ntype QueryHash = string;\n\ntype Entry = {\n // We keep track of the AST so we can use it in the inspector.\n normalized: AST;\n name: string | undefined;\n args: readonly ReadonlyJSONValue[] | undefined;\n count: number;\n gotCallbacks: GotCallback[];\n ttl: TTL;\n};\n\ntype ClientMetric = {\n [K in keyof ClientMetricMap]: TDigest;\n};\n\n/**\n * Tracks what queries the client is currently subscribed to on the server.\n * Sends `changeDesiredQueries` message to server when this changes.\n * Deduplicates requests so that we only listen to a given unique query once.\n */\nexport class QueryManager implements InspectorDelegate {\n readonly #clientID: ClientID;\n readonly #clientToServer: NameMapper;\n readonly #serverToClient: NameMapper;\n readonly #send: (change: ChangeDesiredQueriesMessage) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n readonly #queries: Map<QueryHash, Entry> = new Map();\n readonly #recentQueriesMaxSize: number;\n readonly #recentQueries: Set<string> = new Set();\n readonly #gotQueries: Set<string> = new Set();\n readonly #mutationTracker: MutationTracker;\n readonly #pendingQueryChanges: UpQueriesPatchOp[] = [];\n readonly #queryChangeThrottleMs: number;\n #pendingRemovals: Array<() => void> = [];\n #batchTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #lc: LogContext;\n readonly #metrics: ClientMetric = newMetrics();\n readonly #queryMetrics: Map<string, ClientMetric> = new Map();\n readonly #slowMaterializeThreshold: number;\n #closedError: ZeroError | undefined;\n\n constructor(\n lc: LogContext,\n mutationTracker: MutationTracker,\n clientID: ClientID,\n tables: Record<string, TableSchema>,\n send: (change: ChangeDesiredQueriesMessage) => void,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n recentQueriesMaxSize: number,\n queryChangeThrottleMs: number,\n slowMaterializeThreshold: number,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('QueryManager');\n this.#clientID = clientID;\n this.#clientToServer = clientToServer(tables);\n this.#serverToClient = serverToClient(tables);\n this.#recentQueriesMaxSize = recentQueriesMaxSize;\n this.#send = send;\n this.#mutationTracker = mutationTracker;\n this.#queryChangeThrottleMs = queryChangeThrottleMs;\n this.#slowMaterializeThreshold = slowMaterializeThreshold;\n this.#onFatalError = onFatalError;\n this.#mutationTracker.onAllMutationsApplied(() => {\n if (this.#pendingRemovals.length === 0) {\n return;\n }\n const pendingRemovals = this.#pendingRemovals;\n this.#pendingRemovals = [];\n for (const removal of pendingRemovals) {\n removal();\n }\n });\n\n experimentalWatch(\n diff => {\n for (const diffOp of diff) {\n const queryHash = diffOp.key.substring(GOT_QUERIES_KEY_PREFIX.length);\n switch (diffOp.op) {\n case 'add':\n this.#gotQueries.add(queryHash);\n this.#fireGotCallbacks(queryHash, true);\n break;\n case 'del':\n this.#gotQueries.delete(queryHash);\n this.#fireGotCallbacks(queryHash, false);\n break;\n }\n }\n },\n {\n prefix: GOT_QUERIES_KEY_PREFIX,\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n getAST(queryID: string): AST | undefined {\n const ast = this.#queries.get(queryID)?.normalized;\n return ast && mapAST(ast, this.#serverToClient);\n }\n\n mapClientASTToServer(ast: AST): AST {\n return mapAST(ast, this.#clientToServer);\n }\n\n #fireGotCallbacks(queryHash: string, got: boolean) {\n const gotCallbacks = this.#queries.get(queryHash)?.gotCallbacks ?? [];\n for (const gotCallback of gotCallbacks) {\n gotCallback(got);\n }\n }\n\n /**\n * Get the queries that need to be registered with the server.\n *\n * An optional `lastPatch` can be provided. This is the last patch that was\n * sent to the server and may not yet have been acked. If `lastPatch` is provided,\n * this method will return a patch that does not include any events sent in `lastPatch`.\n *\n * This diffing of last patch and current patch is needed since we send\n * a set of queries to the server when we first connect inside of the `sec-protocol` as\n * the `initConnectionMessage`.\n *\n * While we're waiting for the `connected` response to come back from the server,\n * the client may have registered more queries. We need to diff the `initConnectionMessage`\n * queries with the current set of queries to understand what those were.\n */\n async getQueriesPatch(\n tx: ReadTransaction,\n lastPatch?: Map<string, UpQueriesPatchOp>,\n ): Promise<Map<string, UpQueriesPatchOp>> {\n const existingQueryHashes = new Set<string>();\n const prefix = desiredQueriesPrefixForClient(this.#clientID);\n for await (const key of tx.scan({prefix}).keys()) {\n existingQueryHashes.add(key.substring(prefix.length, key.length));\n }\n const patch: Map<string, UpQueriesPatchOp> = new Map();\n for (const hash of existingQueryHashes) {\n if (!this.#queries.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n\n for (const [hash, {normalized, ttl, name, args}] of this.#queries) {\n if (!existingQueryHashes.has(hash)) {\n patch.set(hash, {\n op: 'put',\n hash,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n // We get TTL out of the DagStore so it is possible that the TTL was written\n // with a too high TTL.\n ttl: clampTTL(ttl), // no lc here since no need to log here\n });\n }\n }\n\n if (lastPatch) {\n // if there are any `puts` in `lastPatch` that are not in `patch` then we need to\n // send a `del` event in `patch`.\n for (const [hash, {op}] of lastPatch) {\n if (op === 'put' && !patch.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n // Remove everything from `patch` that was already sent in `lastPatch`.\n for (const [hash, {op}] of patch) {\n const lastPatchOp = lastPatch.get(hash);\n if (lastPatchOp && lastPatchOp.op === op) {\n patch.delete(hash);\n }\n }\n }\n\n return patch;\n }\n\n handleTransformErrors(errors: ErroredQuery[]) {\n for (const error of errors) {\n const queryId = error.id;\n const entry = this.#queries.get(queryId);\n\n // if we don't have the query registered, continue\n if (!entry) {\n continue;\n }\n\n if (error.error === 'app' || error.error === 'parse') {\n entry.gotCallbacks.forEach(callback => callback(false, error));\n }\n // this code path is not possible technically since errors were never implemented in the legacy query transform error\n // but is included for backwards compatibility and we have a test case for it\n else {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unknown error transforming queries: ${JSON.stringify(error)}`,\n queryIDs: [],\n }),\n );\n // unreachable(error); TODO(0xcadams): this should eventually be unreachable\n }\n }\n }\n\n handleClosed(\n reason: ClientError<{kind: ClientErrorKind.ClientClosed; message: string}>,\n ) {\n if (this.#closedError) {\n return;\n }\n this.#closedError = reason;\n for (const [queryId, entry] of this.#queries) {\n const erroredQuery: ErroredQuery = {\n error: 'app',\n id: queryId,\n name: entry.name ?? 'legacy',\n message: reason.message,\n details: {kind: reason.kind},\n };\n for (const gotCallback of entry.gotCallbacks) {\n gotCallback(false, erroredQuery);\n }\n }\n }\n\n addCustom(\n ast: AST,\n {name, args}: CustomQueryID,\n ttl: TTL,\n gotCallback?: GotCallback,\n ): () => void {\n const normalized = normalizeAST(ast);\n const queryId = hashOfNameAndArgs(name, args);\n return this.#add(queryId, normalized, name, args, ttl, gotCallback);\n }\n\n addLegacy(ast: AST, ttl: TTL, gotCallback?: GotCallback): () => void {\n const normalized = normalizeAST(ast);\n const astHash = hashOfAST(normalized);\n return this.#add(\n astHash,\n normalized,\n undefined, // name is undefined for legacy queries\n undefined, // args are undefined for legacy queries\n ttl,\n gotCallback,\n );\n }\n\n #add(\n queryId: string,\n normalized: AST,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n ttl: TTL,\n gotCallback?: GotCallback,\n ) {\n assert(\n (name === undefined) === (args === undefined),\n 'If name is defined, args must be defined',\n );\n ttl = clampTTL(ttl, this.#lc);\n let entry = this.#queries.get(queryId);\n this.#recentQueries.delete(queryId);\n if (!entry) {\n normalized = mapAST(normalized, this.#clientToServer);\n\n entry = {\n normalized,\n name,\n args,\n count: 1,\n gotCallbacks: gotCallback ? [gotCallback] : [],\n ttl,\n };\n this.#queries.set(queryId, entry);\n this.#queueQueryChange({\n op: 'put',\n hash: queryId,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n ttl,\n });\n } else {\n ++entry.count;\n this.#updateEntry(entry, queryId, ttl);\n\n if (gotCallback) {\n entry.gotCallbacks.push(gotCallback);\n }\n }\n\n if (gotCallback) {\n gotCallback(this.#gotQueries.has(queryId));\n }\n\n let removed = false;\n const cleanupCb = () => {\n if (removed) {\n return;\n }\n removed = true;\n\n // We cannot remove queries while mutations are pending\n // as that could take data out of scope that is needed in a rebase\n if (this.#mutationTracker.size > 0) {\n this.#pendingRemovals.push(() =>\n this.#remove(entry, queryId, gotCallback),\n );\n return;\n }\n\n this.#remove(entry, queryId, gotCallback);\n };\n return cleanupCb;\n }\n\n updateCustom({name, args}: CustomQueryID, ttl: TTL) {\n const queryID = hashOfNameAndArgs(name, args);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n updateLegacy(ast: AST, ttl: TTL) {\n const normalized = normalizeAST(ast);\n const queryID = hashOfAST(normalized);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n #updateEntry(entry: Entry, queryID: string, ttl: TTL): void {\n // If the query already exists and the new ttl is larger than the old one\n // we send a changeDesiredQueries message to the server to update the ttl.\n ttl = clampTTL(ttl, this.#lc);\n if (compareTTL(ttl, entry.ttl) > 0) {\n entry.ttl = ttl;\n this.#queueQueryChange({\n op: 'put',\n hash: queryID,\n ast: entry.name === undefined ? entry.normalized : undefined,\n name: entry.name,\n args: entry.args,\n ttl,\n });\n }\n }\n\n #queueQueryChange(op: UpQueriesPatchOp) {\n this.#pendingQueryChanges.push(op);\n this.#scheduleBatch();\n }\n\n #scheduleBatch() {\n if (this.#batchTimer === undefined) {\n this.#batchTimer = setTimeout(\n () => this.flushBatch(),\n this.#queryChangeThrottleMs,\n );\n }\n }\n\n flushBatch() {\n if (this.#batchTimer !== undefined) {\n clearTimeout(this.#batchTimer);\n this.#batchTimer = undefined;\n }\n if (this.#pendingQueryChanges.length > 0) {\n this.#send([\n 'changeDesiredQueries',\n {\n desiredQueriesPatch: [...this.#pendingQueryChanges],\n },\n ]);\n this.#pendingQueryChanges.length = 0;\n }\n }\n\n #remove(entry: Entry, astHash: string, gotCallback: GotCallback | undefined) {\n if (gotCallback) {\n const index = entry.gotCallbacks.indexOf(gotCallback);\n entry.gotCallbacks.splice(index, 1);\n }\n --entry.count;\n if (entry.count === 0) {\n this.#recentQueries.add(astHash);\n if (this.#recentQueries.size > this.#recentQueriesMaxSize) {\n const lruQueryID = this.#recentQueries.values().next().value;\n assert(lruQueryID, 'Expected LRU query ID to exist');\n this.#queries.delete(lruQueryID);\n this.#recentQueries.delete(lruQueryID);\n this.#queryMetrics.delete(lruQueryID);\n this.#queueQueryChange({op: 'del', hash: lruQueryID});\n }\n }\n }\n\n /**\n * Gets the aggregated metrics for all queries managed by this QueryManager.\n */\n get metrics(): ClientMetric {\n return this.#metrics;\n }\n\n addMetric<K extends keyof ClientMetricMap>(\n metric: K,\n value: number,\n ...args: ClientMetricMap[K]\n ): void {\n // Only query metrics are tracked at this point.\n // If this check fails then we need to add a runtime check.\n metric satisfies `query-${string}`;\n\n // We track all materializations of queries as well as per\n // query materializations.\n this.#metrics[metric].add(value);\n\n const queryID = args[0];\n\n // Handle slow query logging for end-to-end materialization\n if (metric === 'query-materialization-end-to-end') {\n const ast = args[1];\n\n if (\n this.#slowMaterializeThreshold !== undefined &&\n value > this.#slowMaterializeThreshold\n ) {\n this.#lc.warn?.(\n 'Slow query materialization (including server/network)',\n queryID,\n ast,\n value,\n );\n } else {\n this.#lc.debug?.(\n 'Materialized query (including server/network)',\n queryID,\n ast,\n value,\n );\n }\n }\n\n // The query manager manages metrics that are per query.\n let existing = this.#queryMetrics.get(queryID);\n if (!existing) {\n existing = newMetrics();\n this.#queryMetrics.set(queryID, existing);\n }\n existing[metric].add(value);\n }\n\n getQueryMetrics(queryID: string): ClientMetric | undefined {\n return this.#queryMetrics.get(queryID);\n }\n\n /**\n * For testing only: returns all query hashes currently registered.\n */\n getAllNonGotQueryHashes(): Iterable<string> {\n return difference(this.#queries, this.#gotQueries);\n }\n}\n\nfunction newMetrics(): ClientMetric {\n return {\n 'query-materialization-client': new TDigest(),\n 'query-materialization-end-to-end': new TDigest(),\n 'query-update-client': new TDigest(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+DA,IAAa,eAAb,MAAuD;CACrD;CACA;CACA;CACA;CACA;CACA,2BAA2C,IAAI,KAAK;CACpD;CACA,iCAAuC,IAAI,KAAK;CAChD,8BAAoC,IAAI,KAAK;CAC7C;CACA,uBAAoD,EAAE;CACtD;CACA,mBAAsC,EAAE;CACxC;CACA;CACA,WAAkC,YAAY;CAC9C,gCAAoD,IAAI,KAAK;CAC7D;CACA;CAEA,YACE,IACA,iBACA,UACA,QACA,MACA,mB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C,oCAAoC,IAAI,SAAS;EACjD,uBAAuB,IAAI,SAAS;EACrC"}
1
+ {"version":3,"file":"query-manager.js","names":["#clientID","#clientToServer","#serverToClient","#send","#onFatalError","#queries","#recentQueriesMaxSize","#recentQueries","#gotQueries","#mutationTracker","#pendingQueryChanges","#queryChangeThrottleMs","#lc","#metrics","#queryMetrics","#slowMaterializeThreshold","#pendingRemovals","#fireGotCallbacks","#queryEvictedCallback","#closedError","#add","#queueQueryChange","#updateEntry","#remove","#scheduleBatch","#batchTimer"],"sources":["../../../../../zero-client/src/client/query-manager.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReplicacheImpl} from '../../../replicache/src/replicache-impl.ts';\nimport type {ClientID} from '../../../replicache/src/sync/ids.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {TDigest} from '../../../shared/src/tdigest.ts';\nimport {\n mapAST,\n normalizeAST,\n type AST,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {ChangeDesiredQueriesMessage} from '../../../zero-protocol/src/change-desired-queries.ts';\nimport type {ErroredQuery} 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 {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {UpQueriesPatchOp} from '../../../zero-protocol/src/queries-patch.ts';\nimport {\n hashOfAST,\n hashOfNameAndArgs,\n} from '../../../zero-protocol/src/query-hash.ts';\nimport {\n clientToServer,\n serverToClient,\n type NameMapper,\n} from '../../../zero-schema/src/name-mapper.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport type {ClientMetricMap} from '../../../zql/src/query/metrics-delegate.ts';\nimport type {CustomQueryID} from '../../../zql/src/query/named.ts';\nimport type {GotCallback} from '../../../zql/src/query/query-delegate.ts';\nimport {clampTTL, compareTTL, type TTL} from '../../../zql/src/query/ttl.ts';\nimport type {ClientErrorKind} from './client-error-kind.ts';\nimport type {ClientError} from './error.ts';\nimport {type ZeroError} from './error.ts';\nimport type {InspectorDelegate} from './inspector/inspector.ts';\nimport type {QueryClientMetrics} from './inspector/lazy-inspector.ts';\nimport {desiredQueriesPrefixForClient, GOT_QUERIES_KEY_PREFIX} from './keys.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\nimport type {ReadTransaction} from './replicache-types.ts';\n\ntype QueryHash = string;\n\ntype Entry = {\n // We keep track of the AST so we can use it in the inspector.\n normalized: AST;\n name: string | undefined;\n args: readonly ReadonlyJSONValue[] | undefined;\n count: number;\n gotCallbacks: GotCallback[];\n ttl: TTL;\n};\n\ntype ClientMetric = {\n [K in keyof ClientMetricMap]: TDigest;\n};\n\ntype PerQueryClientMetric = {\n 'query-materialization-client': number | undefined;\n 'query-materialization-end-to-end': number | undefined;\n 'query-update-client': TDigest;\n};\n\n/**\n * Tracks what queries the client is currently subscribed to on the server.\n * Sends `changeDesiredQueries` message to server when this changes.\n * Deduplicates requests so that we only listen to a given unique query once.\n */\nexport class QueryManager implements InspectorDelegate {\n readonly #clientID: ClientID;\n readonly #clientToServer: NameMapper;\n readonly #serverToClient: NameMapper;\n readonly #send: (change: ChangeDesiredQueriesMessage) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n readonly #queries: Map<QueryHash, Entry> = new Map();\n readonly #recentQueriesMaxSize: number;\n readonly #recentQueries: Set<string> = new Set();\n readonly #gotQueries: Set<string> = new Set();\n readonly #mutationTracker: MutationTracker;\n readonly #pendingQueryChanges: UpQueriesPatchOp[] = [];\n readonly #queryChangeThrottleMs: number;\n #pendingRemovals: Array<() => void> = [];\n #batchTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #lc: LogContext;\n readonly #metrics: ClientMetric = newMetrics();\n readonly #queryMetrics: Map<string, PerQueryClientMetric> = new Map();\n readonly #slowMaterializeThreshold: number;\n #closedError: ZeroError | undefined;\n #queryEvictedCallback:\n | ((hash: string, ast: AST, metrics: QueryClientMetrics) => void)\n | undefined;\n\n constructor(\n lc: LogContext,\n mutationTracker: MutationTracker,\n clientID: ClientID,\n tables: Record<string, TableSchema>,\n send: (change: ChangeDesiredQueriesMessage) => void,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n recentQueriesMaxSize: number,\n queryChangeThrottleMs: number,\n slowMaterializeThreshold: number,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('QueryManager');\n this.#clientID = clientID;\n this.#clientToServer = clientToServer(tables);\n this.#serverToClient = serverToClient(tables);\n this.#recentQueriesMaxSize = recentQueriesMaxSize;\n this.#send = send;\n this.#mutationTracker = mutationTracker;\n this.#queryChangeThrottleMs = queryChangeThrottleMs;\n this.#slowMaterializeThreshold = slowMaterializeThreshold;\n this.#onFatalError = onFatalError;\n this.#mutationTracker.onAllMutationsApplied(() => {\n if (this.#pendingRemovals.length === 0) {\n return;\n }\n const pendingRemovals = this.#pendingRemovals;\n this.#pendingRemovals = [];\n for (const removal of pendingRemovals) {\n removal();\n }\n });\n\n experimentalWatch(\n diff => {\n for (const diffOp of diff) {\n const queryHash = diffOp.key.substring(GOT_QUERIES_KEY_PREFIX.length);\n switch (diffOp.op) {\n case 'add':\n this.#gotQueries.add(queryHash);\n this.#fireGotCallbacks(queryHash, true);\n break;\n case 'del':\n this.#gotQueries.delete(queryHash);\n this.#fireGotCallbacks(queryHash, false);\n break;\n }\n }\n },\n {\n prefix: GOT_QUERIES_KEY_PREFIX,\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n getAST(queryID: string): AST | undefined {\n const ast = this.#queries.get(queryID)?.normalized;\n return ast && mapAST(ast, this.#serverToClient);\n }\n\n setQueryEvictedCallback(\n cb: (hash: string, ast: AST, metrics: QueryClientMetrics) => void,\n ): void {\n this.#queryEvictedCallback = cb;\n }\n\n mapClientASTToServer(ast: AST): AST {\n return mapAST(ast, this.#clientToServer);\n }\n\n #fireGotCallbacks(queryHash: string, got: boolean) {\n const gotCallbacks = this.#queries.get(queryHash)?.gotCallbacks ?? [];\n for (const gotCallback of gotCallbacks) {\n gotCallback(got);\n }\n }\n\n /**\n * Get the queries that need to be registered with the server.\n *\n * An optional `lastPatch` can be provided. This is the last patch that was\n * sent to the server and may not yet have been acked. If `lastPatch` is provided,\n * this method will return a patch that does not include any events sent in `lastPatch`.\n *\n * This diffing of last patch and current patch is needed since we send\n * a set of queries to the server when we first connect inside of the `sec-protocol` as\n * the `initConnectionMessage`.\n *\n * While we're waiting for the `connected` response to come back from the server,\n * the client may have registered more queries. We need to diff the `initConnectionMessage`\n * queries with the current set of queries to understand what those were.\n */\n async getQueriesPatch(\n tx: ReadTransaction,\n lastPatch?: Map<string, UpQueriesPatchOp>,\n ): Promise<Map<string, UpQueriesPatchOp>> {\n const existingQueryHashes = new Set<string>();\n const prefix = desiredQueriesPrefixForClient(this.#clientID);\n for await (const key of tx.scan({prefix}).keys()) {\n existingQueryHashes.add(key.substring(prefix.length, key.length));\n }\n const patch: Map<string, UpQueriesPatchOp> = new Map();\n for (const hash of existingQueryHashes) {\n if (!this.#queries.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n\n for (const [hash, {normalized, ttl, name, args}] of this.#queries) {\n if (!existingQueryHashes.has(hash)) {\n patch.set(hash, {\n op: 'put',\n hash,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n // We get TTL out of the DagStore so it is possible that the TTL was written\n // with a too high TTL.\n ttl: clampTTL(ttl), // no lc here since no need to log here\n });\n }\n }\n\n if (lastPatch) {\n // if there are any `puts` in `lastPatch` that are not in `patch` then we need to\n // send a `del` event in `patch`.\n for (const [hash, {op}] of lastPatch) {\n if (op === 'put' && !patch.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n // Remove everything from `patch` that was already sent in `lastPatch`.\n for (const [hash, {op}] of patch) {\n const lastPatchOp = lastPatch.get(hash);\n if (lastPatchOp && lastPatchOp.op === op) {\n patch.delete(hash);\n }\n }\n }\n\n return patch;\n }\n\n handleTransformErrors(errors: ErroredQuery[]) {\n for (const error of errors) {\n const queryId = error.id;\n const entry = this.#queries.get(queryId);\n\n // if we don't have the query registered, continue\n if (!entry) {\n continue;\n }\n\n if (error.error === 'app' || error.error === 'parse') {\n entry.gotCallbacks.forEach(callback => callback(false, error));\n }\n // this code path is not possible technically since errors were never implemented in the legacy query transform error\n // but is included for backwards compatibility and we have a test case for it\n else {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unknown error transforming queries: ${JSON.stringify(error)}`,\n queryIDs: [],\n }),\n );\n // unreachable(error); TODO(0xcadams): this should eventually be unreachable\n }\n }\n }\n\n handleClosed(\n reason: ClientError<{kind: ClientErrorKind.ClientClosed; message: string}>,\n ) {\n if (this.#closedError) {\n return;\n }\n this.#closedError = reason;\n for (const [queryId, entry] of this.#queries) {\n const erroredQuery: ErroredQuery = {\n error: 'app',\n id: queryId,\n name: entry.name ?? 'legacy',\n message: reason.message,\n details: {kind: reason.kind},\n };\n for (const gotCallback of entry.gotCallbacks) {\n gotCallback(false, erroredQuery);\n }\n }\n }\n\n addCustom(\n ast: AST,\n {name, args}: CustomQueryID,\n ttl: TTL,\n gotCallback?: GotCallback,\n ): () => void {\n const normalized = normalizeAST(ast);\n const queryId = hashOfNameAndArgs(name, args);\n return this.#add(queryId, normalized, name, args, ttl, gotCallback);\n }\n\n addLegacy(ast: AST, ttl: TTL, gotCallback?: GotCallback): () => void {\n const normalized = normalizeAST(ast);\n const astHash = hashOfAST(normalized);\n return this.#add(\n astHash,\n normalized,\n undefined, // name is undefined for legacy queries\n undefined, // args are undefined for legacy queries\n ttl,\n gotCallback,\n );\n }\n\n #add(\n queryId: string,\n normalized: AST,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n ttl: TTL,\n gotCallback?: GotCallback,\n ) {\n assert(\n (name === undefined) === (args === undefined),\n 'If name is defined, args must be defined',\n );\n ttl = clampTTL(ttl, this.#lc);\n let entry = this.#queries.get(queryId);\n this.#recentQueries.delete(queryId);\n if (!entry) {\n normalized = mapAST(normalized, this.#clientToServer);\n\n entry = {\n normalized,\n name,\n args,\n count: 1,\n gotCallbacks: gotCallback ? [gotCallback] : [],\n ttl,\n };\n this.#queries.set(queryId, entry);\n this.#queueQueryChange({\n op: 'put',\n hash: queryId,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n ttl,\n });\n } else {\n ++entry.count;\n this.#updateEntry(entry, queryId, ttl);\n\n if (gotCallback) {\n entry.gotCallbacks.push(gotCallback);\n }\n }\n\n if (gotCallback) {\n gotCallback(this.#gotQueries.has(queryId));\n }\n\n let removed = false;\n const cleanupCb = () => {\n if (removed) {\n return;\n }\n removed = true;\n\n // We cannot remove queries while mutations are pending\n // as that could take data out of scope that is needed in a rebase\n if (this.#mutationTracker.size > 0) {\n this.#pendingRemovals.push(() =>\n this.#remove(entry, queryId, gotCallback),\n );\n return;\n }\n\n this.#remove(entry, queryId, gotCallback);\n };\n return cleanupCb;\n }\n\n updateCustom({name, args}: CustomQueryID, ttl: TTL) {\n const queryID = hashOfNameAndArgs(name, args);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n updateLegacy(ast: AST, ttl: TTL) {\n const normalized = normalizeAST(ast);\n const queryID = hashOfAST(normalized);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n #updateEntry(entry: Entry, queryID: string, ttl: TTL): void {\n // If the query already exists and the new ttl is larger than the old one\n // we send a changeDesiredQueries message to the server to update the ttl.\n ttl = clampTTL(ttl, this.#lc);\n if (compareTTL(ttl, entry.ttl) > 0) {\n entry.ttl = ttl;\n this.#queueQueryChange({\n op: 'put',\n hash: queryID,\n ast: entry.name === undefined ? entry.normalized : undefined,\n name: entry.name,\n args: entry.args,\n ttl,\n });\n }\n }\n\n #queueQueryChange(op: UpQueriesPatchOp) {\n this.#pendingQueryChanges.push(op);\n this.#scheduleBatch();\n }\n\n #scheduleBatch() {\n if (this.#batchTimer === undefined) {\n this.#batchTimer = setTimeout(\n () => this.flushBatch(),\n this.#queryChangeThrottleMs,\n );\n }\n }\n\n flushBatch() {\n if (this.#batchTimer !== undefined) {\n clearTimeout(this.#batchTimer);\n this.#batchTimer = undefined;\n }\n if (this.#pendingQueryChanges.length > 0) {\n this.#send([\n 'changeDesiredQueries',\n {\n desiredQueriesPatch: [...this.#pendingQueryChanges],\n },\n ]);\n this.#pendingQueryChanges.length = 0;\n }\n }\n\n #remove(entry: Entry, astHash: string, gotCallback: GotCallback | undefined) {\n if (gotCallback) {\n const index = entry.gotCallbacks.indexOf(gotCallback);\n entry.gotCallbacks.splice(index, 1);\n }\n --entry.count;\n if (entry.count === 0) {\n this.#recentQueries.add(astHash);\n if (this.#recentQueries.size > this.#recentQueriesMaxSize) {\n const lruQueryID = this.#recentQueries.values().next().value;\n assert(lruQueryID, 'Expected LRU query ID to exist');\n const evictedAST = this.getAST(lruQueryID);\n const evictedMetrics = this.#queryMetrics.get(lruQueryID);\n this.#queries.delete(lruQueryID);\n this.#recentQueries.delete(lruQueryID);\n this.#queryMetrics.delete(lruQueryID);\n this.#queueQueryChange({op: 'del', hash: lruQueryID});\n assert(evictedAST, 'Expected evicted AST to exist');\n assert(evictedMetrics, 'Expected evicted metrics to exist');\n this.#queryEvictedCallback?.(lruQueryID, evictedAST, evictedMetrics);\n }\n }\n }\n\n /**\n * Gets the aggregated metrics for all queries managed by this QueryManager.\n */\n get metrics(): ClientMetric {\n return this.#metrics;\n }\n\n addMetric<K extends keyof ClientMetricMap>(\n metric: K,\n value: number,\n ...args: ClientMetricMap[K]\n ): void {\n // Only query metrics are tracked at this point.\n // If this check fails then we need to add a runtime check.\n metric satisfies `query-${string}`;\n\n // We track all materializations of queries as well as per\n // query materializations.\n this.#metrics[metric].add(value);\n\n const queryID = args[0];\n\n // Handle slow query logging for end-to-end materialization\n if (metric === 'query-materialization-end-to-end') {\n const ast = args[1];\n\n if (\n this.#slowMaterializeThreshold !== undefined &&\n value > this.#slowMaterializeThreshold\n ) {\n this.#lc.warn?.(\n 'Slow query materialization (including server/network)',\n queryID,\n ast,\n value,\n );\n } else {\n this.#lc.debug?.(\n 'Materialized query (including server/network)',\n queryID,\n ast,\n value,\n );\n }\n }\n\n // The query manager manages metrics that are per query.\n let existing = this.#queryMetrics.get(queryID);\n if (!existing) {\n existing = newPerQueryMetrics();\n this.#queryMetrics.set(queryID, existing);\n }\n switch (metric) {\n case 'query-update-client':\n existing['query-update-client'].add(value);\n break;\n case 'query-materialization-client':\n case 'query-materialization-end-to-end':\n // Recorded once per query (last value wins).\n existing[\n metric as\n | 'query-materialization-client'\n | 'query-materialization-end-to-end'\n ] = value;\n break;\n default:\n unreachable(metric);\n }\n }\n\n getQueryMetrics(queryID: string): PerQueryClientMetric | undefined {\n return this.#queryMetrics.get(queryID);\n }\n\n /**\n * For testing only: returns all query hashes currently registered.\n */\n getAllNonGotQueryHashes(): Iterable<string> {\n return difference(this.#queries, this.#gotQueries);\n }\n}\n\nfunction newMetrics(): ClientMetric {\n return {\n 'query-materialization-client': new TDigest(),\n 'query-materialization-end-to-end': new TDigest(),\n 'query-update-client': new TDigest(),\n };\n}\n\nfunction newPerQueryMetrics(): PerQueryClientMetric {\n return {\n 'query-materialization-client': undefined,\n 'query-materialization-end-to-end': undefined,\n 'query-update-client': new TDigest(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,eAAb,MAAuD;CACrD;CACA;CACA;CACA;CACA;CACA,2BAA2C,IAAI,KAAK;CACpD;CACA,iCAAuC,IAAI,KAAK;CAChD,8BAAoC,IAAI,KAAK;CAC7C;CACA,uBAAoD,EAAE;CACtD;CACA,mBAAs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AAW,MAAA,aAAmB,IAAI,QAAQ;AAC9C,MAAI,CAAC,UAAU;AACb,cAAW,oBAAoB;AAC/B,SAAA,aAAmB,IAAI,SAAS,SAAS;;AAE3C,UAAQ,QAAR;GACE,KAAK;AACH,aAAS,uBAAuB,IAAI,MAAM;AAC1C;GACF,KAAK;GACL,KAAK;AAEH,aACE,UAGE;AACJ;GACF,QACE,aAAY,OAAO;;;CAIzB,gBAAgB,SAAmD;AACjE,SAAO,MAAA,aAAmB,IAAI,QAAQ;;;;;CAMxC,0BAA4C;AAC1C,SAAO,WAAW,MAAA,SAAe,MAAA,WAAiB;;;AAItD,SAAS,aAA2B;AAClC,QAAO;EACL,gCAAgC,IAAI,SAAS;EAC7C,oCAAoC,IAAI,SAAS;EACjD,uBAAuB,IAAI,SAAS;EACrC;;AAGH,SAAS,qBAA2C;AAClD,QAAO;EACL,gCAAgC,KAAA;EAChC,oCAAoC,KAAA;EACpC,uBAAuB,IAAI,SAAS;EACrC"}
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * The current version of Zero.
4
4
  */
5
- var version = "1.5.0-canary.4";
5
+ var version = "1.6.0-canary.1";
6
6
  //#endregion
7
7
  export { version };
8
8
 
@@ -1 +1 @@
1
- {"version":3,"file":"zero.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/zero.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAA8B,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAC,KAAK,QAAQ,EAAW,MAAM,oBAAoB,CAAC;AAG3D,OAAO,EACL,cAAc,EAEf,MAAM,iCAAiC,CAAC;AAGzC,OAAO,KAAK,EAAC,MAAM,EAAe,MAAM,mCAAmC,CAAC;AAC5E,OAAO,KAAK,EAAC,MAAM,EAAe,MAAM,mCAAmC,CAAC;AAE5E,OAAO,KAAK,EACV,aAAa,EACb,QAAQ,EACT,MAAM,qCAAqC,CAAC;AAG7C,OAAO,KAAK,EACV,WAAW,EAEZ,MAAM,kCAAkC,C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