@rocicorp/zero 1.12.0-canary.12 → 1.12.0-canary.13

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 (211) hide show
  1. package/out/replicache/src/btree/diff.d.ts.map +1 -1
  2. package/out/replicache/src/btree/diff.js +1 -2
  3. package/out/replicache/src/btree/diff.js.map +1 -1
  4. package/out/replicache/src/btree/read.d.ts +31 -1
  5. package/out/replicache/src/btree/read.d.ts.map +1 -1
  6. package/out/replicache/src/btree/read.js +74 -19
  7. package/out/replicache/src/btree/read.js.map +1 -1
  8. package/out/replicache/src/btree/splice.d.ts.map +1 -1
  9. package/out/replicache/src/btree/splice.js +2 -1
  10. package/out/replicache/src/btree/splice.js.map +1 -1
  11. package/out/replicache/src/btree/write.d.ts.map +1 -1
  12. package/out/replicache/src/btree/write.js +2 -1
  13. package/out/replicache/src/btree/write.js.map +1 -1
  14. package/out/replicache/src/persist/collect-idb-databases.d.ts +1 -0
  15. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  16. package/out/replicache/src/persist/collect-idb-databases.js +13 -5
  17. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  18. package/out/replicache/src/scan-iterator.js +1 -1
  19. package/out/replicache/src/sync/request-id.js +2 -2
  20. package/out/replicache/src/sync/request-id.js.map +1 -1
  21. package/out/shared/src/bigint-json.d.ts.map +1 -1
  22. package/out/shared/src/bigint-json.js +1 -0
  23. package/out/shared/src/bigint-json.js.map +1 -1
  24. package/out/shared/src/btree-set.d.ts +21 -0
  25. package/out/shared/src/btree-set.d.ts.map +1 -1
  26. package/out/shared/src/btree-set.js +54 -0
  27. package/out/shared/src/btree-set.js.map +1 -1
  28. package/out/shared/src/headers.js +20 -0
  29. package/out/shared/src/headers.js.map +1 -0
  30. package/out/shared/src/natural-runs.d.ts +191 -0
  31. package/out/shared/src/natural-runs.d.ts.map +1 -0
  32. package/out/shared/src/natural-runs.js +337 -0
  33. package/out/shared/src/natural-runs.js.map +1 -0
  34. package/out/shared/src/random-uint64.d.ts.map +1 -1
  35. package/out/shared/src/random-uint64.js +2 -2
  36. package/out/shared/src/random-uint64.js.map +1 -1
  37. package/out/shared/src/random-values.d.ts +19 -1
  38. package/out/shared/src/random-values.d.ts.map +1 -1
  39. package/out/shared/src/random-values.js +38 -4
  40. package/out/shared/src/random-values.js.map +1 -1
  41. package/out/shared/src/tuple-map.d.ts +22 -0
  42. package/out/shared/src/tuple-map.d.ts.map +1 -0
  43. package/out/shared/src/tuple-map.js +48 -0
  44. package/out/shared/src/tuple-map.js.map +1 -0
  45. package/out/zero/package.js +1 -1
  46. package/out/zero/package.js.map +1 -1
  47. package/out/zero-cache/src/auth/auth.d.ts.map +1 -1
  48. package/out/zero-cache/src/auth/auth.js +5 -0
  49. package/out/zero-cache/src/auth/auth.js.map +1 -1
  50. package/out/zero-cache/src/config/zero-config.d.ts +21 -0
  51. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  52. package/out/zero-cache/src/config/zero-config.js +47 -9
  53. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  54. package/out/zero-cache/src/custom-queries/transform-query.js +2 -2
  55. package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
  56. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  57. package/out/zero-cache/src/db/pg-to-lite.js +3 -2
  58. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  59. package/out/zero-cache/src/db/pg-type-parser.js +55 -2
  60. package/out/zero-cache/src/db/pg-type-parser.js.map +1 -1
  61. package/out/zero-cache/src/server/change-streamer.js +5 -2
  62. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  63. package/out/zero-cache/src/server/inspector-delegate.js +6 -29
  64. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  65. package/out/zero-cache/src/server/main.js +5 -0
  66. package/out/zero-cache/src/server/main.js.map +1 -1
  67. package/out/zero-cache/src/server/replicator.js +3 -2
  68. package/out/zero-cache/src/server/replicator.js.map +1 -1
  69. package/out/zero-cache/src/server/syncer.js +5 -4
  70. package/out/zero-cache/src/server/syncer.js.map +1 -1
  71. package/out/zero-cache/src/server/worker-dispatcher.d.ts.map +1 -1
  72. package/out/zero-cache/src/server/worker-dispatcher.js +2 -1
  73. package/out/zero-cache/src/server/worker-dispatcher.js.map +1 -1
  74. package/out/zero-cache/src/services/admin-auth.d.ts +22 -0
  75. package/out/zero-cache/src/services/admin-auth.d.ts.map +1 -0
  76. package/out/zero-cache/src/services/admin-auth.js +42 -0
  77. package/out/zero-cache/src/services/admin-auth.js.map +1 -0
  78. package/out/zero-cache/src/services/auth-attempt-counter.d.ts +33 -0
  79. package/out/zero-cache/src/services/auth-attempt-counter.d.ts.map +1 -0
  80. package/out/zero-cache/src/services/auth-attempt-counter.js +61 -0
  81. package/out/zero-cache/src/services/auth-attempt-counter.js.map +1 -0
  82. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +1 -1
  83. package/out/zero-cache/src/services/change-source/pg/change-source.js +110 -13
  84. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  85. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -7
  86. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  87. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +38 -5
  88. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  89. package/out/zero-cache/src/services/change-source/pg/schema/init.js +10 -1
  90. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  91. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +4 -0
  92. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  93. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +10 -3
  94. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  95. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +23 -2
  96. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  97. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +2 -2
  98. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  99. package/out/zero-cache/src/services/change-streamer/change-streamer.js +10 -3
  100. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  101. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  102. package/out/zero-cache/src/services/heapz.d.ts.map +1 -1
  103. package/out/zero-cache/src/services/heapz.js +4 -5
  104. package/out/zero-cache/src/services/heapz.js.map +1 -1
  105. package/out/zero-cache/src/services/mutagen/error.d.ts +5 -0
  106. package/out/zero-cache/src/services/mutagen/error.d.ts.map +1 -1
  107. package/out/zero-cache/src/services/mutagen/error.js +7 -1
  108. package/out/zero-cache/src/services/mutagen/error.js.map +1 -1
  109. package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
  110. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  111. package/out/zero-cache/src/services/mutagen/pusher.js +1 -1
  112. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  113. package/out/zero-cache/src/services/plannerz.d.ts.map +1 -1
  114. package/out/zero-cache/src/services/plannerz.js +3 -7
  115. package/out/zero-cache/src/services/plannerz.js.map +1 -1
  116. package/out/zero-cache/src/services/profz.d.ts.map +1 -1
  117. package/out/zero-cache/src/services/profz.js +4 -13
  118. package/out/zero-cache/src/services/profz.js.map +1 -1
  119. package/out/zero-cache/src/services/replicator/change-processor.js +29 -2
  120. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  121. package/out/zero-cache/src/services/replicator/incremental-sync.js +3 -3
  122. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  123. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  124. package/out/zero-cache/src/services/statz.js +2 -7
  125. package/out/zero-cache/src/services/statz.js.map +1 -1
  126. package/out/zero-cache/src/services/view-syncer/client-handler.js +22 -1
  127. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  128. package/out/zero-cache/src/services/view-syncer/connection-context-manager.js +40 -2
  129. package/out/zero-cache/src/services/view-syncer/connection-context-manager.js.map +1 -1
  130. package/out/zero-cache/src/services/view-syncer/cvr-store.js +54 -17
  131. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  132. package/out/zero-cache/src/services/view-syncer/cvr.js +11 -0
  133. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  134. package/out/zero-cache/src/services/view-syncer/inspect-auth-limiter.js +107 -0
  135. package/out/zero-cache/src/services/view-syncer/inspect-auth-limiter.js.map +1 -0
  136. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +11 -6
  137. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  138. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +2 -1
  139. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  140. package/out/zero-cache/src/services/view-syncer/row-record-cache.js +16 -14
  141. package/out/zero-cache/src/services/view-syncer/row-record-cache.js.map +1 -1
  142. package/out/zero-cache/src/services/view-syncer/schema/cvr.js +4 -1
  143. package/out/zero-cache/src/services/view-syncer/schema/cvr.js.map +1 -1
  144. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  145. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  146. package/out/zero-cache/src/services/view-syncer/view-syncer.js +89 -51
  147. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  148. package/out/zero-cache/src/types/client-group-log-id.d.ts +9 -0
  149. package/out/zero-cache/src/types/client-group-log-id.d.ts.map +1 -0
  150. package/out/zero-cache/src/types/client-group-log-id.js +16 -0
  151. package/out/zero-cache/src/types/client-group-log-id.js.map +1 -0
  152. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  153. package/out/zero-cache/src/types/lite.js +1 -0
  154. package/out/zero-cache/src/types/lite.js.map +1 -1
  155. package/out/zero-cache/src/types/pg.d.ts +13 -2
  156. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  157. package/out/zero-cache/src/types/pg.js +2 -2
  158. package/out/zero-cache/src/types/pg.js.map +1 -1
  159. package/out/zero-cache/src/types/poke-chunk.d.ts +25 -4
  160. package/out/zero-cache/src/types/poke-chunk.d.ts.map +1 -1
  161. package/out/zero-cache/src/types/poke-chunk.js +46 -5
  162. package/out/zero-cache/src/types/poke-chunk.js.map +1 -1
  163. package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
  164. package/out/zero-cache/src/workers/connection.js +10 -3
  165. package/out/zero-cache/src/workers/connection.js.map +1 -1
  166. package/out/zero-cache/src/workers/rehome.d.ts +10 -0
  167. package/out/zero-cache/src/workers/rehome.d.ts.map +1 -1
  168. package/out/zero-cache/src/workers/rehome.js +4 -2
  169. package/out/zero-cache/src/workers/rehome.js.map +1 -1
  170. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +3 -2
  171. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  172. package/out/zero-cache/src/workers/syncer.js +15 -15
  173. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  174. package/out/zero-client/src/client/inspector/inspector.d.ts +4 -0
  175. package/out/zero-client/src/client/inspector/inspector.d.ts.map +1 -1
  176. package/out/zero-client/src/client/inspector/inspector.js +4 -0
  177. package/out/zero-client/src/client/inspector/inspector.js.map +1 -1
  178. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts +10 -2
  179. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts.map +1 -1
  180. package/out/zero-client/src/client/inspector/lazy-inspector.js +38 -31
  181. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  182. package/out/zero-client/src/client/inspector/query.d.ts +2 -2
  183. package/out/zero-client/src/client/inspector/query.d.ts.map +1 -1
  184. package/out/zero-client/src/client/inspector/query.js +4 -4
  185. package/out/zero-client/src/client/inspector/query.js.map +1 -1
  186. package/out/zero-client/src/client/ivm-branch.d.ts +3 -0
  187. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  188. package/out/zero-client/src/client/ivm-branch.js +10 -5
  189. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  190. package/out/zero-client/src/client/reconnect-backoff.d.ts +31 -0
  191. package/out/zero-client/src/client/reconnect-backoff.d.ts.map +1 -0
  192. package/out/zero-client/src/client/reconnect-backoff.js +44 -0
  193. package/out/zero-client/src/client/reconnect-backoff.js.map +1 -0
  194. package/out/zero-client/src/client/version.js +1 -1
  195. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  196. package/out/zero-client/src/client/zero.js +7 -0
  197. package/out/zero-client/src/client/zero.js.map +1 -1
  198. package/out/zero-client/src/util/nanoid.js +2 -2
  199. package/out/zero-client/src/util/nanoid.js.map +1 -1
  200. package/out/zero-protocol/src/up.d.ts +42 -42
  201. package/out/zero-server/src/process-mutations.d.ts +10 -0
  202. package/out/zero-server/src/process-mutations.d.ts.map +1 -1
  203. package/out/zero-server/src/process-mutations.js +39 -6
  204. package/out/zero-server/src/process-mutations.js.map +1 -1
  205. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  206. package/out/zql/src/ivm/memory-source.js +89 -6
  207. package/out/zql/src/ivm/memory-source.js.map +1 -1
  208. package/out/zql/src/planner/planner-connection.d.ts.map +1 -1
  209. package/out/zql/src/planner/planner-connection.js +37 -3
  210. package/out/zql/src/planner/planner-connection.js.map +1 -1
  211. package/package.json +1 -1
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The value logged for a client group in place of its ID.
3
+ *
4
+ * A clientGroupID lets its holder join the group, so it does not belong in
5
+ * logs. A hash still lets log lines about one group be correlated, which a
6
+ * prefix would too but at the cost of revealing some of the ID's bits.
7
+ */
8
+ export declare function clientGroupLogID(clientGroupID: string): string;
9
+ //# sourceMappingURL=client-group-log-id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-group-log-id.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/client-group-log-id.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAE9D"}
@@ -0,0 +1,16 @@
1
+ import { h64 } from "../../../shared/src/hash.js";
2
+ //#region ../zero-cache/src/types/client-group-log-id.ts
3
+ /**
4
+ * The value logged for a client group in place of its ID.
5
+ *
6
+ * A clientGroupID lets its holder join the group, so it does not belong in
7
+ * logs. A hash still lets log lines about one group be correlated, which a
8
+ * prefix would too but at the cost of revealing some of the ID's bits.
9
+ */
10
+ function clientGroupLogID(clientGroupID) {
11
+ return h64(clientGroupID).toString(36);
12
+ }
13
+ //#endregion
14
+ export { clientGroupLogID };
15
+
16
+ //# sourceMappingURL=client-group-log-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-group-log-id.js","names":[],"sources":["../../../../../zero-cache/src/types/client-group-log-id.ts"],"sourcesContent":["import {h64} from '../../../shared/src/hash.ts';\n\n/**\n * The value logged for a client group in place of its ID.\n *\n * A clientGroupID lets its holder join the group, so it does not belong in\n * logs. A hash still lets log lines about one group be correlated, which a\n * prefix would too but at the cost of revealing some of the ID's bits.\n */\nexport function clientGroupLogID(clientGroupID: string): string {\n return h64(clientGroupID).toString(36);\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,iBAAiB,eAA+B;CAC9D,OAAO,IAAI,aAAa,CAAC,CAAC,SAAS,EAAE;AACvC"}
@@ -1 +1 @@
1
- {"version":3,"file":"lite.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/lite.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EACV,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,gBAAgB,CAAC;AAE9D,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,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,CAC7C,YAAY,EAAE,cAAc,GAC3B,WAAW,CAKb;AAeD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC;AAEpC;;GAEG;AACH,wBAAgB,cAAc,CAC5B,gBAAgB,EAAE,MAAM,EACxB,OAAO,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,EACnC,QAAQ,EAAE,OAAO,EACjB,SAAS,EAAE,OAAO,GACjB,cAAc,CAahB;AAED,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,cAAc,UAG9D;AAED,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,cAAc,WAE9D;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,cAAc,EAAE,cAAc,GAC7B,SAAS,GAAG,SAAS,CAMvB;AAED,wBAAgB,MAAM,CAAC,cAAc,EAAE,cAAc,WAEpD;AAED,wBAAgB,OAAO,CAAC,cAAc,EAAE,cAAc,WAMrD;AAID,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,UAAU,QAezD"}
@@ -54,6 +54,7 @@ function liteValue(val, pgType, jsonFormat) {
54
54
  return stringify(val);
55
55
  }
