@pgxsinkit/server 0.1.4 → 0.1.6

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.
package/dist/index.js ADDED
@@ -0,0 +1,1178 @@
1
+ // @bun
2
+ // packages/server/src/index.ts
3
+ import { eq, sql as sql5 } from "drizzle-orm";
4
+ import { drizzle } from "drizzle-orm/postgres-js";
5
+ import { defineRelations } from "drizzle-orm/relations";
6
+ import { Hono } from "hono";
7
+ import { cors } from "hono/cors";
8
+ import postgres from "postgres";
9
+
10
+ // packages/server/src/mutations/bulk/route.ts
11
+ import { getTableName as getTableName2, sql as sql3 } from "drizzle-orm";
12
+ import { getColumns as getColumns2 } from "drizzle-orm/utils";
13
+ import {
14
+ batchMutationRequestSchema,
15
+ getOmittedProjectedColumns as getOmittedProjectionColumns
16
+ } from "@pgxsinkit/contracts";
17
+
18
+ // packages/server/src/operations-log/writer.ts
19
+ import { sql } from "drizzle-orm";
20
+ function toJson(value) {
21
+ if (value === undefined) {
22
+ return null;
23
+ }
24
+ return JSON.stringify(value);
25
+ }
26
+ async function logOperation(executor, config, entry) {
27
+ if (!config.enabled) {
28
+ return;
29
+ }
30
+ const entityKeyJson = toJson(entry.entityKey ?? null);
31
+ const payloadJson = toJson(entry.payload);
32
+ await executor.execute(sql`
33
+ INSERT INTO operations_log (
34
+ source,
35
+ backend,
36
+ table_name,
37
+ operation_kind,
38
+ user_id,
39
+ entity_key_json,
40
+ payload_json,
41
+ status,
42
+ error_message,
43
+ http_status,
44
+ mutation_id,
45
+ mutation_seq,
46
+ client_timestamp_us,
47
+ request_path,
48
+ server_timestamp_us
49
+ ) VALUES (
50
+ ${entry.source},
51
+ ${entry.backend},
52
+ ${entry.tableName ?? null},
53
+ ${entry.operationKind ?? null},
54
+ ${entry.userId ?? null},
55
+ ${entityKeyJson}::jsonb,
56
+ ${payloadJson}::jsonb,
57
+ ${entry.status},
58
+ ${entry.errorMessage ?? null},
59
+ ${entry.httpStatus ?? null},
60
+ ${entry.mutationId ?? null},
61
+ ${entry.mutationSeq ?? null},
62
+ ${entry.clientTimestampUs ?? null},
63
+ ${entry.requestPath ?? null},
64
+ CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)
65
+ )
66
+ `);
67
+ }
68
+ async function logOperationSafely(executor, config, entry) {
69
+ try {
70
+ await logOperation(executor, config, entry);
71
+ } catch {}
72
+ }
73
+
74
+ // packages/server/src/mutations/bulk/plpgsql-strategy.ts
75
+ import { getTableName, sql as sql2 } from "drizzle-orm";
76
+ import { getTableConfig } from "drizzle-orm/pg-core";
77
+ import { getColumns } from "drizzle-orm/utils";
78
+ import {
79
+ getProjectedColumns
80
+ } from "@pgxsinkit/contracts";
81
+ var PG_TYPE_MAP = {
82
+ PgUUID: "uuid",
83
+ PgText: "text",
84
+ PgVarchar: "varchar",
85
+ PgChar: "char",
86
+ PgInteger: "integer",
87
+ PgSerial: "integer",
88
+ PgSmallInt: "smallint",
89
+ PgSmallIntNumber: "smallint",
90
+ PgBigInt53: "bigint",
91
+ PgBigInt64: "bigint",
92
+ PgBigIntString: "bigint",
93
+ PgBigSerial: "bigint",
94
+ PgBoolean: "boolean",
95
+ PgNumeric: "numeric",
96
+ PgReal: "real",
97
+ PgDoublePrecision: "double precision",
98
+ PgTimestamp: "timestamptz",
99
+ PgTimestampString: "timestamptz",
100
+ PgDate: "date",
101
+ PgDateString: "date",
102
+ PgTime: "time",
103
+ PgTimeString: "time",
104
+ PgJson: "json",
105
+ PgJsonb: "jsonb",
106
+ PgBytea: "bytea",
107
+ PgVector: "vector"
108
+ };
109
+ function drizzleColumnTypeToPg(columnType) {
110
+ return PG_TYPE_MAP[columnType] ?? "text";
111
+ }
112
+ function drizzleColumnToPg(column) {
113
+ const sqlType = column.getSQLType?.();
114
+ if (sqlType && sqlType.length > 0) {
115
+ return sqlType;
116
+ }
117
+ return drizzleColumnTypeToPg(column.columnType);
118
+ }
119
+ function quoteIdent(name) {
120
+ return `"${name.replace(/"/g, '""')}"`;
121
+ }
122
+ function qualifyIdent(schemaName, name) {
123
+ if (!schemaName) {
124
+ return quoteIdent(name);
125
+ }
126
+ return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;
127
+ }
128
+ function toSqlLiteral(value) {
129
+ return value.replace(/'/g, "''");
130
+ }
131
+ function toSqlTextOrNull(value) {
132
+ return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
133
+ }
134
+ function buildManagedFieldExpression(strategy) {
135
+ if (strategy === "authUid") {
136
+ return "auth.uid()";
137
+ }
138
+ return "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)";
139
+ }
140
+ function getManagedFieldsForOperation(entry, operation) {
141
+ const columns = getColumns(entry.table);
142
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [
143
+ propertyKey,
144
+ { name: column.name, columnType: drizzleColumnToPg(column) }
145
+ ]));
146
+ return (entry.governance?.managedFields ?? []).flatMap((field) => {
147
+ if (!field.applyOn.includes(operation)) {
148
+ return [];
149
+ }
150
+ const column = columnMap.get(field.column);
151
+ if (!column) {
152
+ return [];
153
+ }
154
+ return [
155
+ {
156
+ propertyKey: field.column,
157
+ columnName: column.name,
158
+ columnType: drizzleColumnTypeToPg(column.columnType),
159
+ strategy: field.strategy
160
+ }
161
+ ];
162
+ });
163
+ }
164
+ function buildTableBranch(entry) {
165
+ const tableName = getTableName(entry.table);
166
+ const { schema } = getTableConfig(entry.table);
167
+ const qualifiedTableName = qualifyIdent(schema, tableName);
168
+ const columns = getColumns(entry.table);
169
+ const projectedColumns = getProjectedColumns(entry);
170
+ const primaryKeyColumn = entry.primaryKey.columns[0];
171
+ const primaryKeyColumnObject = Object.values(columns).find((column) => column.name === primaryKeyColumn);
172
+ const primaryKeyType = primaryKeyColumnObject ? drizzleColumnToPg(primaryKeyColumnObject) : drizzleColumnTypeToPg("PgText");
173
+ const createManagedFields = getManagedFieldsForOperation(entry, "create");
174
+ const updateManagedFields = getManagedFieldsForOperation(entry, "update");
175
+ const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));
176
+ const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));
177
+ const allColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !createManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`).join(`,
178
+ `);
179
+ const nonPrimaryKeyColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => column.name !== primaryKeyColumn && !updateManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`).join(`,
180
+ `);
181
+ const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
182
+ const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field.strategy)).join(", ");
183
+ const updateManagedAssignmentsSql = updateManagedFields.map((field) => `${quoteIdent(field.columnName)} = ${buildManagedFieldExpression(field.strategy)}`).join(", ");
184
+ const createSqlTemplate = `INSERT INTO ${qualifiedTableName} (%s) VALUES (%s)`.replace(/'/g, "''");
185
+ const updateSqlTemplate = `UPDATE ${qualifiedTableName} SET %s WHERE ${quoteIdent(primaryKeyColumn)} = ($2->>%L)::${primaryKeyType}`.replace(/'/g, "''");
186
+ const createBranch = `
187
+ SELECT format(
188
+ '${createSqlTemplate}',
189
+ concat_ws(', ', nullif(string_agg(quote_ident(col_name), ', '), ''), ${toSqlTextOrNull(createManagedColumnsSql)}),
190
+ concat_ws(', ', nullif(string_agg(format('($1->>%L)::%s', col_name, col_type), ', '), ''), ${toSqlTextOrNull(createManagedValuesSql)})
191
+ )
192
+ INTO dml_sql
193
+ FROM (VALUES
194
+ ${allColumnPairs}
195
+ ) AS col_types(col_name, col_type)
196
+ WHERE v_payload ? col_name;
197
+
198
+ IF dml_sql IS NOT NULL THEN
199
+ EXECUTE dml_sql USING v_payload;
200
+ END IF;
201
+ `.trim();
202
+ const updateBranch = `
203
+ SELECT format(
204
+ '${updateSqlTemplate}',
205
+ concat_ws(', ', nullif(string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '), ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)}),
206
+ '${toSqlLiteral(primaryKeyColumn)}'
207
+ )
208
+ INTO dml_sql
209
+ FROM (VALUES
210
+ ${nonPrimaryKeyColumnPairs}
211
+ ) AS col_types(col_name, col_type)
212
+ WHERE v_payload ? col_name;
213
+
214
+ IF dml_sql IS NOT NULL THEN
215
+ EXECUTE dml_sql USING v_payload, v_entity_key;
216
+ END IF;
217
+ `.trim();
218
+ const deleteBranch = `
219
+ DELETE FROM ${qualifiedTableName}
220
+ WHERE ${quoteIdent(primaryKeyColumn)} = (v_entity_key->>'${toSqlLiteral(primaryKeyColumn)}')::${primaryKeyType};
221
+ `.trim();
222
+ return `
223
+ ELSIF v_table = '${toSqlLiteral(tableName)}' THEN
224
+ IF v_kind = 'create' THEN
225
+ ${createBranch}
226
+ ELSIF v_kind = 'update' THEN
227
+ ${updateBranch}
228
+ ELSIF v_kind = 'delete' THEN
229
+ ${deleteBranch}
230
+ ELSE
231
+ RAISE EXCEPTION 'Unsupported mutation kind "%" for table "%"', v_kind, v_table;
232
+ END IF;
233
+ `.trim();
234
+ }
235
+ function buildPlpgsqlBatchFunctionDdl(registry, options = {}) {
236
+ const tableBranches = Object.values(registry).map((entry) => buildTableBranch(entry)).join(`
237
+ `);
238
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
239
+ return `
240
+ CREATE OR REPLACE FUNCTION ${functionName}(
241
+ p_batch jsonb,
242
+ p_request_path text,
243
+ p_log_enabled boolean,
244
+ p_rls_enabled boolean,
245
+ p_user_claims jsonb
246
+ ) RETURNS void LANGUAGE plpgsql AS $$
247
+ DECLARE
248
+ mutation jsonb;
249
+ dml_sql text;
250
+ v_table text;
251
+ v_kind text;
252
+ v_payload jsonb;
253
+ v_entity_key jsonb;
254
+ v_mutation_id text;
255
+ v_mutation_seq integer;
256
+ v_client_timestamp_us bigint;
257
+ BEGIN
258
+ IF p_rls_enabled THEN
259
+ PERFORM auth.set_auth_context(COALESCE(p_user_claims, '{}'::jsonb));
260
+ END IF;
261
+
262
+ IF jsonb_typeof(p_batch) <> 'object' THEN
263
+ RAISE EXCEPTION 'Batch payload must be a JSON object';
264
+ END IF;
265
+
266
+ IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN
267
+ RAISE EXCEPTION 'Batch payload mutations must be a JSON array';
268
+ END IF;
269
+
270
+ FOR mutation IN SELECT value FROM jsonb_array_elements(p_batch->'mutations')
271
+ LOOP
272
+ dml_sql := NULL;
273
+ v_table := mutation->>'tableName';
274
+ v_kind := mutation->>'kind';
275
+ v_payload := COALESCE(mutation->'payload', '{}'::jsonb);
276
+ v_entity_key := COALESCE(mutation->'entityKey', '{}'::jsonb);
277
+ v_mutation_id := mutation->>'mutationId';
278
+ v_mutation_seq := (mutation->>'mutationSeq')::integer;
279
+ v_client_timestamp_us := NULLIF(mutation->>'clientTimestampUs', '')::bigint;
280
+
281
+ IF FALSE THEN
282
+ NULL;
283
+ ${tableBranches}
284
+ ELSE
285
+ RAISE EXCEPTION 'Unknown table "%" in batch mutation', v_table;
286
+ END IF;
287
+
288
+ IF p_log_enabled THEN
289
+ INSERT INTO operations_log (
290
+ source,
291
+ backend,
292
+ table_name,
293
+ operation_kind,
294
+ entity_key_json,
295
+ payload_json,
296
+ status,
297
+ http_status,
298
+ mutation_id,
299
+ mutation_seq,
300
+ client_timestamp_us,
301
+ request_path,
302
+ server_timestamp_us
303
+ ) VALUES (
304
+ 'batch',
305
+ 'bulk-plpgsql',
306
+ v_table,
307
+ v_kind,
308
+ v_entity_key,
309
+ v_payload,
310
+ 'succeeded',
311
+ 200,
312
+ v_mutation_id::uuid,
313
+ v_mutation_seq,
314
+ v_client_timestamp_us,
315
+ p_request_path,
316
+ CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)
317
+ );
318
+ END IF;
319
+ END LOOP;
320
+ END;
321
+ $$;
322
+ `.trim();
323
+ }
324
+ async function verifyPlpgsqlBatchFunction(db, options = {}) {
325
+ const functionSignature = `${options.functionSchema ? `${options.functionSchema}.` : "public."}pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb)`;
326
+ const result = await db.execute(sql2`
327
+ SELECT to_regprocedure(${functionSignature})::text AS "functionName"
328
+ `);
329
+ const row = Array.from(result, (entry) => entry)[0];
330
+ if (!row?.functionName) {
331
+ throw new Error("bulk-plpgsql-artifact backend requires preinstalled function pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb). Apply sync function migrations before starting the write API.");
332
+ }
333
+ }
334
+ async function verifyArtifactRlsAuthHelpers(db) {
335
+ const result = await db.execute(sql2`
336
+ SELECT
337
+ to_regprocedure('auth.set_auth_context(jsonb)')::text AS "setAuthContext",
338
+ to_regprocedure('auth.uid()')::text AS "authUid",
339
+ to_regprocedure('auth.jwt()')::text AS "authJwt",
340
+ to_regprocedure('auth.has_role(text)')::text AS "authHasRole"
341
+ `);
342
+ const row = Array.from(result, (entry) => entry)[0];
343
+ const missingHelpers = [
344
+ row?.setAuthContext ? null : "auth.set_auth_context(jsonb)",
345
+ row?.authUid ? null : "auth.uid()",
346
+ row?.authJwt ? null : "auth.jwt()",
347
+ row?.authHasRole ? null : "auth.has_role(text)"
348
+ ].filter((value) => value !== null);
349
+ if (missingHelpers.length > 0) {
350
+ throw new Error(`bulk-plpgsql-artifact backend with RLS-enabled tables requires governance SQL to be applied. Missing: ${missingHelpers.join(", ")}. Run bun run db:apply:governance.`);
351
+ }
352
+ }
353
+ async function executePlpgsqlBatch(tx, batch, requestPath, logEnabled, rlsEnabled, userClaims, options = {}) {
354
+ const normalizedClaims = userClaims ?? {};
355
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
356
+ await tx.execute(sql2`SELECT ${sql2.raw(functionName)}(${JSON.stringify(batch)}::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::jsonb)`);
357
+ }
358
+
359
+ // packages/server/src/mutations/bulk/route.ts
360
+ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConfig, operationsLogReady, resolveAuthClaims) {
361
+ let startupReadyPromise;
362
+ const startupReady = () => {
363
+ if (!startupReadyPromise) {
364
+ startupReadyPromise = installBulkStartupDdl(db, registry, backend);
365
+ }
366
+ return startupReadyPromise;
367
+ };
368
+ app.post("/api/mutations", async (context) => {
369
+ await Promise.all([startupReady(), operationsLogReady]);
370
+ let rawBody;
371
+ try {
372
+ rawBody = await context.req.json();
373
+ } catch (error) {
374
+ await logOperationSafely(db, operationsLogConfig, {
375
+ source: "batch",
376
+ backend,
377
+ tableName: null,
378
+ operationKind: null,
379
+ entityKey: null,
380
+ payload: null,
381
+ status: "validation_failed",
382
+ errorMessage: error instanceof Error ? error.message : "Invalid JSON request body",
383
+ httpStatus: 400,
384
+ requestPath: context.req.path
385
+ });
386
+ return context.json({
387
+ message: "Invalid batch mutation request",
388
+ issues: []
389
+ }, 400);
390
+ }
391
+ let body;
392
+ try {
393
+ body = batchMutationRequestSchema.parse(rawBody);
394
+ } catch (error) {
395
+ await logOperationSafely(db, operationsLogConfig, {
396
+ source: "batch",
397
+ backend,
398
+ tableName: null,
399
+ operationKind: null,
400
+ entityKey: null,
401
+ payload: rawBody,
402
+ status: "validation_failed",
403
+ errorMessage: error instanceof Error ? error.message : "Invalid batch mutation request",
404
+ httpStatus: 400,
405
+ requestPath: context.req.path
406
+ });
407
+ return context.json({
408
+ message: "Invalid batch mutation request",
409
+ issues: isValidationError(error) ? error.issues : []
410
+ }, 400);
411
+ }
412
+ const validationErrors = [];
413
+ const invalidMutations = [];
414
+ for (const mutation of body.mutations) {
415
+ if (!(mutation.tableName in registry)) {
416
+ const message = `Unknown table: ${mutation.tableName}`;
417
+ validationErrors.push(message);
418
+ invalidMutations.push({ mutation, message });
419
+ continue;
420
+ }
421
+ const entry = registry[mutation.tableName];
422
+ const syncEntry = entry;
423
+ const schemas = syncEntry.schemas;
424
+ const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);
425
+ const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
426
+ if (projectedFieldViolations.length > 0) {
427
+ const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(", ")}`;
428
+ validationErrors.push(message);
429
+ invalidMutations.push({ mutation, message });
430
+ continue;
431
+ }
432
+ const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
433
+ if (managedFieldViolations.length > 0) {
434
+ const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
435
+ validationErrors.push(message);
436
+ invalidMutations.push({ mutation, message });
437
+ continue;
438
+ }
439
+ try {
440
+ if (mutation.kind === "create" && schemas?.createSchema) {
441
+ schemas.createSchema.parse(normalizedPayload);
442
+ } else if (mutation.kind === "update" && schemas?.updateSchema) {
443
+ schemas.updateSchema.parse(normalizedPayload);
444
+ }
445
+ } catch (error) {
446
+ const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : "";
447
+ const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;
448
+ validationErrors.push(message);
449
+ invalidMutations.push({ mutation, message });
450
+ }
451
+ }
452
+ if (validationErrors.length > 0) {
453
+ for (const invalidMutation of invalidMutations) {
454
+ await logOperationSafely(db, operationsLogConfig, {
455
+ source: "batch",
456
+ backend,
457
+ tableName: invalidMutation.mutation.tableName,
458
+ operationKind: invalidMutation.mutation.kind,
459
+ entityKey: invalidMutation.mutation.entityKey,
460
+ payload: invalidMutation.mutation.payload,
461
+ status: "validation_failed",
462
+ errorMessage: invalidMutation.message,
463
+ httpStatus: 400,
464
+ mutationId: invalidMutation.mutation.mutationId,
465
+ mutationSeq: invalidMutation.mutation.mutationSeq,
466
+ clientTimestampUs: invalidMutation.mutation.clientTimestampUs,
467
+ requestPath: context.req.path
468
+ });
469
+ }
470
+ return context.json({ message: `Payload validation failed: ${validationErrors.join("; ")}` }, 400);
471
+ }
472
+ const acks = [];
473
+ let actorUserId = null;
474
+ const artifactAuthContextRequired = isArtifactAuthContextRequired(registry);
475
+ try {
476
+ await db.transaction(async (tx) => {
477
+ const shouldApplyRlsContext = artifactAuthContextRequired;
478
+ let userClaims = {};
479
+ if (shouldApplyRlsContext) {
480
+ const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
481
+ if (!isPlainObject(resolvedClaims)) {
482
+ await logOperationSafely(db, operationsLogConfig, {
483
+ source: "batch",
484
+ backend,
485
+ tableName: null,
486
+ operationKind: null,
487
+ entityKey: null,
488
+ payload: rawBody,
489
+ status: "validation_failed",
490
+ errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
491
+ httpStatus: 401,
492
+ requestPath: context.req.path
493
+ });
494
+ throw new UnauthorizedBatchMutationError("RLS-enabled artifact backend requires validated JWT claims in request context");
495
+ }
496
+ userClaims = resolvedClaims;
497
+ actorUserId = getUuidClaim(userClaims, "sub");
498
+ }
499
+ const batchRequest = sanitizeArtifactRestrictedFields(body, registry);
500
+ await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
501
+ await executePlpgsqlBatch(tx, batchRequest, context.req.path, false, shouldApplyRlsContext, userClaims);
502
+ if (shouldApplyRlsContext) {
503
+ await tx.execute(sql3`RESET ROLE`);
504
+ }
505
+ for (const mutation of batchRequest.mutations) {
506
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, registry[mutation.tableName], mutation.entityKey);
507
+ await logOperation(tx, operationsLogConfig, {
508
+ source: "batch",
509
+ backend,
510
+ tableName: mutation.tableName,
511
+ operationKind: mutation.kind,
512
+ entityKey: mutation.entityKey,
513
+ payload: mutation.payload,
514
+ status: "succeeded",
515
+ httpStatus: 200,
516
+ mutationId: mutation.mutationId,
517
+ mutationSeq: mutation.mutationSeq,
518
+ clientTimestampUs: mutation.clientTimestampUs,
519
+ requestPath: context.req.path,
520
+ userId: actorUserId
521
+ });
522
+ acks.push({
523
+ tableName: mutation.tableName,
524
+ entityKey: mutation.entityKey,
525
+ mutationId: mutation.mutationId,
526
+ mutationSeq: mutation.mutationSeq,
527
+ status: "acked",
528
+ ...serverUpdatedAtUs ? { serverUpdatedAtUs } : {}
529
+ });
530
+ }
531
+ });
532
+ } catch (error) {
533
+ if (error instanceof UnauthorizedBatchMutationError) {
534
+ return context.json({ message: error.message }, 401);
535
+ }
536
+ const errorMessage = formatBatchExecutionError(error);
537
+ for (const mutation of body.mutations) {
538
+ await logOperationSafely(db, operationsLogConfig, {
539
+ source: "batch",
540
+ backend,
541
+ tableName: mutation.tableName,
542
+ operationKind: mutation.kind,
543
+ entityKey: mutation.entityKey,
544
+ payload: mutation.payload,
545
+ status: "execution_failed",
546
+ errorMessage,
547
+ httpStatus: 500,
548
+ mutationId: mutation.mutationId,
549
+ mutationSeq: mutation.mutationSeq,
550
+ clientTimestampUs: mutation.clientTimestampUs,
551
+ requestPath: context.req.path,
552
+ userId: actorUserId
553
+ });
554
+ }
555
+ return context.json({ message: errorMessage }, 500);
556
+ }
557
+ return context.json({ acks });
558
+ });
559
+ }
560
+ function isValidationError(error) {
561
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
562
+ }
563
+ function isPlainObject(value) {
564
+ return typeof value === "object" && value !== null && !Array.isArray(value);
565
+ }
566
+ function formatBatchExecutionError(error) {
567
+ const rootCause = getRootCauseError(error);
568
+ if (!rootCause) {
569
+ return "Batch mutation failed";
570
+ }
571
+ const details = [rootCause.message];
572
+ const errorCode = getErrorStringProperty(rootCause, "code");
573
+ const errorDetail = getErrorStringProperty(rootCause, "detail");
574
+ const errorHint = getErrorStringProperty(rootCause, "hint");
575
+ if (errorCode) {
576
+ details.push(`code: ${errorCode}`);
577
+ }
578
+ if (errorDetail) {
579
+ details.push(`detail: ${errorDetail}`);
580
+ }
581
+ if (errorHint) {
582
+ details.push(`hint: ${errorHint}`);
583
+ }
584
+ return details.join(" | ");
585
+ }
586
+ function getRootCauseError(error) {
587
+ let current = error;
588
+ let lastError = null;
589
+ const seen = new Set;
590
+ while (current instanceof Error && !seen.has(current)) {
591
+ seen.add(current);
592
+ lastError = current;
593
+ current = current.cause;
594
+ }
595
+ return lastError;
596
+ }
597
+ function getErrorStringProperty(error, key) {
598
+ if (!(key in error)) {
599
+ return null;
600
+ }
601
+ const value = error[key];
602
+ return typeof value === "string" && value.length > 0 ? value : null;
603
+ }
604
+ function isArtifactAuthContextRequired(registry) {
605
+ return Object.values(registry).some((entry) => entry.governance?.rls?.enabled === true || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authUid"));
606
+ }
607
+
608
+ class UnauthorizedBatchMutationError extends Error {
609
+ }
610
+ function getUuidClaim(claims, key) {
611
+ const value = claims[key];
612
+ if (typeof value !== "string") {
613
+ return null;
614
+ }
615
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
616
+ }
617
+ function findManagedFieldViolations(entry, mutationKind, payload) {
618
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
619
+ return [];
620
+ }
621
+ const managedFields = getManagedFieldsForOperation2(entry, mutationKind);
622
+ if (managedFields.length === 0) {
623
+ return [];
624
+ }
625
+ const payloadKeys = new Set(Object.keys(payload));
626
+ return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);
627
+ }
628
+ function findProjectedFieldViolations(entry, mutationKind, payload) {
629
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
630
+ return [];
631
+ }
632
+ const projectedFields = getProjectedAwayFields(entry);
633
+ if (projectedFields.length === 0) {
634
+ return [];
635
+ }
636
+ const payloadKeys = new Set(Object.keys(payload));
637
+ return [
638
+ ...new Set(projectedFields.filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName)).map((field) => field.propertyKey))
639
+ ];
640
+ }
641
+ function sanitizeArtifactRestrictedFields(batch, registry) {
642
+ return {
643
+ mutations: batch.mutations.map((mutation) => {
644
+ if (mutation.kind === "delete") {
645
+ return mutation;
646
+ }
647
+ const entry = registry[mutation.tableName];
648
+ if (!entry) {
649
+ return mutation;
650
+ }
651
+ const managedFields = getManagedFieldsForOperation2(entry, mutation.kind);
652
+ const projectedFields = getProjectedAwayFields(entry);
653
+ if (managedFields.length === 0 && projectedFields.length === 0) {
654
+ return mutation;
655
+ }
656
+ const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};
657
+ for (const field of managedFields) {
658
+ delete payload[field.propertyKey];
659
+ delete payload[field.columnName];
660
+ }
661
+ for (const field of projectedFields) {
662
+ delete payload[field.propertyKey];
663
+ delete payload[field.columnName];
664
+ }
665
+ return {
666
+ ...mutation,
667
+ payload
668
+ };
669
+ })
670
+ };
671
+ }
672
+ function getManagedFieldsForOperation2(entry, mutationKind) {
673
+ if (mutationKind === "delete") {
674
+ return [];
675
+ }
676
+ const columns = getColumns2(entry.table);
677
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
678
+ return (entry.governance?.managedFields ?? []).filter((field) => field.applyOn.includes(mutationKind)).map((field) => ({
679
+ propertyKey: field.column,
680
+ columnName: columnMap.get(field.column) ?? field.column,
681
+ strategy: field.strategy
682
+ }));
683
+ }
684
+ function getProjectedAwayFields(entry) {
685
+ return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
686
+ propertyKey,
687
+ columnName
688
+ }));
689
+ }
690
+ function toSchemaPayload(entry, payload) {
691
+ if (!isPlainObject(payload)) {
692
+ return payload;
693
+ }
694
+ const columns = getColumns2(entry.table);
695
+ const keyMap = new Map;
696
+ for (const [propertyKey, column] of Object.entries(columns)) {
697
+ keyMap.set(propertyKey, propertyKey);
698
+ keyMap.set(column.name, propertyKey);
699
+ }
700
+ return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));
701
+ }
702
+ async function readServerUpdatedAtUs(tx, entry, entityKey) {
703
+ const columns = getColumns2(entry.table);
704
+ const updatedAtColumn = Object.values(columns).find((column) => column.name === "updated_at_us");
705
+ if (!updatedAtColumn) {
706
+ return;
707
+ }
708
+ const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {
709
+ const rawValue = entityKey[primaryKeyColumn];
710
+ if (rawValue === undefined) {
711
+ throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);
712
+ }
713
+ return sql3`${quoteIdentifier(primaryKeyColumn)} = ${rawValue}`;
714
+ });
715
+ const result = await tx.execute(sql3`
716
+ SELECT ${quoteIdentifier("updated_at_us")}::text AS "updatedAtUs"
717
+ FROM ${quoteIdentifier(getTableName2(entry.table))}
718
+ WHERE ${sql3.join(conditions, sql3` AND `)}
719
+ LIMIT 1
720
+ `);
721
+ const row = Array.from(result)[0];
722
+ return row?.updatedAtUs ?? undefined;
723
+ }
724
+ function quoteIdentifier(identifier) {
725
+ return sql3.raw(`"${identifier.replace(/"/g, '""')}"`);
726
+ }
727
+ async function installBulkStartupDdl(db, registry, _backend) {
728
+ await verifyPlpgsqlBatchFunction(db);
729
+ if (isArtifactAuthContextRequired(registry)) {
730
+ await verifyArtifactRlsAuthHelpers(db);
731
+ }
732
+ }
733
+
734
+ // packages/server/src/operations-log/ddl.ts
735
+ import { sql as sql4 } from "drizzle-orm";
736
+ async function ensureOperationsLogSchema(db, config) {
737
+ if (!config.enabled) {
738
+ return;
739
+ }
740
+ const result = await db.execute(sql4`
741
+ SELECT to_regclass('public.operations_log')::text AS "tableName"
742
+ `);
743
+ const row = Array.from(result, (entry) => entry)[0];
744
+ if (!row?.tableName) {
745
+ throw new Error("operations_log table is missing. Run bun run db:push before starting the write API.");
746
+ }
747
+ }
748
+
749
+ // packages/server/src/index.ts
750
+ var defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
751
+ function createSyncServer(options) {
752
+ const client = createPostgresClient(options.databaseUrl);
753
+ const schema = buildSchema(options.registry);
754
+ const db = createDrizzleDatabase(client, schema);
755
+ const app = new Hono;
756
+ let bunServer;
757
+ const status = {
758
+ phase: "ready",
759
+ isRunning: false
760
+ };
761
+ let address = null;
762
+ const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
763
+ const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
764
+ const backend = options.backend ?? "bulk-plpgsql-artifact";
765
+ app.use("/api/*", cors({
766
+ origin: options.allowedOrigins ?? defaultAllowedOrigins,
767
+ allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
768
+ allowHeaders: ["Content-Type", "Authorization"]
769
+ }));
770
+ app.onError((error, context) => {
771
+ status.phase = "degraded";
772
+ status.lastError = error instanceof Error ? error.message : "Unexpected error";
773
+ options.onStatusChange?.(status);
774
+ if (isValidationError2(error)) {
775
+ return context.json({
776
+ message: "Validation failed",
777
+ issues: error.issues
778
+ }, 400);
779
+ }
780
+ return context.json({
781
+ message: error instanceof Error ? error.message : "Unexpected error"
782
+ }, 500);
783
+ });
784
+ app.get("/health", (context) => {
785
+ return context.json({ ok: true });
786
+ });
787
+ for (const [tableKey, entry] of Object.entries(options.registry)) {
788
+ registerTableRoutes(app, db, tableKey, entry, {
789
+ backend,
790
+ operationsLogConfig,
791
+ operationsLogReady
792
+ });
793
+ }
794
+ registerBulkMutationRoute(app, db, options.registry, backend, operationsLogConfig, operationsLogReady, options.resolveAuthClaims);
795
+ const fetch = async (request) => app.fetch(request);
796
+ return {
797
+ drizzle: db,
798
+ fetch,
799
+ request: (path, init) => {
800
+ const baseUrl = address === null ? "http://localhost" : `http://${address.host}:${address.port}`;
801
+ return fetch(new Request(new URL(path, baseUrl), init));
802
+ },
803
+ start: async () => {
804
+ if (bunServer) {
805
+ return;
806
+ }
807
+ const bun = getBunNamespace();
808
+ if (!bun) {
809
+ throw new Error("createSyncServer.start() requires the Bun runtime");
810
+ }
811
+ const host = options.host ?? "0.0.0.0";
812
+ const port = options.port ?? 3001;
813
+ const idleTimeout = options.idleTimeoutSeconds;
814
+ bunServer = bun.serve({
815
+ hostname: host,
816
+ port,
817
+ ...idleTimeout !== undefined ? { idleTimeout } : {},
818
+ fetch: app.fetch
819
+ });
820
+ status.isRunning = true;
821
+ status.phase = "ready";
822
+ delete status.lastError;
823
+ address = { host, port };
824
+ options.onStatusChange?.(status);
825
+ },
826
+ stop: async () => {
827
+ bunServer?.stop();
828
+ bunServer = undefined;
829
+ status.isRunning = false;
830
+ await client.end();
831
+ options.onStatusChange?.(status);
832
+ },
833
+ status,
834
+ get address() {
835
+ return address;
836
+ },
837
+ diagnostics: () => ({
838
+ tables: Object.keys(options.registry),
839
+ modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),
840
+ routes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.routes]))
841
+ })
842
+ };
843
+ }
844
+ function createPostgresClient(connectionString) {
845
+ const url = new URL(connectionString);
846
+ const sslmode = url.searchParams.get("sslmode");
847
+ return postgres({
848
+ host: url.hostname,
849
+ port: Number(url.port || "5432"),
850
+ database: url.pathname.replace(/^\//, ""),
851
+ user: decodeURIComponent(url.username),
852
+ password: decodeURIComponent(url.password),
853
+ ssl: sslmode === "disable" ? false : "prefer",
854
+ max: 10
855
+ });
856
+ }
857
+ function buildSchema(registry) {
858
+ return Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, entry.table]));
859
+ }
860
+ function createDrizzleDatabase(client, schema) {
861
+ const relations = defineRelations(schema);
862
+ const createDatabase = drizzle;
863
+ return createDatabase({ client, relations });
864
+ }
865
+ function registerTableRoutes(app, db, tableKey, entry, options) {
866
+ const basePath = entry.routes?.basePath;
867
+ if (!basePath) {
868
+ return;
869
+ }
870
+ const primaryKeyColumnName = getSinglePrimaryKeyColumnName(entry, tableKey);
871
+ const primaryKeyColumn = getTableColumn(entry.table, primaryKeyColumnName, tableKey);
872
+ const crudWritesAllowed = options.backend !== "bulk-plpgsql-artifact";
873
+ if (entry.mode !== "writeonly") {
874
+ app.get(basePath, async (context) => {
875
+ const rows = await db.select().from(entry.table);
876
+ return context.json(parseRows(entry, rows));
877
+ });
878
+ }
879
+ if (entry.mode !== "readonly") {
880
+ if (!crudWritesAllowed) {
881
+ registerMethodNotAllowed(app, basePath, ["POST", "PATCH", "DELETE"], tableKey);
882
+ registerMethodNotAllowed(app, `${basePath}/:id`, ["PATCH", "DELETE"], tableKey);
883
+ return;
884
+ }
885
+ app.post(basePath, async (context) => {
886
+ await options.operationsLogReady;
887
+ const requestBody = await context.req.json();
888
+ let payload;
889
+ try {
890
+ payload = parseCreatePayload(entry, requestBody);
891
+ } catch (error) {
892
+ await logOperationSafely(db, options.operationsLogConfig, {
893
+ source: "crud",
894
+ backend: options.backend,
895
+ tableName: tableKey,
896
+ operationKind: "create",
897
+ entityKey: extractEntityKeyFromRecord(entry, requestBody),
898
+ payload: requestBody,
899
+ status: "validation_failed",
900
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
901
+ httpStatus: 400,
902
+ requestPath: context.req.path
903
+ });
904
+ return context.json({
905
+ message: "Validation failed",
906
+ issues: isValidationError2(error) ? error.issues : []
907
+ }, 400);
908
+ }
909
+ try {
910
+ const insertedRow = await db.transaction(async (tx) => {
911
+ const inserted = await tx.insert(entry.table).values(payload).returning();
912
+ const row = inserted[0];
913
+ if (!row) {
914
+ throw new Error(`Failed to insert ${tableKey}`);
915
+ }
916
+ await logOperation(tx, options.operationsLogConfig, {
917
+ source: "crud",
918
+ backend: options.backend,
919
+ tableName: tableKey,
920
+ operationKind: "create",
921
+ entityKey: extractEntityKeyFromRecord(entry, row),
922
+ payload,
923
+ status: "succeeded",
924
+ httpStatus: 201,
925
+ requestPath: context.req.path
926
+ });
927
+ return row;
928
+ });
929
+ return context.json(parseRow(entry, insertedRow), 201);
930
+ } catch (error) {
931
+ await logOperationSafely(db, options.operationsLogConfig, {
932
+ source: "crud",
933
+ backend: options.backend,
934
+ tableName: tableKey,
935
+ operationKind: "create",
936
+ entityKey: extractEntityKeyFromRecord(entry, payload),
937
+ payload,
938
+ status: "execution_failed",
939
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
940
+ httpStatus: 500,
941
+ requestPath: context.req.path
942
+ });
943
+ throw error;
944
+ }
945
+ });
946
+ app.patch(`${basePath}/:id`, async (context) => {
947
+ await options.operationsLogReady;
948
+ const id = context.req.param("id");
949
+ const entityKey = {
950
+ [primaryKeyColumnName]: id
951
+ };
952
+ const requestBody = await context.req.json();
953
+ let payload;
954
+ try {
955
+ payload = parseUpdatePayload(entry, requestBody);
956
+ } catch (error) {
957
+ await logOperationSafely(db, options.operationsLogConfig, {
958
+ source: "crud",
959
+ backend: options.backend,
960
+ tableName: tableKey,
961
+ operationKind: "update",
962
+ entityKey,
963
+ payload: requestBody,
964
+ status: "validation_failed",
965
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
966
+ httpStatus: 400,
967
+ requestPath: context.req.path
968
+ });
969
+ return context.json({
970
+ message: "Validation failed",
971
+ issues: isValidationError2(error) ? error.issues : []
972
+ }, 400);
973
+ }
974
+ try {
975
+ const updatedRow = await db.transaction(async (tx) => {
976
+ const updated = await tx.update(entry.table).set(withUpdatedAtUs(entry.table, payload)).where(eq(primaryKeyColumn, id)).returning();
977
+ if (updated.length === 0) {
978
+ await logOperation(tx, options.operationsLogConfig, {
979
+ source: "crud",
980
+ backend: options.backend,
981
+ tableName: tableKey,
982
+ operationKind: "update",
983
+ entityKey,
984
+ payload,
985
+ status: "not_found",
986
+ httpStatus: 404,
987
+ requestPath: context.req.path
988
+ });
989
+ return null;
990
+ }
991
+ const row = updated[0];
992
+ await logOperation(tx, options.operationsLogConfig, {
993
+ source: "crud",
994
+ backend: options.backend,
995
+ tableName: tableKey,
996
+ operationKind: "update",
997
+ entityKey: extractEntityKeyFromRecord(entry, row) ?? entityKey,
998
+ payload,
999
+ status: "succeeded",
1000
+ httpStatus: 200,
1001
+ requestPath: context.req.path
1002
+ });
1003
+ return row;
1004
+ });
1005
+ if (updatedRow === null) {
1006
+ return context.json({ message: `${tableKey} record not found` }, 404);
1007
+ }
1008
+ return context.json(parseRow(entry, updatedRow));
1009
+ } catch (error) {
1010
+ await logOperationSafely(db, options.operationsLogConfig, {
1011
+ source: "crud",
1012
+ backend: options.backend,
1013
+ tableName: tableKey,
1014
+ operationKind: "update",
1015
+ entityKey,
1016
+ payload,
1017
+ status: "execution_failed",
1018
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
1019
+ httpStatus: 500,
1020
+ requestPath: context.req.path
1021
+ });
1022
+ throw error;
1023
+ }
1024
+ });
1025
+ app.delete(`${basePath}/:id`, async (context) => {
1026
+ await options.operationsLogReady;
1027
+ const id = context.req.param("id");
1028
+ const entityKey = {
1029
+ [primaryKeyColumnName]: id
1030
+ };
1031
+ try {
1032
+ const deleted = await db.transaction(async (tx) => {
1033
+ const deletedRows = await tx.delete(entry.table).where(eq(primaryKeyColumn, id)).returning();
1034
+ if (deletedRows.length === 0) {
1035
+ await logOperation(tx, options.operationsLogConfig, {
1036
+ source: "crud",
1037
+ backend: options.backend,
1038
+ tableName: tableKey,
1039
+ operationKind: "delete",
1040
+ entityKey,
1041
+ payload: entityKey,
1042
+ status: "not_found",
1043
+ httpStatus: 404,
1044
+ requestPath: context.req.path
1045
+ });
1046
+ return false;
1047
+ }
1048
+ await logOperation(tx, options.operationsLogConfig, {
1049
+ source: "crud",
1050
+ backend: options.backend,
1051
+ tableName: tableKey,
1052
+ operationKind: "delete",
1053
+ entityKey,
1054
+ payload: entityKey,
1055
+ status: "succeeded",
1056
+ httpStatus: 204,
1057
+ requestPath: context.req.path
1058
+ });
1059
+ return true;
1060
+ });
1061
+ if (!deleted) {
1062
+ return context.json({ message: `${tableKey} record not found` }, 404);
1063
+ }
1064
+ return context.body(null, 204);
1065
+ } catch (error) {
1066
+ await logOperationSafely(db, options.operationsLogConfig, {
1067
+ source: "crud",
1068
+ backend: options.backend,
1069
+ tableName: tableKey,
1070
+ operationKind: "delete",
1071
+ entityKey,
1072
+ payload: entityKey,
1073
+ status: "execution_failed",
1074
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
1075
+ httpStatus: 500,
1076
+ requestPath: context.req.path
1077
+ });
1078
+ throw error;
1079
+ }
1080
+ });
1081
+ }
1082
+ }
1083
+ function getSinglePrimaryKeyColumnName(entry, tableKey) {
1084
+ if (entry.primaryKey.columns.length !== 1) {
1085
+ throw new Error(`@pgxsinkit/server currently supports single-column primary keys only: ${tableKey}`);
1086
+ }
1087
+ return entry.primaryKey.columns[0];
1088
+ }
1089
+ function getTableColumn(table, columnName, tableKey) {
1090
+ const column = table[columnName];
1091
+ if (!column) {
1092
+ throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
1093
+ }
1094
+ return column;
1095
+ }
1096
+ function parseCreatePayload(entry, input) {
1097
+ return entry.schemas?.createSchema ? entry.schemas.createSchema.parse(input) : input;
1098
+ }
1099
+ function parseUpdatePayload(entry, input) {
1100
+ return entry.schemas?.updateSchema ? entry.schemas.updateSchema.parse(input) : input;
1101
+ }
1102
+ function registerMethodNotAllowed(app, path, methods, tableKey) {
1103
+ for (const method of methods) {
1104
+ app.on(method, path, (context) => {
1105
+ context.header("Allow", "GET, OPTIONS");
1106
+ return context.json({
1107
+ message: `CRUD ${method} routes are disabled for ${tableKey} when WRITE_API_BACKEND=bulk-plpgsql-artifact. Use POST /api/mutations instead.`
1108
+ }, 405);
1109
+ });
1110
+ }
1111
+ }
1112
+ function parseRows(entry, rows) {
1113
+ return rows.map((row) => parseRow(entry, row));
1114
+ }
1115
+ function parseRow(entry, row) {
1116
+ const normalized = normalizeBigInts(row);
1117
+ return entry.schemas?.recordSchema ? entry.schemas.recordSchema.parse(normalized) : normalized;
1118
+ }
1119
+ function withUpdatedAtUs(table, payload) {
1120
+ const values = {
1121
+ ...isRecord(payload) ? payload : {}
1122
+ };
1123
+ if ("updatedAtUs" in table) {
1124
+ values.updatedAtUs = sql5`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
1125
+ }
1126
+ return values;
1127
+ }
1128
+ function normalizeBigInts(value) {
1129
+ if (typeof value === "bigint") {
1130
+ return value.toString();
1131
+ }
1132
+ if (Array.isArray(value)) {
1133
+ return value.map((entry) => normalizeBigInts(entry));
1134
+ }
1135
+ if (isRecord(value)) {
1136
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, normalizeBigInts(entry)]));
1137
+ }
1138
+ return value;
1139
+ }
1140
+ function isRecord(value) {
1141
+ return typeof value === "object" && value !== null;
1142
+ }
1143
+ function getBunNamespace() {
1144
+ const maybeBun = globalThis.Bun;
1145
+ return maybeBun;
1146
+ }
1147
+ function isValidationError2(error) {
1148
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
1149
+ }
1150
+ function resolveOperationsLogConfig(options) {
1151
+ return {
1152
+ enabled: options?.enabled ?? true
1153
+ };
1154
+ }
1155
+ function extractEntityKeyFromRecord(entry, value) {
1156
+ if (!isRecord(value)) {
1157
+ return null;
1158
+ }
1159
+ const entityKey = {};
1160
+ for (const primaryKeyColumn of entry.primaryKey.columns) {
1161
+ const rawValue = value[primaryKeyColumn];
1162
+ if (rawValue === undefined || rawValue === null) {
1163
+ return null;
1164
+ }
1165
+ if (typeof rawValue === "string" || typeof rawValue === "number" || typeof rawValue === "bigint" || typeof rawValue === "boolean") {
1166
+ entityKey[primaryKeyColumn] = String(rawValue);
1167
+ continue;
1168
+ }
1169
+ return null;
1170
+ }
1171
+ return entityKey;
1172
+ }
1173
+ export {
1174
+ createSyncServer,
1175
+ buildPlpgsqlBatchFunctionDdl
1176
+ };
1177
+
1178
+ //# debugId=BA7E7DC63BEEBF8964756E2164756E21