@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,206 @@
1
+ // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —
2
+ // specifically a port of the serializer from electric-sql/pglite PR #1035.
3
+ // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
4
+ /**
5
+ * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT
6
+ * text)` stream.
7
+ *
8
+ * The Electric client parses the wire values it receives into native JS values
9
+ * before they reach this module: `int2`/`int4`/`float4`/`float8` become
10
+ * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`
11
+ * become parsed objects/arrays, array columns become (possibly nested) JS
12
+ * arrays, and every other type is left as its raw Postgres text representation
13
+ * (a `string`). To feed those values back into `COPY` we have to reverse that:
14
+ * turn each value into the exact text Postgres' input functions expect, then
15
+ * apply the COPY framing.
16
+ *
17
+ * Rather than invent an escaping scheme (the previous CSV-based approach broke
18
+ * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the
19
+ * two relevant PostgreSQL backend routines:
20
+ *
21
+ * - `CopyAttributeOutText` (src/backend/commands/copyto.c) — field escaping
22
+ * - `array_out` (src/backend/utils/adt/arrayfuncs.c) — array literals
23
+ *
24
+ * The TEXT format is used (not CSV) because it is what Postgres itself emits
25
+ * internally, has a single well-defined escaping algorithm, and round-trips
26
+ * every built-in type.
27
+ */
28
+
29
+ // Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.
30
+ const DELIMITER = "\t";
31
+ const NULL_MARKER = "\\N";
32
+ const ROW_SEPARATOR = "\n";
33
+
34
+ // CopyAttributeOutText escapes the backslash, the field delimiter, and the
35
+ // control characters that have C-style escapes. Every other byte is emitted
36
+ // literally. Our delimiter is a tab, which already has a C-style escape, so the
37
+ // single map below covers all cases.
38
+ const COPY_TEXT_ESCAPES: Record<string, string> = {
39
+ "\\": "\\\\",
40
+ "\b": "\\b",
41
+ "\f": "\\f",
42
+ "\n": "\\n",
43
+ "\r": "\\r",
44
+ "\t": "\\t",
45
+ "\v": "\\v",
46
+ };
47
+ const COPY_TEXT_ESCAPE_RE = /[\\\b\f\n\r\t\v]/g;
48
+
49
+ /** Escape an already-stringified field value per `CopyAttributeOutText`. */
50
+ function escapeCopyText(value: string): string {
51
+ return value.replace(COPY_TEXT_ESCAPE_RE, (c) => COPY_TEXT_ESCAPES[c] ?? c);
52
+ }
53
+
54
+ /**
55
+ * Convert a Uint8Array to Postgres `bytea` hex-format text (`\xDEADBEEF`).
56
+ * Electric normally delivers `bytea` already as such a string, so this only
57
+ * matters for callers using a custom parser that yields binary.
58
+ */
59
+ function byteaToText(bytes: Uint8Array): string {
60
+ let hex = "";
61
+ for (const byte of bytes) {
62
+ hex += byte.toString(16).padStart(2, "0");
63
+ }
64
+ return "\\x" + hex;
65
+ }
66
+
67
+ /**
68
+ * Render a JS `number` the way Postgres' float/int input accepts it. The only
69
+ * special cases are the non-finite values, which Postgres spells out in words.
70
+ */
71
+ function numberToText(value: number): string {
72
+ if (Number.isNaN(value)) return "NaN";
73
+ if (value === Infinity) return "Infinity";
74
+ if (value === -Infinity) return "-Infinity";
75
+ return String(value);
76
+ }
77
+
78
+ // array_out quotes an element when it is empty, looks like the literal NULL, or
79
+ // contains a brace, the element delimiter (comma), a double-quote, a backslash,
80
+ // or ASCII whitespace. We mirror `array_isspace`, which is stricter than JS
81
+ // `\s` (it excludes Unicode whitespace), so the output matches Postgres' own
82
+ // `array_out` TEXT format exactly and re-parses correctly on `COPY FROM`.
83
+ const ARRAY_NEEDS_QUOTE_RE = /[{}",\\ \t\n\r\v\f]/;
84
+
85
+ /** Quote/escape a single array element's text per `array_out`. */
86
+ function quoteArrayElement(text: string): string {
87
+ const needsQuote = text.length === 0 || text.toLowerCase() === "null" || ARRAY_NEEDS_QUOTE_RE.test(text);
88
+ if (!needsQuote) return text;
89
+ // Inside quotes only `"` and `\` are escaped, each with a single backslash.
90
+ return '"' + text.replace(/(["\\])/g, "\\$1") + '"';
91
+ }
92
+
93
+ /**
94
+ * Build a Postgres array literal (`{...}`) from a JS array, recursing into
95
+ * nested arrays for multi-dimensional arrays. NULL elements become an unquoted
96
+ * `NULL`; nested arrays are emitted as bare `{...}` (never quoted), exactly as
97
+ * `array_out` does.
98
+ */
99
+ function arrayToText(arr: ReadonlyArray<unknown>): string {
100
+ const elements = arr.map((el) => {
101
+ if (el === null || el === undefined) return "NULL";
102
+ if (Array.isArray(el)) return arrayToText(el);
103
+ return quoteArrayElement(valueToText(el));
104
+ });
105
+ return "{" + elements.join(",") + "}";
106
+ }
107
+
108
+ /**
109
+ * Convert a non-null JS value to its bare Postgres text representation (before
110
+ * COPY field escaping is applied). Dispatch is on the runtime type produced by
111
+ * the Electric parser. `json`/`jsonb` columns are handled ahead of this by
112
+ * `serializeCopyValue` when a column type is known; reaching the object branch
113
+ * here is the type-less fallback.
114
+ */
115
+ function valueToText(value: unknown): string {
116
+ switch (typeof value) {
117
+ case "string":
118
+ return value;
119
+ case "number":
120
+ return numberToText(value);
121
+ case "bigint":
122
+ return value.toString();
123
+ case "boolean":
124
+ return value ? "t" : "f";
125
+ case "object": {
126
+ if (Array.isArray(value)) return arrayToText(value);
127
+ if (value instanceof Date) return value.toISOString();
128
+ if (value instanceof Uint8Array) return byteaToText(value);
129
+ if (value instanceof ArrayBuffer) return byteaToText(new Uint8Array(value));
130
+ if (ArrayBuffer.isView(value)) {
131
+ const view = value as ArrayBufferView;
132
+ return byteaToText(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
133
+ }
134
+ // json / jsonb arrive already parsed; re-serialize them.
135
+ return JSON.stringify(value);
136
+ }
137
+ default:
138
+ // Should be unreachable for Electric-parsed values; be defensive.
139
+ return String(value);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Build a Postgres array literal from a `json[]`/`jsonb[]` value. Each element
145
+ * is JSON text (re-serialized from the parsed value), so we cannot reuse the
146
+ * generic array path: a JSON array element must stay JSON (`[1,2]`), not be
147
+ * turned into a nested SQL array (`{1,2}`).
148
+ */
149
+ function jsonArrayToText(arr: ReadonlyArray<unknown>): string {
150
+ const elements = arr.map((el) => (el === null || el === undefined ? "NULL" : quoteArrayElement(jsonToText(el))));
151
+ return "{" + elements.join(",") + "}";
152
+ }
153
+
154
+ /**
155
+ * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric
156
+ * delivers these columns already run through `JSON.parse`, so the value is the
157
+ * decoded JS value (object, array, string, number, boolean or null) and always
158
+ * needs `JSON.stringify` to become valid JSON input again — including scalars
159
+ * (the string `hi` must be written as `"hi"`).
160
+ */
161
+ function jsonToText(value: unknown): string {
162
+ return JSON.stringify(value);
163
+ }
164
+
165
+ /**
166
+ * Postgres `udt_name`s that need JSON-aware serialization rather than the
167
+ * generic runtime-type dispatch. Used to resolve the otherwise undecidable
168
+ * "is this JS array a SQL array or a JSON array?" ambiguity.
169
+ */
170
+ const JSON_UDT_NAMES = new Set(["json", "jsonb"]);
171
+ const JSON_ARRAY_UDT_NAMES = new Set(["_json", "_jsonb"]);
172
+
173
+ /**
174
+ * Serialize a single value into one COPY TEXT field. `null`/`undefined` become
175
+ * the NULL marker (`\N`); everything else is converted to text and escaped.
176
+ *
177
+ * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates
178
+ * `json`/`jsonb` columns; when omitted the value's runtime type is used (which
179
+ * cannot tell a `jsonb` array from a SQL array).
180
+ */
181
+ export function serializeCopyValue(value: unknown, udtName?: string): string {
182
+ if (value === null || value === undefined) return NULL_MARKER;
183
+ if (udtName !== undefined) {
184
+ if (JSON_UDT_NAMES.has(udtName)) return escapeCopyText(jsonToText(value));
185
+ if (JSON_ARRAY_UDT_NAMES.has(udtName) && Array.isArray(value)) return escapeCopyText(jsonArrayToText(value));
186
+ }
187
+ return escapeCopyText(valueToText(value));
188
+ }
189
+
190
+ /**
191
+ * Serialize a list of row objects into the body of a `COPY ... FROM` request in
192
+ * TEXT format. Columns are emitted in the given order, fields are tab
193
+ * separated, and rows are newline separated.
194
+ *
195
+ * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass
196
+ * it so `json`/`jsonb` columns serialize correctly.
197
+ */
198
+ export function generateCopyData(
199
+ rows: ReadonlyArray<Record<string, unknown>>,
200
+ columns: ReadonlyArray<string>,
201
+ columnTypes?: Readonly<Record<string, string | undefined>>,
202
+ ): string {
203
+ return rows
204
+ .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))
205
+ .join(ROW_SEPARATOR);
206
+ }
@@ -0,0 +1,48 @@
1
+ import type { PGlite, PGliteInterface, Transaction } from "@electric-sql/pglite";
2
+ import { drizzle, type PgliteDatabase } from "drizzle-orm/pglite";
3
+
4
+ /**
5
+ * A Drizzle handle whose executor is an already-open PGlite connection *or* an open PGlite
6
+ * `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML
7
+ * (ADR-0028 decision 4).
8
+ *
9
+ * The blocker the old convertibility report cited was "`drizzle-orm/pglite` wraps only a PGlite
10
+ * instance, not a Transaction". That is a *type* boundary, not a runtime one: drizzle's pglite session
11
+ * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified
12
+ * against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the
13
+ * only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).
14
+ * PGlite's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle
15
+ * built over a `Transaction` executes every statement **on that transaction** — participating in the
16
+ * engine's commit boundary rather than opening its own.
17
+ *
18
+ * The cast to `PGlite` is the narrowest honest one: at runtime the session only calls `.query`, which
19
+ * both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the
20
+ * expected single-expression cast for this seam.
21
+ *
22
+ * CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction
23
+ * boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync
24
+ * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full PGlite,
25
+ * which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose
26
+ * or use it.
27
+ *
28
+ * MUST be the `{ client }` config form: drizzle's pglite driver destructures `{ connection, client }`
29
+ * from a bare first argument, so `drizzle(pg)` misdetects the handle as a config object and silently
30
+ * constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.
31
+ */
32
+
33
+ // One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`
34
+ // is short-lived (one commit) but reused across the several metadata statements that run within that
35
+ // commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while
36
+ // never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the
37
+ // WeakMap drops it once the commit's closure is collected).
38
+ const handles = new WeakMap<PGliteInterface | Transaction, PgliteDatabase<never>>();
39
+
40
+ /** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */
41
+ export function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never> {
42
+ let db = handles.get(pg);
43
+ if (!db) {
44
+ db = drizzle({ client: pg as unknown as PGlite }) as PgliteDatabase<never>;
45
+ handles.set(pg, db);
46
+ }
47
+ return db;
48
+ }