56
56
  const obj = toLiteValue(val);
57
+ if (typeof obj === "bigint" && BigInt.asIntN(64, obj) !== obj) return Number(obj);
57
58
  return obj && typeof obj === "object" ? stringify(obj) : obj;
58
59
  }
59
60
  function toLiteValue(val) {
@@ -1 +1 @@
1
- {"version":3,"file":"lite.js","names":["upstreamDataTypeToZqlValueType"],"sources":["../../../../../zero-cache/src/types/lite.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../../zero-schema/src/table-schema.ts';\nimport type {ColumnSpec, LiteTableSpec} from '../db/specs.ts';\nimport {dataTypeToZqlValueType as upstreamDataTypeToZqlValueType} from './pg-data-type.ts';\nimport type {PostgresValueType} from './pg.ts';\nimport type {RowValue} from './row-key.ts';\n\n/** Javascript value types supported by better-sqlite3. */\nexport type LiteValueType = number | bigint | string | null | Uint8Array;\n\nexport type LiteRow = Readonly<Record<string, LiteValueType>>;\nexport type LiteRowKey = LiteRow; // just for API readability\n\nfunction columnType(col: string, table: LiteTableSpec) {\n const spec = table.columns[col];\n assert(spec, `Unknown column ${col} in table ${table.name}`);\n return spec.dataType;\n}\n\nexport const JSON_STRINGIFIED = 's';\nexport const JSON_PARSED = 'p';\n\nexport type JSONFormat = typeof JSON_STRINGIFIED | typeof JSON_PARSED;\n\n/**\n * Creates a LiteRow from the supplied RowValue. A copy of the `row`\n * is made only if a value conversion is performed.\n */\nexport function liteRow(\n row: RowValue,\n table: LiteTableSpec,\n jsonFormat: JSONFormat,\n): {row: LiteRow; numCols: number} {\n let copyNeeded = false;\n let numCols = 0;\n\n for (const key in row) {\n numCols++;\n const val = row[key];\n const liteVal = liteValue(val, columnType(key, table), jsonFormat);\n if (val !== liteVal) {\n copyNeeded = true;\n break;\n }\n }\n if (!copyNeeded) {\n return {row: row as unknown as LiteRow, numCols};\n }\n // Slow path for when a conversion is needed.\n numCols = 0;\n const converted: Record<string, LiteValueType> = {};\n for (const key in row) {\n numCols++;\n converted[key] = liteValue(row[key], columnType(key, table), jsonFormat);\n }\n return {row: converted, numCols};\n}\n\n/**\n * Postgres values types that are supported by SQLite are stored as-is.\n * This includes Uint8Arrays for the `bytea` / `BLOB` type.\n * * `boolean` values are converted to `0` or `1` integers.\n * * `PreciseDate` values are converted to epoch microseconds.\n * * JSON and Array values are stored as `JSON.stringify()` strings.\n *\n * Note that this currently does not handle the `bytea[]` type, but that's\n * already a pretty questionable type.\n */\nexport function liteValue(\n val: PostgresValueType,\n pgType: string,\n jsonFormat: JSONFormat,\n): LiteValueType {\n if (val instanceof Uint8Array || val === null) {\n return val;\n }\n const valueType = liteTypeToZqlValueType(pgType);\n if (valueType === 'json') {\n if (jsonFormat === JSON_STRINGIFIED && typeof val === 'string') {\n // JSON and JSONB values are already strings if the JSON was not parsed.\n return val;\n }\n // Non-JSON/JSONB values will always appear as objects / arrays.\n return stringify(val);\n }\n const obj = toLiteValue(val);\n return obj && typeof obj === 'object' ? stringify(obj) : obj;\n}\n\nfunction toLiteValue(val: JSONValue): Exclude<JSONValue, boolean> {\n switch (typeof val) {\n case 'string':\n case 'number':\n case 'bigint':\n return val;\n case 'boolean':\n return val ? 1 : 0;\n }\n if (val === null) {\n return val;\n }\n if (Array.isArray(val)) {\n return val.map(v => toLiteValue(v));\n }\n assert(\n val.constructor?.name === 'Object',\n `Unhandled object type ${val.constructor?.name}`,\n );\n return val; // JSON\n}\n\nexport function mapLiteDataTypeToZqlSchemaValue(\n liteDataType: LiteTypeString,\n): SchemaValue {\n return {\n type: mapLiteDataTypeToZqlValueType(liteDataType),\n optional: nullableUpstream(liteDataType),\n };\n}\n\nfunction mapLiteDataTypeToZqlValueType(dataType: LiteTypeString): ValueType {\n const type = liteTypeToZqlValueType(dataType);\n if (type === undefined) {\n throw new Error(`Unsupported data type ${dataType}`);\n }\n return type;\n}\n\n// Note: Includes the \"TEXT\" substring for SQLite type affinity\nconst TEXT_ENUM_ATTRIBUTE = '|TEXT_ENUM';\nconst NOT_NULL_ATTRIBUTE = '|NOT_NULL';\nconst TEXT_ARRAY_ATTRIBUTE = '|TEXT_ARRAY';\n\n/**\n * The `LiteTypeString` utilizes SQLite's loose type system to encode\n * auxiliary information about the upstream column (e.g. type and\n * constraints) that does not necessarily affect how SQLite handles the data,\n * but nonetheless determines how higher level logic handles the data.\n *\n * The format of the type string is the original upstream type, followed\n * by any number of attributes, each of which begins with the `|` character.\n * The current list of attributes are:\n * * `|NOT_NULL` to indicate that the upstream column does not allow nulls\n * * `|TEXT_ENUM` to indicate an enum that should be treated as a string\n * * `|TEXT_ARRAY` to indicate an array\n *\n * Examples:\n * * `int8`\n * * `int8|NOT_NULL`\n * * `timestamp with time zone`\n * * `timestamp with time zone|NOT_NULL`\n * * `nomz|TEXT_ENUM`\n * * `nomz|NOT_NULL|TEXT_ENUM`\n * * `int8[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY`\n * * `int8|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8|NOT_NULL[]` - Legacy (read support)\n * * `nomz[]|TEXT_ENUM|TEXT_ARRAY`\n * * `nomz|TEXT_ENUM[]` - Legacy (read support)\n * * `nomz|TEXT_ENUM|TEXT_ARRAY[]` - Legacy (read support)\n */\nexport type LiteTypeString = string;\n\n/**\n * Formats a {@link LiteTypeString}.\n */\nexport function liteTypeString(\n upstreamDataType: string,\n notNull: boolean | null | undefined,\n textEnum: boolean,\n textArray: boolean,\n): LiteTypeString {\n let typeString = upstreamDataType;\n assert(!typeString.includes('|'), 'Upstream type should not contain |');\n if (notNull) {\n typeString += NOT_NULL_ATTRIBUTE;\n }\n if (textEnum) {\n typeString += TEXT_ENUM_ATTRIBUTE;\n }\n if (textArray) {\n typeString += TEXT_ARRAY_ATTRIBUTE;\n }\n return typeString;\n}\n\nexport function upstreamDataType(liteTypeString: LiteTypeString) {\n const delim = liteTypeString.indexOf('|');\n return delim > 0 ? liteTypeString.substring(0, delim) : liteTypeString;\n}\n\nexport function nullableUpstream(liteTypeString: LiteTypeString) {\n return !liteTypeString.includes(NOT_NULL_ATTRIBUTE);\n}\n\n/**\n * Returns the value type for the `pgDataType` if it is supported by ZQL.\n * (Note that `pgDataType` values are stored as-is in the SQLite column defs).\n *\n * For types not supported by ZQL, returns `undefined`.\n */\nexport function liteTypeToZqlValueType(\n liteTypeString: LiteTypeString,\n): ValueType | undefined {\n return upstreamDataTypeToZqlValueType(\n upstreamDataType(liteTypeString).toLowerCase(),\n liteTypeString.includes(TEXT_ENUM_ATTRIBUTE),\n isArray(liteTypeString),\n );\n}\n\nexport function isEnum(liteTypeString: LiteTypeString) {\n return liteTypeString.includes(TEXT_ENUM_ATTRIBUTE);\n}\n\nexport function isArray(liteTypeString: LiteTypeString) {\n return (\n liteTypeString.includes(TEXT_ARRAY_ATTRIBUTE) ||\n // Before we added `|TEXT_ARRAY`, we just used `[]` suffix to indicate arrays.\n liteTypeString.includes('[]')\n );\n}\n\nconst invalidDataTypeRe = /^.+\\|.*\\[\\]/;\n\nexport function assertValidLiteColumnSpec(spec: ColumnSpec) {\n const {dataType} = spec;\n assert(\n dataType.includes(TEXT_ARRAY_ATTRIBUTE) === dataType.includes('[]'),\n () =>\n `TEXT_ARRAY_ATTRIBUTE and [] must be consistent in dataType: ${dataType}`,\n );\n assert(\n dataType.includes('[]') === (spec.elemPgTypeClass !== null),\n () =>\n `[] in dataType (${dataType}) must match elemPgTypeClass presence (${spec.elemPgTypeClass})`,\n );\n\n // and no [] after |\n assert(!invalidDataTypeRe.test(dataType), `Invalid dataType ${dataType}`);\n}\n"],"mappings":";;;;AAiBA,SAAS,WAAW,KAAa,OAAsB;CACrD,MAAM,OAAO,MAAM,QAAQ;CAC3B,OAAO,MAAM,kBAAkB,IAAI,YAAY,MAAM,MAAM;CAC3D,OAAO,KAAK;AACd;;;;;AAWA,SAAgB,QACd,KACA,OACA,YACiC;CACjC,IAAI,aAAa;CACjB,IAAI,UAAU;CAEd,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,MAAM,MAAM,IAAI;EAEhB,IAAI,QADY,UAAU,KAAK,WAAW,KAAK,KAAK,GAAG,UAC3C,GAAS;GACnB,aAAa;GACb;EACF;CACF;CACA,IAAI,CAAC,YACH,OAAO;EAAM;EAA2B;CAAO;CAGjD,UAAU;CACV,MAAM,YAA2C,CAAC;CAClD,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,UAAU,OAAO,UAAU,IAAI,MAAM,WAAW,KAAK,KAAK,GAAG,UAAU;CACzE;CACA,OAAO;EAAC,KAAK;EAAW;CAAO;AACjC;;;;;;;;;;;AAYA,SAAgB,UACd,KACA,QACA,YACe;CACf,IAAI,eAAe,cAAc,QAAQ,MACvC,OAAO;CAGT,IADkB,uBAAuB,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;;;;AAQA,SAAgB,uBACd,gBACuB;CACvB,OAAOA,uBACL,iBAAiB,cAAc,CAAC,CAAC,YAAY,GAC7C,eAAe,SAAS,mBAAmB,GAC3C,QAAQ,cAAc,CACxB;AACF;AAEA,SAAgB,OAAO,gBAAgC;CACrD,OAAO,eAAe,SAAS,mBAAmB;AACpD;AAEA,SAAgB,QAAQ,gBAAgC;CACtD,OACE,eAAe,SAAS,oBAAoB,KAE5C,eAAe,SAAS,IAAI;AAEhC;AAEA,IAAM,oBAAoB;AAE1B,SAAgB,0BAA0B,MAAkB;CAC1D,MAAM,EAAC,aAAY;CACnB,OACE,SAAS,SAAS,oBAAoB,MAAM,SAAS,SAAS,IAAI,SAEhE,+DAA+D,UACnE;CACA,OACE,SAAS,SAAS,IAAI,OAAO,KAAK,oBAAoB,aAEpD,mBAAmB,SAAS,yCAAyC,KAAK,gBAAgB,EAC9F;CAGA,OAAO,CAAC,kBAAkB,KAAK,QAAQ,GAAG,oBAAoB,UAAU;AAC1E"}
1
+ {"version":3,"file":"lite.js","names":["upstreamDataTypeToZqlValueType"],"sources":["../../../../../zero-cache/src/types/lite.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../../zero-schema/src/table-schema.ts';\nimport type {ColumnSpec, LiteTableSpec} from '../db/specs.ts';\nimport {dataTypeToZqlValueType as upstreamDataTypeToZqlValueType} from './pg-data-type.ts';\nimport type {PostgresValueType} from './pg.ts';\nimport type {RowValue} from './row-key.ts';\n\n/** Javascript value types supported by better-sqlite3. */\nexport type LiteValueType = number | bigint | string | null | Uint8Array;\n\nexport type LiteRow = Readonly<Record<string, LiteValueType>>;\nexport type LiteRowKey = LiteRow; // just for API readability\n\nfunction columnType(col: string, table: LiteTableSpec) {\n const spec = table.columns[col];\n assert(spec, `Unknown column ${col} in table ${table.name}`);\n return spec.dataType;\n}\n\nexport const JSON_STRINGIFIED = 's';\nexport const JSON_PARSED = 'p';\n\nexport type JSONFormat = typeof JSON_STRINGIFIED | typeof JSON_PARSED;\n\n/**\n * Creates a LiteRow from the supplied RowValue. A copy of the `row`\n * is made only if a value conversion is performed.\n */\nexport function liteRow(\n row: RowValue,\n table: LiteTableSpec,\n jsonFormat: JSONFormat,\n): {row: LiteRow; numCols: number} {\n let copyNeeded = false;\n let numCols = 0;\n\n for (const key in row) {\n numCols++;\n const val = row[key];\n const liteVal = liteValue(val, columnType(key, table), jsonFormat);\n if (val !== liteVal) {\n copyNeeded = true;\n break;\n }\n }\n if (!copyNeeded) {\n return {row: row as unknown as LiteRow, numCols};\n }\n // Slow path for when a conversion is needed.\n numCols = 0;\n const converted: Record<string, LiteValueType> = {};\n for (const key in row) {\n numCols++;\n converted[key] = liteValue(row[key], columnType(key, table), jsonFormat);\n }\n return {row: converted, numCols};\n}\n\n/**\n * Postgres values types that are supported by SQLite are stored as-is.\n * This includes Uint8Arrays for the `bytea` / `BLOB` type.\n * * `boolean` values are converted to `0` or `1` integers.\n * * `PreciseDate` values are converted to epoch microseconds.\n * * JSON and Array values are stored as `JSON.stringify()` strings.\n *\n * Note that this currently does not handle the `bytea[]` type, but that's\n * already a pretty questionable type.\n */\nexport function liteValue(\n val: PostgresValueType,\n pgType: string,\n jsonFormat: JSONFormat,\n): LiteValueType {\n if (val instanceof Uint8Array || val === null) {\n return val;\n }\n const valueType = liteTypeToZqlValueType(pgType);\n if (valueType === 'json') {\n if (jsonFormat === JSON_STRINGIFIED && typeof val === 'string') {\n // JSON and JSONB values are already strings if the JSON was not parsed.\n return val;\n }\n // Non-JSON/JSONB values will always appear as objects / arrays.\n return stringify(val);\n }\n const obj = toLiteValue(val);\n if (typeof obj === 'bigint' && BigInt.asIntN(64, obj) !== obj) {\n // SQLite cannot bind an integer beyond int64, and no int8 can be one, so\n // this is a double that was written as digits, which parse() reads as a\n // bigint. A change logged before stringify() wrote those with an exponent\n // is still in that form. Storing a double matches initial sync.\n return Number(obj);\n }\n return obj && typeof obj === 'object' ? stringify(obj) : obj;\n}\n\nfunction toLiteValue(val: JSONValue): Exclude<JSONValue, boolean> {\n switch (typeof val) {\n case 'string':\n case 'number':\n case 'bigint':\n return val;\n case 'boolean':\n return val ? 1 : 0;\n }\n if (val === null) {\n return val;\n }\n if (Array.isArray(val)) {\n return val.map(v => toLiteValue(v));\n }\n assert(\n val.constructor?.name === 'Object',\n `Unhandled object type ${val.constructor?.name}`,\n );\n return val; // JSON\n}\n\nexport function mapLiteDataTypeToZqlSchemaValue(\n liteDataType: LiteTypeString,\n): SchemaValue {\n return {\n type: mapLiteDataTypeToZqlValueType(liteDataType),\n optional: nullableUpstream(liteDataType),\n };\n}\n\nfunction mapLiteDataTypeToZqlValueType(dataType: LiteTypeString): ValueType {\n const type = liteTypeToZqlValueType(dataType);\n if (type === undefined) {\n throw new Error(`Unsupported data type ${dataType}`);\n }\n return type;\n}\n\n// Note: Includes the \"TEXT\" substring for SQLite type affinity\nconst TEXT_ENUM_ATTRIBUTE = '|TEXT_ENUM';\nconst NOT_NULL_ATTRIBUTE = '|NOT_NULL';\nconst TEXT_ARRAY_ATTRIBUTE = '|TEXT_ARRAY';\n\n/**\n * The `LiteTypeString` utilizes SQLite's loose type system to encode\n * auxiliary information about the upstream column (e.g. type and\n * constraints) that does not necessarily affect how SQLite handles the data,\n * but nonetheless determines how higher level logic handles the data.\n *\n * The format of the type string is the original upstream type, followed\n * by any number of attributes, each of which begins with the `|` character.\n * The current list of attributes are:\n * * `|NOT_NULL` to indicate that the upstream column does not allow nulls\n * * `|TEXT_ENUM` to indicate an enum that should be treated as a string\n * * `|TEXT_ARRAY` to indicate an array\n *\n * Examples:\n * * `int8`\n * * `int8|NOT_NULL`\n * * `timestamp with time zone`\n * * `timestamp with time zone|NOT_NULL`\n * * `nomz|TEXT_ENUM`\n * * `nomz|NOT_NULL|TEXT_ENUM`\n * * `int8[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY`\n * * `int8|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8|NOT_NULL[]` - Legacy (read support)\n * * `nomz[]|TEXT_ENUM|TEXT_ARRAY`\n * * `nomz|TEXT_ENUM[]` - Legacy (read support)\n * * `nomz|TEXT_ENUM|TEXT_ARRAY[]` - Legacy (read support)\n */\nexport type LiteTypeString = string;\n\n/**\n * Formats a {@link LiteTypeString}.\n */\nexport function liteTypeString(\n upstreamDataType: string,\n notNull: boolean | null | undefined,\n textEnum: boolean,\n textArray: boolean,\n): LiteTypeString {\n let typeString = upstreamDataType;\n assert(!typeString.includes('|'), 'Upstream type should not contain |');\n if (notNull) {\n typeString += NOT_NULL_ATTRIBUTE;\n }\n if (textEnum) {\n typeString += TEXT_ENUM_ATTRIBUTE;\n }\n if (textArray) {\n typeString += TEXT_ARRAY_ATTRIBUTE;\n }\n return typeString;\n}\n\nexport function upstreamDataType(liteTypeString: LiteTypeString) {\n const delim = liteTypeString.indexOf('|');\n return delim > 0 ? liteTypeString.substring(0, delim) : liteTypeString;\n}\n\nexport function nullableUpstream(liteTypeString: LiteTypeString) {\n return !liteTypeString.includes(NOT_NULL_ATTRIBUTE);\n}\n\n/**\n * Returns the value type for the `pgDataType` if it is supported by ZQL.\n * (Note that `pgDataType` values are stored as-is in the SQLite column defs).\n *\n * For types not supported by ZQL, returns `undefined`.\n */\nexport function liteTypeToZqlValueType(\n liteTypeString: LiteTypeString,\n): ValueType | undefined {\n return upstreamDataTypeToZqlValueType(\n upstreamDataType(liteTypeString).toLowerCase(),\n liteTypeString.includes(TEXT_ENUM_ATTRIBUTE),\n isArray(liteTypeString),\n );\n}\n\nexport function isEnum(liteTypeString: LiteTypeString) {\n return liteTypeString.includes(TEXT_ENUM_ATTRIBUTE);\n}\n\nexport function isArray(liteTypeString: LiteTypeString) {\n return (\n liteTypeString.includes(TEXT_ARRAY_ATTRIBUTE) ||\n // Before we added `|TEXT_ARRAY`, we just used `[]` suffix to indicate arrays.\n liteTypeString.includes('[]')\n );\n}\n\nconst invalidDataTypeRe = /^.+\\|.*\\[\\]/;\n\nexport function assertValidLiteColumnSpec(spec: ColumnSpec) {\n const {dataType} = spec;\n assert(\n dataType.includes(TEXT_ARRAY_ATTRIBUTE) === dataType.includes('[]'),\n () =>\n `TEXT_ARRAY_ATTRIBUTE and [] must be consistent in dataType: ${dataType}`,\n );\n assert(\n dataType.includes('[]') === (spec.elemPgTypeClass !== null),\n () =>\n `[] in dataType (${dataType}) must match elemPgTypeClass presence (${spec.elemPgTypeClass})`,\n );\n\n // and no [] after |\n assert(!invalidDataTypeRe.test(dataType), `Invalid dataType ${dataType}`);\n}\n"],"mappings":";;;;AAiBA,SAAS,WAAW,KAAa,OAAsB;CACrD,MAAM,OAAO,MAAM,QAAQ;CAC3B,OAAO,MAAM,kBAAkB,IAAI,YAAY,MAAM,MAAM;CAC3D,OAAO,KAAK;AACd;;;;;AAWA,SAAgB,QACd,KACA,OACA,YACiC;CACjC,IAAI,aAAa;CACjB,IAAI,UAAU;CAEd,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,MAAM,MAAM,IAAI;EAEhB,IAAI,QADY,UAAU,KAAK,WAAW,KAAK,KAAK,GAAG,UAC3C,GAAS;GACnB,aAAa;GACb;EACF;CACF;CACA,IAAI,CAAC,YACH,OAAO;EAAM;EAA2B;CAAO;CAGjD,UAAU;CACV,MAAM,YAA2C,CAAC;CAClD,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,UAAU,OAAO,UAAU,IAAI,MAAM,WAAW,KAAK,KAAK,GAAG,UAAU;CACzE;CACA,OAAO;EAAC,KAAK;EAAW;CAAO;AACjC;;;;;;;;;;;AAYA,SAAgB,UACd,KACA,QACA,YACe;CACf,IAAI,eAAe,cAAc,QAAQ,MACvC,OAAO;CAGT,IADkB,uBAAuB,MACrC,MAAc,QAAQ;EACxB,IAAI,eAAA,OAAmC,OAAO,QAAQ,UAEpD,OAAO;EAGT,OAAO,UAAU,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;;;AAQA,SAAgB,uBACd,gBACuB;CACvB,OAAOA,uBACL,iBAAiB,cAAc,CAAC,CAAC,YAAY,GAC7C,eAAe,SAAS,mBAAmB,GAC3C,QAAQ,cAAc,CACxB;AACF;AAEA,SAAgB,OAAO,gBAAgC;CACrD,OAAO,eAAe,SAAS,mBAAmB;AACpD;AAEA,SAAgB,QAAQ,gBAAgC;CACtD,OACE,eAAe,SAAS,oBAAoB,KAE5C,eAAe,SAAS,IAAI;AAEhC;AAEA,IAAM,oBAAoB;AAE1B,SAAgB,0BAA0B,MAAkB;CAC1D,MAAM,EAAC,aAAY;CACnB,OACE,SAAS,SAAS,oBAAoB,MAAM,SAAS,SAAS,IAAI,SAEhE,+DAA+D,UACnE;CACA,OACE,SAAS,SAAS,IAAI,OAAO,KAAK,oBAAoB,aAEpD,mBAAmB,SAAS,yCAAyC,KAAK,gBAAgB,EAC9F;CAGA,OAAO,CAAC,kBAAkB,KAAK,QAAQ,GAAG,oBAAoB,UAAU;AAC1E"}
@@ -26,20 +26,31 @@ export type TypeOptions = {
26
26
  * still be stringified by the pg client.
27
27
  */
28
28
  sendStringAsJson?: boolean;
29
+ /**
30
+ * Reads `json` and `jsonb` values with `JSON.parse()`, so that every number is
31
+ * a JavaScript number, including an integer beyond the safe range, which
32
+ * would otherwise be a `bigint`, and which this rounds instead. Use it only
33
+ * for data that holds no such integers, like the CVR, where every number came
34
+ * from a client or from a row sent to one.
35
+ *
36
+ * This matters for `jsonb`, which does not keep the form a number was written
37
+ * in: `1e+19` comes back as digits, which look the same as an int8.
38
+ */
39
+ plainJSON?: boolean | undefined;
29
40
  };
30
41
  /**
31
42
  * Configures types for the Postgres.js client library (`postgres`).
32
43
  *
33
44
  * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.
34
45
  */
35
- export declare const postgresTypeConfig: ({ sendStringAsJson }?: TypeOptions) => {
46
+ export declare const postgresTypeConfig: ({ sendStringAsJson, plainJSON, }?: TypeOptions) => {
36
47
  types: {
37
48
  bigint: PostgresType<bigint>;
38
49
  json: {
39
50
  to: number;
40
51
  from: number[];
41
52
  serialize: typeof import("../../../shared/src/bigint-json.ts").stringify;
42
- parse: typeof import("../../../shared/src/bigint-json.ts").parse;
53
+ parse: (text: string, reviver?: (this: any, key: string, value: any) => any) => any;
43
54
  };
44
55
  timestamp: {
45
56
  to: number;
@@ -1 +1 @@
1
- {"version":3,"file":"pg.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/pg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,MAAM,EAAC,MAAM,UAAU,CAAC;AAehC,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,QAAQ,EAAE,EAAc,KAAK,YAAY,EAAC,MAAM,UAAU,CAAC;AAClE,OAAO,EAAa,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;AAmB9E,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAmD7D;AAED,iBAAS,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAuBhD;AAcD,wBAAgB,0BAA0B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAoBvE;AAOD,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CA8ErE;AAED,iBAAS,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAK/C;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,UAAU,CAAC;AAEvD,MAAM,MAAM,WAAW,GAAG;IACxB;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,0BAAwB,WAAW;;;;;;;;;;;;;;;;;;2BAwB7C,OAAO;;;;;;2BAOP,OAAO;;;;;;2BAQP,MAAM,GAAG,IAAI;;;;;;2BAUb,MAAM;uBACV,MAAM,GAAG,MAAM;;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hD,CAAC;AAEF,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,WAE1E;AA8BD,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,OAAO,WAiB/C"}
@@ -108,13 +108,13 @@ function dateToUTCMidnight(date) {
108
108
  *
109
109
  * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.
110
110
  */
111
- var postgresTypeConfig = ({ sendStringAsJson } = {}) => ({ types: {
111
+ var postgresTypeConfig = ({ sendStringAsJson, plainJSON } = {}) => ({ types: {
112
112
  bigint: postgres.BigInt,
113
113
  json: {
114
114
  to: 114,
115
115
  from: [114, JSONB],
116
116
  serialize: sendStringAsJson ? (x) => typeof x === "string" ? x : BigIntJSON.stringify(x) : BigIntJSON.stringify,
117
- parse: BigIntJSON.parse
117
+ parse: plainJSON ? globalThis.JSON.parse : BigIntJSON.parse
118
118
  },
119
119
  timestamp: {
120
120
  to: TIMESTAMP,
@@ -1 +1 @@
1
- {"version":3,"file":"pg.js","names":[],"sources":["../../../../../zero-cache/src/types/pg.ts"],"sourcesContent":["import {Socket} from 'node:net';\nimport {\n PG_CONFIGURATION_LIMIT_EXCEEDED,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_EXCEPTION,\n PG_CONNECTION_FAILURE,\n PG_INSUFFICIENT_PRIVILEGE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_CATALOG_NAME,\n PG_INVALID_PASSWORD,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_TOO_MANY_CONNECTIONS,\n} from '@drdgvhbh/postgres-error-codes';\nimport {PreciseDate} from '@google-cloud/precise-date';\nimport {OID} from '@postgresql-typed/oids';\nimport type {LogContext} from '@rocicorp/logger';\nimport postgres, {type Notice, type PostgresType} from 'postgres';\nimport {BigIntJSON, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {ConfigurationError} from './configuration-error.ts';\nimport {\n DATE,\n JSON,\n JSONB,\n NUMERIC,\n TIME,\n TIMESTAMP,\n TIMESTAMPTZ,\n TIMETZ,\n} from './pg-types.ts';\n\n// Matches: YEAR-MM-DD HH:MM:SS[.fraction][+-TZ[:MM]][ BC]\nconst pgTimestampRe =\n /^(\\d+)-(\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{1,2}(?::\\d{2})?)?(?: BC)?$/;\n\n// exported for testing.\nexport function timestampToFpMillis(timestamp: string): number {\n if (timestamp === 'infinity') return Infinity;\n if (timestamp === '-infinity') return -Infinity;\n const match = timestamp.match(pgTimestampRe);\n if (!match) {\n throw new Error(`Error parsing ${timestamp}`);\n }\n\n const [, yearStr, monthDay, time, tz] = match;\n const bc = timestamp.endsWith(' BC');\n\n let year = Number(yearStr);\n if (bc) {\n // Postgres: 1 BC = JS year 0, 2 BC = JS year -1, N BC = -(N-1)\n year = -(year - 1);\n }\n\n // Format year as ISO 8601 expanded year if needed.\n // https://tc39.es/ecma262/#sec-expanded-years\n let isoYear: string;\n if (year >= 0 && year <= 9999) {\n isoYear = String(year).padStart(4, '0');\n } else if (year >= 0) {\n isoYear = '+' + String(year).padStart(6, '0');\n } else {\n isoYear = '-' + String(Math.abs(year)).padStart(6, '0');\n }\n\n // Build a UTC ISO string so PreciseDate returns microsecond precision.\n const utcString = `${isoYear}-${monthDay}T${time}Z`;\n\n try {\n const fullTime = new PreciseDate(utcString).getFullTime();\n const millis = Number(fullTime / 1_000_000n);\n const nanos = Number(fullTime % 1_000_000n);\n const ret = millis + nanos * 1e-6; // floating point milliseconds\n\n // Add back in the timezone offset. We passed local time as UTC,\n // so a positive offset means we need to subtract, and vice versa.\n if (tz) {\n const positiveOffset = tz.startsWith('+');\n const [hours, minutes] = tz.split(':');\n const offset =\n Math.abs(Number(hours)) * 60 + (minutes ? Number(minutes) : 0);\n const offsetMillis = offset * 60 * 1_000;\n return positiveOffset ? ret - offsetMillis : ret + offsetMillis;\n }\n return ret;\n } catch (e) {\n throw new Error(`Error parsing ${timestamp}`, {cause: e});\n }\n}\n\nfunction serializeTimestamp(val: unknown): string {\n switch (typeof val) {\n case 'string':\n return val; // Let Postgres parse it\n case 'number': {\n if (Number.isInteger(val)) {\n return new PreciseDate(val).toISOString();\n }\n // Convert floating point to bigint nanoseconds.\n const nanoseconds =\n 1_000_000n * BigInt(Math.trunc(val)) +\n BigInt(Math.trunc((val % 1) * 1e6));\n return new PreciseDate(nanoseconds).toISOString();\n }\n // Note: Don't support bigint inputs until we decide what the semantics are (e.g. micros vs nanos)\n // case 'bigint':\n // return new PreciseDate(val).toISOString();\n default:\n if (val instanceof Date) {\n return val.toISOString();\n }\n }\n throw new Error(`Unsupported type \"${typeof val}\" for timestamp`);\n}\n\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction serializeTime(x: unknown, type: 'time' | 'timetz'): string {\n switch (typeof x) {\n case 'string':\n return x; // Let Postgres parse it\n case 'number':\n return millisecondsToPostgresTime(x);\n }\n throw new Error(`Unsupported type \"${typeof x}\" for ${type}`);\n}\n\nexport function millisecondsToPostgresTime(milliseconds: number): string {\n if (milliseconds < 0) {\n throw new Error('Milliseconds cannot be negative');\n }\n\n if (milliseconds >= MILLISECONDS_PER_DAY) {\n throw new Error(\n `Milliseconds cannot exceed 24 hours (${MILLISECONDS_PER_DAY}ms)`,\n );\n }\n\n milliseconds = Math.floor(milliseconds); // Ensure it's an integer\n\n const totalSeconds = Math.floor(milliseconds / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const ms = milliseconds % 1000;\n\n return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}+00`;\n}\n\n// Regular expression to match HH:MM:SS, HH:MM:SS.mmm, or HH:MM:SS+00 / HH:MM:SS.mmm+00\n// Supports optional timezone offset\nconst timeRegex =\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:([+-])(\\d{1,2})(?::(\\d{2}))?)?$/;\n\nexport function postgresTimeToMilliseconds(timeString: string): number {\n // Validate basic format\n if (!timeString || typeof timeString !== 'string') {\n throw new Error('Invalid time string: must be a non-empty string');\n }\n\n const match = timeString.match(timeRegex);\n\n if (!match) {\n throw new Error(\n `Invalid time format: \"${timeString}\". Expected HH:MM:SS[.mmm][+|-HH[:MM]]`,\n );\n }\n\n // Extract components\n const hours = parseInt(match[1], 10);\n const minutes = parseInt(match[2], 10);\n const seconds = parseInt(match[3], 10);\n // Handle optional milliseconds, pad right with zeros if needed\n let milliseconds = 0;\n if (match[4]) {\n // Pad microseconds to 6 digits\n const msString = match[4].padEnd(6, '0');\n // slice milliseconds out of the microseconds\n // e.g. 123456 -> 123, 1234 -> 123,\n milliseconds = parseInt(msString.slice(0, 3), 10);\n }\n\n // Validate ranges\n if (hours < 0 || hours > 24) {\n throw new Error(\n `Invalid hours: ${hours}. Must be between 0 and 24 (24 means end of day)`,\n );\n }\n\n if (minutes < 0 || minutes >= 60) {\n throw new Error(`Invalid minutes: ${minutes}. Must be between 0 and 59`);\n }\n\n if (seconds < 0 || seconds >= 60) {\n throw new Error(`Invalid seconds: ${seconds}. Must be between 0 and 59`);\n }\n\n if (milliseconds < 0 || milliseconds >= 1000) {\n throw new Error(\n `Invalid milliseconds: ${milliseconds}. Must be between 0 and 999`,\n );\n }\n\n // Special case: PostgreSQL allows 24:00:00 to represent end of day\n if (hours === 24 && (minutes !== 0 || seconds !== 0 || milliseconds !== 0)) {\n throw new Error(\n 'Invalid time: when hours is 24, minutes, seconds, and milliseconds must be 0',\n );\n }\n\n // Calculate total milliseconds\n let totalMs =\n hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;\n\n // Timezone Offset\n if (match[5]) {\n const sign = match[5] === '+' ? 1 : -1;\n const tzHours = parseInt(match[6], 10);\n const tzMinutes = match[7] ? parseInt(match[7], 10) : 0;\n const offsetMs = sign * (tzHours * 3600000 + tzMinutes * 60000);\n totalMs -= offsetMs;\n }\n\n // Normalize to 0-24h only if outside valid range\n if (totalMs > MILLISECONDS_PER_DAY || totalMs < 0) {\n return (\n ((totalMs % MILLISECONDS_PER_DAY) + MILLISECONDS_PER_DAY) %\n MILLISECONDS_PER_DAY\n );\n }\n\n return totalMs;\n}\n\nfunction dateToUTCMidnight(date: string): number {\n if (date === 'infinity') return Infinity;\n if (date === '-infinity') return -Infinity;\n const d = new Date(date);\n return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());\n}\n\n/**\n * The (javascript) types of objects that can be returned by our configured\n * Postgres clients. For initial-sync, these comes from the postgres.js client:\n *\n * https://github.com/porsager/postgres/blob/master/src/types.js\n *\n * and for the replication stream these come from the the node-postgres client:\n *\n * https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js\n */\nexport type PostgresValueType = JSONValue | Uint8Array;\n\nexport type TypeOptions = {\n /**\n * Sends strings directly as JSON values (i.e. without JSON stringification).\n * The application is responsible for ensuring that string inputs for JSON\n * columns are already stringified. Other data types (e.g. objects) will\n * still be stringified by the pg client.\n */\n sendStringAsJson?: boolean;\n};\n\n/**\n * Configures types for the Postgres.js client library (`postgres`).\n *\n * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.\n */\nexport const postgresTypeConfig = ({sendStringAsJson}: TypeOptions = {}) => ({\n // Type the type IDs as `number` so that Typescript doesn't complain about\n // referencing external types during type inference.\n types: {\n bigint: postgres.BigInt,\n json: {\n to: JSON,\n from: [JSON, JSONB],\n serialize: sendStringAsJson\n ? (x: unknown) => (typeof x === 'string' ? x : BigIntJSON.stringify(x))\n : BigIntJSON.stringify,\n parse: BigIntJSON.parse,\n },\n // Timestamps are converted to PreciseDate objects.\n timestamp: {\n to: TIMESTAMP,\n from: [TIMESTAMP, TIMESTAMPTZ],\n serialize: serializeTimestamp,\n parse: timestampToFpMillis,\n },\n // Times are converted as strings\n time: {\n to: TIME,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'time'),\n parse: postgresTimeToMilliseconds,\n },\n\n timetz: {\n to: TIMETZ,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'timetz'),\n parse: postgresTimeToMilliseconds,\n },\n\n // The DATE type is stored directly as the PG normalized date string.\n date: {\n to: DATE,\n from: [DATE],\n serialize: (x: string | Date) =>\n (x instanceof Date ? x : new Date(x)).toISOString(),\n parse: dateToUTCMidnight,\n },\n // Returns a `js` number which can lose precision for large numbers.\n // JS number is 53 bits so this should generally not occur.\n // An API will be provided for users to override this type.\n numeric: {\n to: NUMERIC,\n from: [NUMERIC],\n serialize: (x: number) => String(x), // pg expects a string\n parse: (x: string | number) => Number(x),\n },\n },\n});\n\nexport type PostgresDB = postgres.Sql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\nexport type PostgresTransaction = postgres.TransactionSql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\n// Guards against half-open TCP connections, which otherwise hang the pool\n// indefinitely: a proxy can keep the client-facing socket alive (ACKing TCP\n// keepalives) after its backend is gone, so no 'close' or 'error' event ever\n// fires and statements like BEGIN / COMMIT await forever.\n// See https://github.com/porsager/postgres/issues/1089.\n//\n// If no bytes are read or written for this long, the socket is reset, which\n// rejects all in-flight queries and lets the pool recover. Wire activity\n// resets the timer, so streaming operations (e.g. COPY) are safe, but\n// statements that legitimately compute silently for longer (e.g. index\n// builds in migrations) must raise this. Settable as an emergency measure\n// (0 disables); deliberately not exposed as a server option.\nconst SOCKET_INACTIVITY_TIMEOUT_MS = parseInt(\n process.env.ZERO_PG_SOCKET_INACTIVITY_TIMEOUT ?? '120000',\n);\n\ntype SocketFactoryOptions = {\n host: string[];\n port: number[];\n path?: string | false;\n};\n\n/**\n * Creates the custom socket factory passed to postgres.js via its (untyped)\n * `socket` option. postgres.js does not call `connect()` on custom sockets,\n * and its TLS upgrade reads `socket.host` for the SNI servername, so the\n * factory must handle both itself.\n *\n * Note: unlike postgres.js's internal socket, reconnects do not rotate\n * through multiple hosts; multi-host URIs are not used by the zero-cache.\n *\n * Exported for testing.\n */\nexport function inactivityTimeoutSocket(\n lc: LogContext,\n timeoutMs = SOCKET_INACTIVITY_TIMEOUT_MS,\n // When > 0, enables OS-level TCP keepalive probes with this initial delay.\n // Unlike the inactivity watchdog, keepalive distinguishes an idle-but-alive\n // connection from a dead one (the OS tears down the socket only when probes\n // go unanswered), so it does not false-positive on connections that are\n // legitimately idle for long stretches -- e.g. a backfill COPY stream that\n // this process deliberately back-pressures. It does NOT catch a proxy that\n // ACKs keepalives after its backend is gone (the case the watchdog guards);\n // callers that disable the watchdog (timeoutMs = 0) in favor of keepalive\n // accept that residual risk. Keepalive is a socket option, not a listener,\n // so it survives postgres.js's removeAllListeners() on TLS upgrade.\n keepAliveMs = 0,\n) {\n return (options: SocketFactoryOptions): Socket => {\n const socket = new Socket();\n if (keepAliveMs > 0) {\n socket.setKeepAlive(true, keepAliveMs);\n }\n const target = options.path\n ? options.path\n : `${options.host[0]}:${options.port[0]}`;\n if (timeoutMs > 0) {\n // socket.setTimeout() cannot be used here: it registers its callback\n // as a 'timeout' event listener, and postgres.js removes all listeners\n // from the raw socket when upgrading it to TLS (removeAllListeners()\n // in secure()), which would silently disarm the watchdog on every TLS\n // connection. An interval is not a socket listener, so it survives the\n // upgrade, and encrypted traffic still flows through this raw socket,\n // advancing its byte counters.\n //\n // The counters are sampled once per timeout period, so a half-open\n // socket is reset after one to two timeout periods of inactivity.\n let lastActivity = -1;\n const watchdog = setInterval(() => {\n if (socket.destroyed) {\n clearInterval(watchdog);\n return;\n }\n const activity = socket.bytesRead + socket.bytesWritten;\n if (activity === lastActivity) {\n lc.warn?.(\n `resetting connection to ${target} after ${timeoutMs} ms of inactivity ` +\n `(likely half-open); in-flight queries will be rejected`,\n );\n clearInterval(watchdog);\n socket.resetAndDestroy();\n } else {\n lastActivity = activity;\n }\n }, timeoutMs);\n watchdog.unref();\n // Best-effort cleanup; removed on TLS upgrade, in which case the\n // destroyed check above clears the (unref'ed) interval instead.\n socket.once('close', () => clearInterval(watchdog));\n }\n if (options.path) {\n socket.connect(options.path);\n } else {\n const [host] = options.host;\n const [port] = options.port;\n socket.connect(port, host);\n // Read by postgres.js for the TLS SNI servername.\n Object.assign(socket, {host, port});\n }\n return socket;\n };\n}\n\nexport function pgClient(\n lc: LogContext,\n connectionURI: string,\n // A descriptive name for the code that is making the connection, so that we\n // can debug things like deadlocks.\n applicationName: string,\n options?: postgres.Options<{\n bigint: PostgresType<bigint>;\n json: PostgresType<JSONValue>;\n }> & {\n /**\n * How to detect a dead (\"half-open\") connection:\n * - `'inactivity-timeout'` (default): reset the socket after\n * {@link SOCKET_INACTIVITY_TIMEOUT_MS} of no read/write activity. Catches\n * proxy-level half-opens, but false-positives on connections that are\n * legitimately idle for long stretches.\n * - `'keepalive'`: disable the inactivity watchdog and rely on OS TCP\n * keepalive probes instead. Use for connections that are expected to sit\n * idle under back-pressure (e.g. the backfill COPY stream), where the\n * watchdog would reset a perfectly healthy connection.\n */\n liveness?: 'inactivity-timeout' | 'keepalive';\n },\n opts?: TypeOptions,\n): PostgresDB {\n applicationName = `zero-${applicationName}`;\n\n // Postgres carries row values in the `detail`, `hint`, `where` and\n // `internal_query` fields -- e.g. a unique violation reports\n // `Key (email)=(someone@example.com) already exists` in `detail`. Forward\n // only the severity, SQLSTATE and schema location; never the Notice itself.\n // The text is logged as `noticeMessage` because a `message` field would be\n // clobbered by the log line's own message (\"pg notice\").\n const safeNotice = (n: Notice) => ({\n severity: n.severity,\n code: n.code,\n noticeMessage: n.message,\n schema: n.schema_name,\n table: n.table_name,\n column: n.column_name,\n constraint: n.constraint_name,\n routine: n.routine,\n });\n\n const onnotice = (n: Notice) => {\n // https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html#PLPGSQL-STATEMENTS-RAISE\n switch (n.severity) {\n case 'NOTICE':\n return; // silenced\n case 'DEBUG':\n lc.debug?.('pg notice', safeNotice(n));\n return;\n case 'WARNING':\n lc.warn?.('pg notice', safeNotice(n));\n return;\n case 'EXCEPTION':\n lc.error?.('pg notice', safeNotice(n));\n return;\n case 'LOG':\n case 'INFO':\n default:\n lc.info?.('pg notice', safeNotice(n));\n }\n };\n const url = new URL(connectionURI);\n const sslFlag =\n url.searchParams.get('ssl') ?? url.searchParams.get('sslmode') ?? 'prefer';\n\n let ssl: boolean | 'prefer' | {rejectUnauthorized: boolean};\n if (sslFlag === 'disable' || sslFlag === 'false') {\n ssl = false;\n } else if (sslFlag === 'no-verify') {\n ssl = {rejectUnauthorized: false};\n } else {\n ssl = sslFlag as 'prefer';\n }\n\n // Set connections to expire between 5 and 10 minutes to free up state on PG.\n const maxLifetimeSeconds = randInt(5 * 60, 10 * 60);\n const {liveness = 'inactivity-timeout', ...pgOptions} = options ?? {};\n const providedConnection = pgOptions.connection ?? {};\n\n // postgres.js supports a custom socket factory via the `socket` option,\n // but it is missing from its type declarations, hence the untyped spread.\n const socketLc = lc.withContext('appName', applicationName);\n const socketFactory = {\n socket:\n liveness === 'keepalive'\n ? // Disable the inactivity watchdog and use TCP keepalive instead.\n inactivityTimeoutSocket(socketLc, 0, 60_000)\n : inactivityTimeoutSocket(socketLc),\n };\n\n return postgres(connectionURI, {\n ...postgresTypeConfig(opts),\n onnotice,\n ['max_lifetime']: maxLifetimeSeconds,\n // Close idle connections cleanly before the socket inactivity timer\n // (which cannot distinguish an idle pool connection from a hung query)\n // resets them.\n ['idle_timeout']: 60,\n ssl,\n ...socketFactory,\n ...pgOptions,\n connection: {\n ...providedConnection,\n ['application_name']: applicationName,\n },\n });\n}\n\nexport async function connectPgClient(\n ...args: Parameters<typeof pgClient>\n): Promise<PostgresDB> {\n const db = pgClient(...args);\n try {\n await db`SELECT 1`.simple().execute();\n return db;\n } catch (e) {\n if (isPostgresConfigError(e)) {\n throw new ConfigurationError(\n 'Unable to connect to Postgres. Check your database configuration.',\n {cause: e},\n );\n }\n throw e;\n }\n}\n\n/**\n * Disables any statement_timeout for the current transaction. By default,\n * Postgres does not impose a statement timeout, but some users and providers\n * set one at the database level (even though it is explicitly discouraged by\n * the Postgres documentation).\n *\n * Zero logic in particular often does not fit into the category of general\n * application logic; for potentially long-running operations like migrations\n * and background cleanup, the statement timeout should be disabled to prevent\n * these operations from timing out.\n */\nexport function disableStatementTimeout(sql: PostgresTransaction) {\n void sql`SET LOCAL statement_timeout = 0;`.execute().catch(() => {});\n}\n\nexport const typeNameByOID: Record<number, string> = Object.freeze(\n Object.fromEntries(\n Object.entries(OID).map(([name, oid]) => [\n oid,\n name.startsWith('_') ? `${name.substring(1)}[]` : name,\n ]),\n ),\n);\n\nexport function isPostgresError(e: unknown, ...codes: [string, ...string[]]) {\n return e instanceof postgres.PostgresError && codes.includes(e.code);\n}\n\nfunction isPostgresStartupConnectionError(e: unknown) {\n if (!(e instanceof Error) || !('code' in e)) {\n return false;\n }\n const {code} = e;\n // postgres.js throws plain Error instances for connection failures that\n // happen before Postgres can return a SQLSTATE. These are still startup\n // configuration problems for Zero: wrong host/port, unreachable DB, DNS,\n // TLS certificate mismatch, etc.\n return (\n typeof code === 'string' &&\n [\n 'CONNECT_TIMEOUT',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ERR_TLS_CERT_ALTNAME_INVALID',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n ].includes(code)\n );\n}\n\nexport function isPostgresConfigError(e: unknown) {\n return (\n isPostgresStartupConnectionError(e) ||\n isPostgresError(\n e,\n PG_CONNECTION_EXCEPTION,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_S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AAC,KAAK,CAAC,MAAM,SAAS,CACvC,KACA,KAAK,WAAW,GAAG,IAAI,GAAG,KAAK,UAAU,CAAC,EAAE,MAAM,IACpD,CAAC,CACH,CACF;AAEA,SAAgB,gBAAgB,GAAY,GAAG,OAA8B;CAC3E,OAAO,aAAa,SAAS,iBAAiB,MAAM,SAAS,EAAE,IAAI;AACrE;AAEA,SAAS,iCAAiC,GAAY;CACpD,IAAI,EAAE,aAAa,UAAU,EAAE,UAAU,IACvC,OAAO;CAET,MAAM,EAAC,SAAQ;CAKf,OACE,OAAO,SAAS,YAChB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,SAAS,IAAI;AAEnB;AAEA,SAAgB,sBAAsB,GAAY;CAChD,OACE,iCAAiC,CAAC,KAClC,gBACE,GACA,yBACA,gDACA,8BACA,uBACA,wCACA,qBACA,yBACA,2BACA,yBACA,+BACF;AAEJ"}
1
+ {"version":3,"file":"pg.js","names":[],"sources":["../../../../../zero-cache/src/types/pg.ts"],"sourcesContent":["import {Socket} from 'node:net';\nimport {\n PG_CONFIGURATION_LIMIT_EXCEEDED,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_EXCEPTION,\n PG_CONNECTION_FAILURE,\n PG_INSUFFICIENT_PRIVILEGE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_CATALOG_NAME,\n PG_INVALID_PASSWORD,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_TOO_MANY_CONNECTIONS,\n} from '@drdgvhbh/postgres-error-codes';\nimport {PreciseDate} from '@google-cloud/precise-date';\nimport {OID} from '@postgresql-typed/oids';\nimport type {LogContext} from '@rocicorp/logger';\nimport postgres, {type Notice, type PostgresType} from 'postgres';\nimport {BigIntJSON, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {ConfigurationError} from './configuration-error.ts';\nimport {\n DATE,\n JSON,\n JSONB,\n NUMERIC,\n TIME,\n TIMESTAMP,\n TIMESTAMPTZ,\n TIMETZ,\n} from './pg-types.ts';\n\n// Matches: YEAR-MM-DD HH:MM:SS[.fraction][+-TZ[:MM]][ BC]\nconst pgTimestampRe =\n /^(\\d+)-(\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{1,2}(?::\\d{2})?)?(?: BC)?$/;\n\n// exported for testing.\nexport function timestampToFpMillis(timestamp: string): number {\n if (timestamp === 'infinity') return Infinity;\n if (timestamp === '-infinity') return -Infinity;\n const match = timestamp.match(pgTimestampRe);\n if (!match) {\n throw new Error(`Error parsing ${timestamp}`);\n }\n\n const [, yearStr, monthDay, time, tz] = match;\n const bc = timestamp.endsWith(' BC');\n\n let year = Number(yearStr);\n if (bc) {\n // Postgres: 1 BC = JS year 0, 2 BC = JS year -1, N BC = -(N-1)\n year = -(year - 1);\n }\n\n // Format year as ISO 8601 expanded year if needed.\n // https://tc39.es/ecma262/#sec-expanded-years\n let isoYear: string;\n if (year >= 0 && year <= 9999) {\n isoYear = String(year).padStart(4, '0');\n } else if (year >= 0) {\n isoYear = '+' + String(year).padStart(6, '0');\n } else {\n isoYear = '-' + String(Math.abs(year)).padStart(6, '0');\n }\n\n // Build a UTC ISO string so PreciseDate returns microsecond precision.\n const utcString = `${isoYear}-${monthDay}T${time}Z`;\n\n try {\n const fullTime = new PreciseDate(utcString).getFullTime();\n const millis = Number(fullTime / 1_000_000n);\n const nanos = Number(fullTime % 1_000_000n);\n const ret = millis + nanos * 1e-6; // floating point milliseconds\n\n // Add back in the timezone offset. We passed local time as UTC,\n // so a positive offset means we need to subtract, and vice versa.\n if (tz) {\n const positiveOffset = tz.startsWith('+');\n const [hours, minutes] = tz.split(':');\n const offset =\n Math.abs(Number(hours)) * 60 + (minutes ? Number(minutes) : 0);\n const offsetMillis = offset * 60 * 1_000;\n return positiveOffset ? ret - offsetMillis : ret + offsetMillis;\n }\n return ret;\n } catch (e) {\n throw new Error(`Error parsing ${timestamp}`, {cause: e});\n }\n}\n\nfunction serializeTimestamp(val: unknown): string {\n switch (typeof val) {\n case 'string':\n return val; // Let Postgres parse it\n case 'number': {\n if (Number.isInteger(val)) {\n return new PreciseDate(val).toISOString();\n }\n // Convert floating point to bigint nanoseconds.\n const nanoseconds =\n 1_000_000n * BigInt(Math.trunc(val)) +\n BigInt(Math.trunc((val % 1) * 1e6));\n return new PreciseDate(nanoseconds).toISOString();\n }\n // Note: Don't support bigint inputs until we decide what the semantics are (e.g. micros vs nanos)\n // case 'bigint':\n // return new PreciseDate(val).toISOString();\n default:\n if (val instanceof Date) {\n return val.toISOString();\n }\n }\n throw new Error(`Unsupported type \"${typeof val}\" for timestamp`);\n}\n\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction serializeTime(x: unknown, type: 'time' | 'timetz'): string {\n switch (typeof x) {\n case 'string':\n return x; // Let Postgres parse it\n case 'number':\n return millisecondsToPostgresTime(x);\n }\n throw new Error(`Unsupported type \"${typeof x}\" for ${type}`);\n}\n\nexport function millisecondsToPostgresTime(milliseconds: number): string {\n if (milliseconds < 0) {\n throw new Error('Milliseconds cannot be negative');\n }\n\n if (milliseconds >= MILLISECONDS_PER_DAY) {\n throw new Error(\n `Milliseconds cannot exceed 24 hours (${MILLISECONDS_PER_DAY}ms)`,\n );\n }\n\n milliseconds = Math.floor(milliseconds); // Ensure it's an integer\n\n const totalSeconds = Math.floor(milliseconds / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const ms = milliseconds % 1000;\n\n return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}+00`;\n}\n\n// Regular expression to match HH:MM:SS, HH:MM:SS.mmm, or HH:MM:SS+00 / HH:MM:SS.mmm+00\n// Supports optional timezone offset\nconst timeRegex =\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:([+-])(\\d{1,2})(?::(\\d{2}))?)?$/;\n\nexport function postgresTimeToMilliseconds(timeString: string): number {\n // Validate basic format\n if (!timeString || typeof timeString !== 'string') {\n throw new Error('Invalid time string: must be a non-empty string');\n }\n\n const match = timeString.match(timeRegex);\n\n if (!match) {\n throw new Error(\n `Invalid time format: \"${timeString}\". Expected HH:MM:SS[.mmm][+|-HH[:MM]]`,\n );\n }\n\n // Extract components\n const hours = parseInt(match[1], 10);\n const minutes = parseInt(match[2], 10);\n const seconds = parseInt(match[3], 10);\n // Handle optional milliseconds, pad right with zeros if needed\n let milliseconds = 0;\n if (match[4]) {\n // Pad microseconds to 6 digits\n const msString = match[4].padEnd(6, '0');\n // slice milliseconds out of the microseconds\n // e.g. 123456 -> 123, 1234 -> 123,\n milliseconds = parseInt(msString.slice(0, 3), 10);\n }\n\n // Validate ranges\n if (hours < 0 || hours > 24) {\n throw new Error(\n `Invalid hours: ${hours}. Must be between 0 and 24 (24 means end of day)`,\n );\n }\n\n if (minutes < 0 || minutes >= 60) {\n throw new Error(`Invalid minutes: ${minutes}. Must be between 0 and 59`);\n }\n\n if (seconds < 0 || seconds >= 60) {\n throw new Error(`Invalid seconds: ${seconds}. Must be between 0 and 59`);\n }\n\n if (milliseconds < 0 || milliseconds >= 1000) {\n throw new Error(\n `Invalid milliseconds: ${milliseconds}. Must be between 0 and 999`,\n );\n }\n\n // Special case: PostgreSQL allows 24:00:00 to represent end of day\n if (hours === 24 && (minutes !== 0 || seconds !== 0 || milliseconds !== 0)) {\n throw new Error(\n 'Invalid time: when hours is 24, minutes, seconds, and milliseconds must be 0',\n );\n }\n\n // Calculate total milliseconds\n let totalMs =\n hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;\n\n // Timezone Offset\n if (match[5]) {\n const sign = match[5] === '+' ? 1 : -1;\n const tzHours = parseInt(match[6], 10);\n const tzMinutes = match[7] ? parseInt(match[7], 10) : 0;\n const offsetMs = sign * (tzHours * 3600000 + tzMinutes * 60000);\n totalMs -= offsetMs;\n }\n\n // Normalize to 0-24h only if outside valid range\n if (totalMs > MILLISECONDS_PER_DAY || totalMs < 0) {\n return (\n ((totalMs % MILLISECONDS_PER_DAY) + MILLISECONDS_PER_DAY) %\n MILLISECONDS_PER_DAY\n );\n }\n\n return totalMs;\n}\n\nfunction dateToUTCMidnight(date: string): number {\n if (date === 'infinity') return Infinity;\n if (date === '-infinity') return -Infinity;\n const d = new Date(date);\n return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());\n}\n\n/**\n * The (javascript) types of objects that can be returned by our configured\n * Postgres clients. For initial-sync, these comes from the postgres.js client:\n *\n * https://github.com/porsager/postgres/blob/master/src/types.js\n *\n * and for the replication stream these come from the the node-postgres client:\n *\n * https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js\n */\nexport type PostgresValueType = JSONValue | Uint8Array;\n\nexport type TypeOptions = {\n /**\n * Sends strings directly as JSON values (i.e. without JSON stringification).\n * The application is responsible for ensuring that string inputs for JSON\n * columns are already stringified. Other data types (e.g. objects) will\n * still be stringified by the pg client.\n */\n sendStringAsJson?: boolean;\n\n /**\n * Reads `json` and `jsonb` values with `JSON.parse()`, so that every number is\n * a JavaScript number, including an integer beyond the safe range, which\n * would otherwise be a `bigint`, and which this rounds instead. Use it only\n * for data that holds no such integers, like the CVR, where every number came\n * from a client or from a row sent to one.\n *\n * This matters for `jsonb`, which does not keep the form a number was written\n * in: `1e+19` comes back as digits, which look the same as an int8.\n */\n plainJSON?: boolean | undefined;\n};\n\n/**\n * Configures types for the Postgres.js client library (`postgres`).\n *\n * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.\n */\nexport const postgresTypeConfig = ({\n sendStringAsJson,\n plainJSON,\n}: TypeOptions = {}) => ({\n // Type the type IDs as `number` so that Typescript doesn't complain about\n // referencing external types during type inference.\n types: {\n bigint: postgres.BigInt,\n json: {\n to: JSON,\n from: [JSON, JSONB],\n serialize: sendStringAsJson\n ? (x: unknown) => (typeof x === 'string' ? x : BigIntJSON.stringify(x))\n : BigIntJSON.stringify,\n parse: plainJSON ? globalThis.JSON.parse : BigIntJSON.parse,\n },\n // Timestamps are converted to PreciseDate objects.\n timestamp: {\n to: TIMESTAMP,\n from: [TIMESTAMP, TIMESTAMPTZ],\n serialize: serializeTimestamp,\n parse: timestampToFpMillis,\n },\n // Times are converted as strings\n time: {\n to: TIME,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'time'),\n parse: postgresTimeToMilliseconds,\n },\n\n timetz: {\n to: TIMETZ,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'timetz'),\n parse: postgresTimeToMilliseconds,\n },\n\n // The DATE type is stored directly as the PG normalized date string.\n date: {\n to: DATE,\n from: [DATE],\n serialize: (x: string | Date) =>\n (x instanceof Date ? x : new Date(x)).toISOString(),\n parse: dateToUTCMidnight,\n },\n // Returns a `js` number which can lose precision for large numbers.\n // JS number is 53 bits so this should generally not occur.\n // An API will be provided for users to override this type.\n numeric: {\n to: NUMERIC,\n from: [NUMERIC],\n serialize: (x: number) => String(x), // pg expects a string\n parse: (x: string | number) => Number(x),\n },\n },\n});\n\nexport type PostgresDB = postgres.Sql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\nexport type PostgresTransaction = postgres.TransactionSql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\n// Guards against half-open TCP connections, which otherwise hang the pool\n// indefinitely: a proxy can keep the client-facing socket alive (ACKing TCP\n// keepalives) after its backend is gone, so no 'close' or 'error' event ever\n// fires and statements like BEGIN / COMMIT await forever.\n// See https://github.com/porsager/postgres/issues/1089.\n//\n// If no bytes are read or written for this long, the socket is reset, which\n// rejects all in-flight queries and lets the pool recover. Wire activity\n// resets the timer, so streaming operations (e.g. COPY) are safe, but\n// statements that legitimately compute silently for longer (e.g. index\n// builds in migrations) must raise this. Settable as an emergency measure\n// (0 disables); deliberately not exposed as a server option.\nconst SOCKET_INACTIVITY_TIMEOUT_MS = parseInt(\n process.env.ZERO_PG_SOCKET_INACTIVITY_TIMEOUT ?? '120000',\n);\n\ntype SocketFactoryOptions = {\n host: string[];\n port: number[];\n path?: string | false;\n};\n\n/**\n * Creates the custom socket factory passed to postgres.js via its (untyped)\n * `socket` option. postgres.js does not call `connect()` on custom sockets,\n * and its TLS upgrade reads `socket.host` for the SNI servername, so the\n * factory must handle both itself.\n *\n * Note: unlike postgres.js's internal socket, reconnects do not rotate\n * through multiple hosts; multi-host URIs are not used by the zero-cache.\n *\n * Exported for testing.\n */\nexport function inactivityTimeoutSocket(\n lc: LogContext,\n timeoutMs = SOCKET_INACTIVITY_TIMEOUT_MS,\n // When > 0, enables OS-level TCP keepalive probes with this initial delay.\n // Unlike the inactivity watchdog, keepalive distinguishes an idle-but-alive\n // connection from a dead one (the OS tears down the socket only when probes\n // go unanswered), so it does not false-positive on connections that are\n // legitimately idle for long stretches -- e.g. a backfill COPY stream that\n // this process deliberately back-pressures. It does NOT catch a proxy that\n // ACKs keepalives after its backend is gone (the case the watchdog guards);\n // callers that disable the watchdog (timeoutMs = 0) in favor of keepalive\n // accept that residual risk. Keepalive is a socket option, not a listener,\n // so it survives postgres.js's removeAllListeners() on TLS upgrade.\n keepAliveMs = 0,\n) {\n return (options: SocketFactoryOptions): Socket => {\n const socket = new Socket();\n if (keepAliveMs > 0) {\n socket.setKeepAlive(true, keepAliveMs);\n }\n const target = options.path\n ? options.path\n : `${options.host[0]}:${options.port[0]}`;\n if (timeoutMs > 0) {\n // socket.setTimeout() cannot be used here: it registers its callback\n // as a 'timeout' event listener, and postgres.js removes all listeners\n // from the raw socket when upgrading it to TLS (removeAllListeners()\n // in secure()), which would silently disarm the watchdog on every TLS\n // connection. An interval is not a socket listener, so it survives the\n // upgrade, and encrypted traffic still flows through this raw socket,\n // advancing its byte counters.\n //\n // The counters are sampled once per timeout period, so a half-open\n // socket is reset after one to two timeout periods of inactivity.\n let lastActivity = -1;\n const watchdog = setInterval(() => {\n if (socket.destroyed) {\n clearInterval(watchdog);\n return;\n }\n const activity = socket.bytesRead + socket.bytesWritten;\n if (activity === lastActivity) {\n lc.warn?.(\n `resetting connection to ${target} after ${timeoutMs} ms of inactivity ` +\n `(likely half-open); in-flight queries will be rejected`,\n );\n clearInterval(watchdog);\n socket.resetAndDestroy();\n } else {\n lastActivity = activity;\n }\n }, timeoutMs);\n watchdog.unref();\n // Best-effort cleanup; removed on TLS upgrade, in which case the\n // destroyed check above clears the (unref'ed) interval instead.\n socket.once('close', () => clearInterval(watchdog));\n }\n if (options.path) {\n socket.connect(options.path);\n } else {\n const [host] = options.host;\n const [port] = options.port;\n socket.connect(port, host);\n // Read by postgres.js for the TLS SNI servername.\n Object.assign(socket, {host, port});\n }\n return socket;\n };\n}\n\nexport function pgClient(\n lc: LogContext,\n connectionURI: string,\n // A descriptive name for the code that is making the connection, so that we\n // can debug things like deadlocks.\n applicationName: string,\n options?: postgres.Options<{\n bigint: PostgresType<bigint>;\n json: PostgresType<JSONValue>;\n }> & {\n /**\n * How to detect a dead (\"half-open\") connection:\n * - `'inactivity-timeout'` (default): reset the socket after\n * {@link SOCKET_INACTIVITY_TIMEOUT_MS} of no read/write activity. Catches\n * proxy-level half-opens, but false-positives on connections that are\n * legitimately idle for long stretches.\n * - `'keepalive'`: disable the inactivity watchdog and rely on OS TCP\n * keepalive probes instead. Use for connections that are expected to sit\n * idle under back-pressure (e.g. the backfill COPY stream), where the\n * watchdog would reset a perfectly healthy connection.\n */\n liveness?: 'inactivity-timeout' | 'keepalive';\n },\n opts?: TypeOptions,\n): PostgresDB {\n applicationName = `zero-${applicationName}`;\n\n // Postgres carries row values in the `detail`, `hint`, `where` and\n // `internal_query` fields -- e.g. a unique violation reports\n // `Key (email)=(someone@example.com) already exists` in `detail`. Forward\n // only the severity, SQLSTATE and schema location; never the Notice itself.\n // The text is logged as `noticeMessage` because a `message` field would be\n // clobbered by the log line's own message (\"pg notice\").\n const safeNotice = (n: Notice) => ({\n severity: n.severity,\n code: n.code,\n noticeMessage: n.message,\n schema: n.schema_name,\n table: n.table_name,\n column: n.column_name,\n constraint: n.constraint_name,\n routine: n.routine,\n });\n\n const onnotice = (n: Notice) => {\n // https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html#PLPGSQL-STATEMENTS-RAISE\n switch (n.severity) {\n case 'NOTICE':\n return; // silenced\n case 'DEBUG':\n lc.debug?.('pg notice', safeNotice(n));\n return;\n case 'WARNING':\n lc.warn?.('pg notice', safeNotice(n));\n return;\n case 'EXCEPTION':\n lc.error?.('pg notice', safeNotice(n));\n return;\n case 'LOG':\n case 'INFO':\n default:\n lc.info?.('pg notice', safeNotice(n));\n }\n };\n const url = new URL(connectionURI);\n const sslFlag =\n url.searchParams.get('ssl') ?? url.searchParams.get('sslmode') ?? 'prefer';\n\n let ssl: boolean | 'prefer' | {rejectUnauthorized: boolean};\n if (sslFlag === 'disable' || sslFlag === 'false') {\n ssl = false;\n } else if (sslFlag === 'no-verify') {\n ssl = {rejectUnauthorized: false};\n } else {\n ssl = sslFlag as 'prefer';\n }\n\n // Set connections to expire between 5 and 10 minutes to free up state on PG.\n const maxLifetimeSeconds = randInt(5 * 60, 10 * 60);\n const {liveness = 'inactivity-timeout', ...pgOptions} = options ?? {};\n const providedConnection = pgOptions.connection ?? {};\n\n // postgres.js supports a custom socket factory via the `socket` option,\n // but it is missing from its type declarations, hence the untyped spread.\n const socketLc = lc.withContext('appName', applicationName);\n const socketFactory = {\n socket:\n liveness === 'keepalive'\n ? // Disable the inactivity watchdog and use TCP keepalive instead.\n inactivityTimeoutSocket(socketLc, 0, 60_000)\n : inactivityTimeoutSocket(socketLc),\n };\n\n return postgres(connectionURI, {\n ...postgresTypeConfig(opts),\n onnotice,\n ['max_lifetime']: maxLifetimeSeconds,\n // Close idle connections cleanly before the socket inactivity timer\n // (which cannot distinguish an idle pool connection from a hung query)\n // resets them.\n ['idle_timeout']: 60,\n ssl,\n ...socketFactory,\n ...pgOptions,\n connection: {\n ...providedConnection,\n ['application_name']: applicationName,\n },\n });\n}\n\nexport async function connectPgClient(\n ...args: Parameters<typeof pgClient>\n): Promise<PostgresDB> {\n const db = pgClient(...args);\n try {\n await db`SELECT 1`.simple().execute();\n return db;\n } catch (e) {\n if (isPostgresConfigError(e)) {\n throw new ConfigurationError(\n 'Unable to connect to Postgres. Check your database configuration.',\n {cause: e},\n );\n }\n throw e;\n }\n}\n\n/**\n * Disables any statement_timeout for the current transaction. By default,\n * Postgres does not impose a statement timeout, but some users and providers\n * set one at the database level (even though it is explicitly discouraged by\n * the Postgres documentation).\n *\n * Zero logic in particular often does not fit into the category of general\n * application logic; for potentially long-running operations like migrations\n * and background cleanup, the statement timeout should be disabled to prevent\n * these operations from timing out.\n */\nexport function disableStatementTimeout(sql: PostgresTransaction) {\n void sql`SET LOCAL statement_timeout = 0;`.execute().catch(() => {});\n}\n\nexport const typeNameByOID: Record<number, string> = Object.freeze(\n Object.fromEntries(\n Object.entries(OID).map(([name, oid]) => [\n oid,\n name.startsWith('_') ? `${name.substring(1)}[]` : name,\n ]),\n ),\n);\n\nexport function isPostgresError(e: unknown, ...codes: [string, ...string[]]) {\n return e instanceof postgres.PostgresError && codes.includes(e.code);\n}\n\nfunction isPostgresStartupConnectionError(e: unknown) {\n if (!(e instanceof Error) || !('code' in e)) {\n return false;\n }\n const {code} = e;\n // postgres.js throws plain Error instances for connection failures that\n // happen before Postgres can return a SQLSTATE. These are still startup\n // configuration problems for Zero: wrong host/port, unreachable DB, DNS,\n // TLS certificate mismatch, etc.\n return (\n typeof code === 'string' &&\n [\n 'CONNECT_TIMEOUT',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ERR_TLS_CERT_ALTNAME_INVALID',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n ].includes(code)\n );\n}\n\nexport function isPostgresConfigError(e: unknown) {\n return (\n isPostgresStartupConnectionError(e) ||\n isPostgresError(\n e,\n PG_CONNECTION_EXCEPTION,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_FAILURE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_PASSWORD,\n PG_INVALID_CATALOG_NAME,\n PG_INSUFFICIENT_PRIVILEGE,\n PG_TOO_MANY_CONNECTIONS,\n PG_CONFIGURATION_LIMIT_EXCEEDED,\n )\n );\n}\n"],"mappings":";;;;;;;;;;AAgCA,IAAM,gBACJ;AAGF,SAAgB,oBAAoB,WAA2B;CAC7D,IAAI,cAAc,YAAY,OAAO;CACrC,IAAI,cAAc,aAAa,OAAO;CACtC,MAAM,QAAQ,UAAU,MAAM,aAAa;CAC3C,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,iBAAiB,WAAW;CAG9C,MAAM,GAAG,SAAS,UAAU,MAAM,MAAM;CACxC,MAAM,KAAK,UAAU,SAAS,KAAK;CAEnC,IAAI,OAAO,OAAO,OAAO;CACzB,IAAI,IAEF,OAAO,EAAE,OAAO;CAKlB,IAAI;CACJ,IAAI,QAAQ,KAAK,QAAQ,MACvB,UAAU,OAAO,IAAI,CAAC,CAAC,SAAS,GAAG,GAAG;MACjC,IAAI,QAAQ,GACjB,UAAU,MAAM,OAAO,IAAI,CAAC,CAAC,SAAS,GAAG,GAAG;MAE5C,UAAU,MAAM,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;CAIxD,MAAM,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,KAAK;CAEjD,IAAI;EACF,MAAM,WAAW,IAAI,YAAY,SAAS,CAAC,CAAC,YAAY;EAGxD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,IAAI;CAC3B,IAAI;EACF,MAAM,EAAE,WAAW,OAAO,CAAC,CAAC,QAAQ;EACpC,OAAO;CACT,SAAS,GAAG;EACV,IAAI,sBAAsB,CAAC,GACzB,MAAM,IAAI,mBACR,qEACA,EAAC,OAAO,EAAC,CACX;EAEF,MAAM;CACR;AACF;AAiBqD,OAAO,OAC1D,OAAO,YACL,OAAO,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,SAAS,CACvC,KACA,KAAK,WAAW,GAAG,IAAI,GAAG,KAAK,UAAU,CAAC,EAAE,MAAM,IACpD,CAAC,CACH,CACF;AAEA,SAAgB,gBAAgB,GAAY,GAAG,OAA8B;CAC3E,OAAO,aAAa,SAAS,iBAAiB,MAAM,SAAS,EAAE,IAAI;AACrE;AAEA,SAAS,iCAAiC,GAAY;CACpD,IAAI,EAAE,aAAa,UAAU,EAAE,UAAU,IACvC,OAAO;CAET,MAAM,EAAC,SAAQ;CAKf,OACE,OAAO,SAAS,YAChB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,SAAS,IAAI;AAEnB;AAEA,SAAgB,sBAAsB,GAAY;CAChD,OACE,iCAAiC,CAAC,KAClC,gBACE,GACA,yBACA,gDACA,8BACA,uBACA,wCACA,qBACA,yBACA,2BACA,yBACA,+BACF;AAEJ"}
@@ -1,17 +1,38 @@
1
1
  import { type PokeChunk } from '../../../zero-protocol/src/poke.ts';
2
2
  export type EmitPokeChunk = (chunk: PokeChunk) => Promise<void>;
3
3
  /**
4
- * Streams a JSON array into fixed-size UTF-8 chunks.
4
+ * Streams a JSON array into bounded UTF-8 chunks.
5
5
  *
6
6
  * The emitter must finish consuming a chunk before its promise resolves. This
7
- * lets the encoder reuse one fixed-size buffer for the entire poke. Memory is
7
+ * lets the encoder reuse its buffer for the rest of the poke, and lets the
8
+ * owner reuse it for its next poke once finish() resolves. Memory is
8
9
  * therefore O(chunk size), independent of poke size.
10
+ *
11
+ * The buffer starts at `INITIAL_POKE_CHUNK_BYTES` and doubles up to
12
+ * `chunkBytes` when a poke needs more, so frames are at most `chunkBytes`.
9
13
  */
10
14
  export declare class PokeChunkEncoder {
11
15
  #private;
12
- constructor(chunkBytes?: number);
16
+ /**
17
+ * @param buffer The buffer returned by the previous poke's finish(), to
18
+ * reuse instead of allocating one.
19
+ */
20
+ constructor(buffer?: Uint8Array | undefined, chunkBytes?: number);
13
21
  addPatch(serializedPatch: string, emit: EmitPokeChunk): Promise<void>;
14
- finish(emit: EmitPokeChunk): Promise<void>;
22
+ /**
23
+ * Returns the buffer once the last emit of its bytes has resolved, so the
24
+ * owner can pass it to the next poke's encoder. Only this path hands the
25
+ * buffer out: a cancelled poke, or one whose emit in finish() failed or timed
26
+ * out, never returns it, since the socket may still be reading the chunk.
27
+ *
28
+ * finish() throws if an addPatch() rejected or hasn't resolved. Otherwise it
29
+ * would send the failed chunk again, close the array in the middle of a
30
+ * patch, and return a buffer the socket may still be reading.
31
+ *
32
+ * A buffer that grew is not returned, so an idle owner holds at most
33
+ * `INITIAL_POKE_CHUNK_BYTES`.
34
+ */
35
+ finish(emit: EmitPokeChunk): Promise<Uint8Array | undefined>;
15
36
  cancel(): void;
16
37
  }
17
38
  //# sourceMappingURL=poke-chunk.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"poke-chunk.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/poke-chunk.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,SAAS,EACf,MAAM,oCAAoC,CAAC;AAI5C,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEhE;;;;;;GAMG;AACH,qBAAa,gBAAgB;;IAO3B,YAAY,UAAU,SAAmB,EAMxC;IAEK,QAAQ,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAI1E;IAEK,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAK/C;IAED,MAAM,IAAI,IAAI,CAGb;CAwBF"}
1
+ {"version":3,"file":"poke-chunk.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/poke-chunk.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,SAAS,EACf,MAAM,oCAAoC,CAAC;AAK5C,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEhE;;;;;;;;;;GAUG;AACH,qBAAa,gBAAgB;;IAW3B;;;OAGG;IACH,YAAY,MAAM,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,UAAU,SAAmB,EAQzE;IAEK,QAAQ,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAO1E;IAED;;;;;;;;;;;;OAYG;IACG,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAOjE;IAED,MAAM,IAAI,IAAI,CAGb;CAsCF"}
@@ -2,34 +2,66 @@ import { assert } from "../../../shared/src/asserts.js";
2
2
  import "../../../zero-protocol/src/poke.js";
3
3
  //#region ../zero-cache/src/types/poke-chunk.ts
4
4
  var POKE_CHUNK_BYTES = 1048576;
5
+ var INITIAL_POKE_CHUNK_BYTES = 16384;
5
6
  /**
6
- * Streams a JSON array into fixed-size UTF-8 chunks.
7
+ * Streams a JSON array into bounded UTF-8 chunks.
7
8
  *
8
9
  * The emitter must finish consuming a chunk before its promise resolves. This
9
- * lets the encoder reuse one fixed-size buffer for the entire poke. Memory is
10
+ * lets the encoder reuse its buffer for the rest of the poke, and lets the
11
+ * owner reuse it for its next poke once finish() resolves. Memory is
10
12
  * therefore O(chunk size), independent of poke size.
13
+ *
14
+ * The buffer starts at `INITIAL_POKE_CHUNK_BYTES` and doubles up to
15
+ * `chunkBytes` when a poke needs more, so frames are at most `chunkBytes`.
11
16
  */
12
17
  var PokeChunkEncoder = class {
13
18
  #encoder = new TextEncoder();
19
+ #chunkBytes;
14
20
  #buffer;
15
21
  #bufferedBytes = 1;
16
22
  #patchCount = 0;
17
23
  #finished = false;
18
- constructor(chunkBytes = POKE_CHUNK_BYTES) {
24
+ #grown = false;
25
+ /** Set while addPatch() runs, and left set if it rejects. */
26
+ #patchInProgress = false;
27
+ /**
28
+ * @param buffer The buffer returned by the previous poke's finish(), to
29
+ * reuse instead of allocating one.
30
+ */
31
+ constructor(buffer, chunkBytes = POKE_CHUNK_BYTES) {
19
32
  assert(chunkBytes >= 5, "poke chunk size must be at least five bytes");
20
- this.#buffer = new Uint8Array(chunkBytes);
33
+ this.#chunkBytes = chunkBytes;
34
+ this.#buffer = buffer ?? new Uint8Array(Math.min(INITIAL_POKE_CHUNK_BYTES, chunkBytes));
21
35
  this.#buffer[0] = 0;
22
36
  }
23
37
  async addPatch(serializedPatch, emit) {
24
38
  assert(!this.#finished, "cannot add a patch to a finished poke");
39
+ assert(!this.#patchInProgress, "previous addPatch() did not complete");
40
+ this.#patchInProgress = true;
25
41
  await this.#write(this.#patchCount++ === 0 ? "[" : ",", emit);
26
42
  await this.#write(serializedPatch, emit);
43
+ this.#patchInProgress = false;
27
44
  }
45
+ /**
46
+ * Returns the buffer once the last emit of its bytes has resolved, so the
47
+ * owner can pass it to the next poke's encoder. Only this path hands the
48
+ * buffer out: a cancelled poke, or one whose emit in finish() failed or timed
49
+ * out, never returns it, since the socket may still be reading the chunk.
50
+ *
51
+ * finish() throws if an addPatch() rejected or hasn't resolved. Otherwise it
52
+ * would send the failed chunk again, close the array in the middle of a
53
+ * patch, and return a buffer the socket may still be reading.
54
+ *
55
+ * A buffer that grew is not returned, so an idle owner holds at most
56
+ * `INITIAL_POKE_CHUNK_BYTES`.
57
+ */
28
58
  async finish(emit) {
29
59
  assert(!this.#finished, "cannot finish a poke twice");
60
+ assert(!this.#patchInProgress, "previous addPatch() did not complete");
30
61
  this.#finished = true;
31
62
  await this.#write(this.#patchCount === 0 ? "[]" : "]", emit);
32
63
  await this.#flush(emit);
64
+ return this.#grown ? void 0 : this.#buffer;
33
65
  }
34
66
  cancel() {
35
67
  this.#finished = true;
@@ -42,9 +74,18 @@ var PokeChunkEncoder = class {
42
74
  const result = this.#encoder.encodeInto(value.slice(read), target);
43
75
  read += result.read;
44
76
  this.#bufferedBytes += result.written;
45
- if (this.#bufferedBytes === this.#buffer.length || result.read === 0) await this.#flush(emit);
77
+ if (read < value.length) {
78
+ if (this.#buffer.length < this.#chunkBytes) this.#grow();
79
+ else await this.#flush(emit);
80
+ }
46
81
  }
47
82
  }
83
+ #grow() {
84
+ const buffer = new Uint8Array(Math.min(this.#buffer.length * 2, this.#chunkBytes));
85
+ buffer.set(this.#buffer.subarray(0, this.#bufferedBytes));
86
+ this.#buffer = buffer;
87
+ this.#grown = true;
88
+ }
48
89
  async #flush(emit) {
49
90
  if (this.#bufferedBytes === 1) return;
50
91
  await emit(this.#buffer.subarray(0, this.#bufferedBytes));
@@ -1 +1 @@
1
- {"version":3,"file":"poke-chunk.js","names":[],"sources":["../../../../../zero-cache/src/types/poke-chunk.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {\n POKE_CHUNK_MESSAGE_TYPE,\n type PokeChunk,\n} from '../../../zero-protocol/src/poke.ts';\n\nconst POKE_CHUNK_BYTES = 1024 * 1024;\n\nexport type EmitPokeChunk = (chunk: PokeChunk) => Promise<void>;\n\n/**\n * Streams a JSON array into fixed-size UTF-8 chunks.\n *\n * The emitter must finish consuming a chunk before its promise resolves. This\n * lets the encoder reuse one fixed-size buffer for the entire poke. Memory is\n * therefore O(chunk size), independent of poke size.\n */\nexport class PokeChunkEncoder {\n readonly #encoder = new TextEncoder();\n readonly #buffer: Uint8Array;\n #bufferedBytes = 1;\n #patchCount = 0;\n #finished = false;\n\n constructor(chunkBytes = POKE_CHUNK_BYTES) {\n // One byte tags the binary message and four bytes are required to encode\n // the largest UTF-8 code point. A smaller buffer could prevent progress.\n assert(chunkBytes >= 5, 'poke chunk size must be at least five bytes');\n this.#buffer = new Uint8Array(chunkBytes);\n this.#buffer[0] = POKE_CHUNK_MESSAGE_TYPE;\n }\n\n async addPatch(serializedPatch: string, emit: EmitPokeChunk): Promise<void> {\n assert(!this.#finished, 'cannot add a patch to a finished poke');\n await this.#write(this.#patchCount++ === 0 ? '[' : ',', emit);\n await this.#write(serializedPatch, emit);\n }\n\n async finish(emit: EmitPokeChunk): Promise<void> {\n assert(!this.#finished, 'cannot finish a poke twice');\n this.#finished = true;\n await this.#write(this.#patchCount === 0 ? '[]' : ']', emit);\n await this.#flush(emit);\n }\n\n cancel(): void {\n this.#finished = true;\n this.#bufferedBytes = 1;\n }\n\n async #write(value: string, emit: EmitPokeChunk): Promise<void> {\n let read = 0;\n while (read < value.length) {\n const target = this.#buffer.subarray(this.#bufferedBytes);\n const result = this.#encoder.encodeInto(value.slice(read), target);\n read += result.read;\n this.#bufferedBytes += result.written;\n\n // A multi-byte code point may not fit in the remaining space.\n if (this.#bufferedBytes === this.#buffer.length || result.read === 0) {\n await this.#flush(emit);\n }\n }\n }\n\n async #flush(emit: EmitPokeChunk): Promise<void> {\n if (this.#bufferedBytes === 1) {\n return;\n }\n await emit(this.#buffer.subarray(0, this.#bufferedBytes));\n this.#bufferedBytes = 1;\n }\n}\n"],"mappings":";;;AAMA,IAAM,mBAAmB;;;;;;;;AAWzB,IAAa,mBAAb,MAA8B;CAC5B,WAAoB,IAAI,YAAY;CACpC;CACA,iBAAiB;CACjB,cAAc;CACd,YAAY;CAEZ,YAAY,aAAa,kBAAkB;EAGzC,OAAO,cAAc,GAAG,6CAA6C;EACrE,KAAK,UAAU,IAAI,WAAW,UAAU;EACxC,KAAK,QAAQ,KAAA;CACf;CAEA,MAAM,SAAS,iBAAyB,MAAoC;EAC1E,OAAO,CAAC,KAAK,WAAW,uCAAuC;EAC/D,MAAM,KAAK,OAAO,KAAK,kBAAkB,IAAI,MAAM,KAAK,IAAI;EAC5D,MAAM,KAAK,OAAO,iBAAiB,IAAI;CACzC;CAEA,MAAM,OAAO,MAAoC;EAC/C,OAAO,CAAC,KAAK,WAAW,4BAA4B;EACpD,KAAK,YAAY;EACjB,MAAM,KAAK,OAAO,KAAK,gBAAgB,IAAI,OAAO,KAAK,IAAI;EAC3D,MAAM,KAAK,OAAO,IAAI;CACxB;CAEA,SAAe;EACb,KAAK,YAAY;EACjB,KAAK,iBAAiB;CACxB;CAEA,MAAM,OAAO,OAAe,MAAoC;EAC9D,IAAI,OAAO;EACX,OAAO,OAAO,MAAM,QAAQ;GAC1B,MAAM,SAAS,KAAK,QAAQ,SAAS,KAAK,cAAc;GACxD,MAAM,SAAS,KAAK,SAAS,WAAW,MAAM,MAAM,IAAI,GAAG,MAAM;GACjE,QAAQ,OAAO;GACf,KAAK,kBAAkB,OAAO;GAG9B,IAAI,KAAK,mBAAmB,KAAK,QAAQ,UAAU,OAAO,SAAS,GACjE,MAAM,KAAK,OAAO,IAAI;EAE1B;CACF;CAEA,MAAM,OAAO,MAAoC;EAC/C,IAAI,KAAK,mBAAmB,GAC1B;EAEF,MAAM,KAAK,KAAK,QAAQ,SAAS,GAAG,KAAK,cAAc,CAAC;EACxD,KAAK,iBAAiB;CACxB;AACF"}
1
+ {"version":3,"file":"poke-chunk.js","names":[],"sources":["../../../../../zero-cache/src/types/poke-chunk.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {\n POKE_CHUNK_MESSAGE_TYPE,\n type PokeChunk,\n} from '../../../zero-protocol/src/poke.ts';\n\nconst POKE_CHUNK_BYTES = 1024 * 1024;\nconst INITIAL_POKE_CHUNK_BYTES = 16 * 1024;\n\nexport type EmitPokeChunk = (chunk: PokeChunk) => Promise<void>;\n\n/**\n * Streams a JSON array into bounded UTF-8 chunks.\n *\n * The emitter must finish consuming a chunk before its promise resolves. This\n * lets the encoder reuse its buffer for the rest of the poke, and lets the\n * owner reuse it for its next poke once finish() resolves. Memory is\n * therefore O(chunk size), independent of poke size.\n *\n * The buffer starts at `INITIAL_POKE_CHUNK_BYTES` and doubles up to\n * `chunkBytes` when a poke needs more, so frames are at most `chunkBytes`.\n */\nexport class PokeChunkEncoder {\n readonly #encoder = new TextEncoder();\n readonly #chunkBytes: number;\n #buffer: Uint8Array;\n #bufferedBytes = 1;\n #patchCount = 0;\n #finished = false;\n #grown = false;\n /** Set while addPatch() runs, and left set if it rejects. */\n #patchInProgress = false;\n\n /**\n * @param buffer The buffer returned by the previous poke's finish(), to\n * reuse instead of allocating one.\n */\n constructor(buffer?: Uint8Array | undefined, chunkBytes = POKE_CHUNK_BYTES) {\n // One byte tags the binary message and four bytes are required to encode\n // the largest UTF-8 code point. A smaller buffer could prevent progress.\n assert(chunkBytes >= 5, 'poke chunk size must be at least five bytes');\n this.#chunkBytes = chunkBytes;\n this.#buffer =\n buffer ?? new Uint8Array(Math.min(INITIAL_POKE_CHUNK_BYTES, chunkBytes));\n this.#buffer[0] = POKE_CHUNK_MESSAGE_TYPE;\n }\n\n async addPatch(serializedPatch: string, emit: EmitPokeChunk): Promise<void> {\n assert(!this.#finished, 'cannot add a patch to a finished poke');\n assert(!this.#patchInProgress, 'previous addPatch() did not complete');\n this.#patchInProgress = true;\n await this.#write(this.#patchCount++ === 0 ? '[' : ',', emit);\n await this.#write(serializedPatch, emit);\n this.#patchInProgress = false;\n }\n\n /**\n * Returns the buffer once the last emit of its bytes has resolved, so the\n * owner can pass it to the next poke's encoder. Only this path hands the\n * buffer out: a cancelled poke, or one whose emit in finish() failed or timed\n * out, never returns it, since the socket may still be reading the chunk.\n *\n * finish() throws if an addPatch() rejected or hasn't resolved. Otherwise it\n * would send the failed chunk again, close the array in the middle of a\n * patch, and return a buffer the socket may still be reading.\n *\n * A buffer that grew is not returned, so an idle owner holds at most\n * `INITIAL_POKE_CHUNK_BYTES`.\n */\n async finish(emit: EmitPokeChunk): Promise<Uint8Array | undefined> {\n assert(!this.#finished, 'cannot finish a poke twice');\n assert(!this.#patchInProgress, 'previous addPatch() did not complete');\n this.#finished = true;\n await this.#write(this.#patchCount === 0 ? '[]' : ']', emit);\n await this.#flush(emit);\n return this.#grown ? undefined : this.#buffer;\n }\n\n cancel(): void {\n this.#finished = true;\n this.#bufferedBytes = 1;\n }\n\n async #write(value: string, emit: EmitPokeChunk): Promise<void> {\n let read = 0;\n while (read < value.length) {\n const target = this.#buffer.subarray(this.#bufferedBytes);\n const result = this.#encoder.encodeInto(value.slice(read), target);\n read += result.read;\n this.#bufferedBytes += result.written;\n\n // The rest didn't fit. The buffer may be full, or a multi-byte code\n // point may not fit in the remaining space.\n if (read < value.length) {\n if (this.#buffer.length < this.#chunkBytes) {\n this.#grow();\n } else {\n await this.#flush(emit);\n }\n }\n }\n }\n\n #grow(): void {\n const buffer = new Uint8Array(\n Math.min(this.#buffer.length * 2, this.#chunkBytes),\n );\n buffer.set(this.#buffer.subarray(0, this.#bufferedBytes));\n this.#buffer = buffer;\n this.#grown = true;\n }\n\n async #flush(emit: EmitPokeChunk): Promise<void> {\n if (this.#bufferedBytes === 1) {\n return;\n }\n await emit(this.#buffer.subarray(0, this.#bufferedBytes));\n this.#bufferedBytes = 1;\n }\n}\n"],"mappings":";;;AAMA,IAAM,mBAAmB;AACzB,IAAM,2BAA2B;;;;;;;;;;;;AAejC,IAAa,mBAAb,MAA8B;CAC5B,WAAoB,IAAI,YAAY;CACpC;CACA;CACA,iBAAiB;CACjB,cAAc;CACd,YAAY;CACZ,SAAS;;CAET,mBAAmB;;;;;CAMnB,YAAY,QAAiC,aAAa,kBAAkB;EAG1E,OAAO,cAAc,GAAG,6CAA6C;EACrE,KAAK,cAAc;EACnB,KAAK,UACH,UAAU,IAAI,WAAW,KAAK,IAAI,0BAA0B,UAAU,CAAC;EACzE,KAAK,QAAQ,KAAA;CACf;CAEA,MAAM,SAAS,iBAAyB,MAAoC;EAC1E,OAAO,CAAC,KAAK,WAAW,uCAAu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D,KAAK,iBAAiB;CACxB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/connection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAW,MAAM,kBAAkB,CAAC;AAE3D,OAAO,SAAkC,MAAM,IAAI,CAAC;AAEpD,OAAO,KAAK,MAAM,MAAM,+BAA+B,CAAC;AAExD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,oCAAoC,CAAC;AAGnE,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,qCAAqC,CAAC;AAKnE,OAAO,EAEL,KAAK,SAAS,EAGf,MAAM,oCAAoC,CAAC;AAK5C,OAAO,EAEL,KAAK,gCAAgC,EACtC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wBAAwB,CAAC;AAOjE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,qBAAqB,CAAC;AAEvD,MAAM,MAAM,aAAa,GACrB;IACE,IAAI,EAAE,IAAI,CAAC;CACZ,GACD;IACE,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,SAAS,CAAC;CAClB,GACD;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,EAAE,SAAS,EAAE,CAAC;CACrB,GACD,YAAY,CAAC;AAEjB,MAAM,MAAM,YAAY,GACpB;IACE,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,YAAY,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC,oBAAoB,CAAC,CAAC;CACtC,GACD;IACE,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,QAAQ,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;CAC5B,CAAC;AAEN,MAAM,WAAW,cAAc;IAC7B,aAAa,CACX,GAAG,EAAE,gCAA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AC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,CAAC,GAAG,qBAAqB,EAChE,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,QAIhC;IAED,SAAS,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,QAE/C;CACF;AAED,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,GAAG;IAC1D,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC;CAClE,CAAC;AAGF,wBAAgB,IAAI,CAClB,EAAE,EAAE,UAAU,EACd,EAAE,EAAE,aAAa,EACjB,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,CAAC,GAAG,qBAAqB,EAChE,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,QA0ChC;AAED;;;;;;GAMG;AACH,qBAAa,gBAAgB;;IAQ3B,YAAY,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,EAIrE;IAED,IAAI,CACF,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,CAAC,GAAG,qBAAqB,EAChE,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,GAC9B,IAAI,CAsBN;CAkDF;AAmFD,wBAAgB,SAAS,CACvB,EAAE,EAAE,UAAU,EACd,EAAE,EAAE,SAAS,EACb,SAAS,EAAE,SAAS,EACpB,MAAM,CAAC,EAAE,OAAO,QA+BjB"}
@@ -8,6 +8,7 @@ import "../../../zero-protocol/src/protocol-version.js";
8
8
  import { getOrCreateCounter } from "../observability/metrics.js";
9
9
  import { ProtocolErrorWithLevel, getLogLevel, wrapWithProtocolError } from "../types/error-with-level.js";
10
10
  import { upstreamSchemaWithUnparsedAnalyzeQuery } from "../../../zero-protocol/src/up.js";
11
+ import { clientGroupLogID } from "../types/client-group-log-id.js";
11
12
  import { PokeChunkEncoder } from "../types/poke-chunk.js";
12
13
  import WebSocket$1, { createWebSocketStream } from "ws";
13
14
  import { Readable, Writable, pipeline } from "node:stream";
@@ -62,7 +63,7 @@ var Connection = class {
62
63
  this.#ws = ws;
63
64
  this.#wsID = wsID;
64
65
  this.#protocolVersion = protocolVersion;
65
- this.#lc = lc.withContext("connection").withContext("clientID", clientID).withContext("clientGroupID", clientGroupID).withContext("wsID", wsID);
66
+ this.#lc = lc.withContext("connection").withContext("clientID", clientID).withContext("clientGroupID", clientGroupLogID(clientGroupID)).withContext("wsID", wsID);
66
67
  this.#downstreamSender = new DownstreamSender(this.#lc, ws, protocolVersion);
67
68
  this.#lc.debug?.("new connection");
68
69
  this.#onClose = onClose;
@@ -265,6 +266,8 @@ var DownstreamSender = class {
265
266
  #ws;
266
267
  #protocolVersion;
267
268
  #pokeChunkEncoder;
269
+ /** The last finished poke's buffer, so the next poke allocates nothing. */
270
+ #idlePokeChunkBuffer;
268
271
  constructor(lc, ws, protocolVersion) {
269
272
  this.#lc = lc;
270
273
  this.#ws = ws;
@@ -274,7 +277,8 @@ var DownstreamSender = class {
274
277
  if (this.#protocolVersion >= 52) switch (data[0]) {
275
278
  case "pokeStart":
276
279
  assert(this.#pokeChunkEncoder === void 0, "cannot start a poke while another poke is in progress");
277
- this.#pokeChunkEncoder = new PokeChunkEncoder();
280
+ this.#pokeChunkEncoder = new PokeChunkEncoder(this.#idlePokeChunkBuffer);
281
+ this.#idlePokeChunkBuffer = void 0;
278
282
  break;
279
283
  case "pokePart":
280
284
  this.#sendPokePart(data, callback, serialized);
@@ -301,7 +305,10 @@ var DownstreamSender = class {
301
305
  send(this.#lc, this.#ws, pokeEnd, callback);
302
306
  return;
303
307
  }
304
- encoder.finish((chunk) => sendBinary(this.#lc, this.#ws, chunk)).then(() => sendAsync(this.#lc, this.#ws, pokeEnd)).then(() => invokeCallback(callback), (error) => invokeCallback(callback, toError(error)));
308
+ encoder.finish((chunk) => sendBinary(this.#lc, this.#ws, chunk)).then((buffer) => {
309
+ this.#idlePokeChunkBuffer = buffer;
310
+ return sendAsync(this.#lc, this.#ws, pokeEnd);
311
+ }).then(() => invokeCallback(callback), (error) => invokeCallback(callback, toError(error)));
305
312
  }
306
313
  };
307
314
  var POKE_PART_PREFIX = "[\"pokePart\",";