@prisma-next/adapter-postgres 0.12.0-dev.5 → 0.12.0-dev.50

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.
@@ -0,0 +1,1357 @@
1
+ import { APP_SPACE_ID, extractCodecLookup } from "@prisma-next/framework-components/control";
2
+ import { LiteralExpr, RawExpr, collectOrderedParamRefs, isDdlNode } from "@prisma-next/sql-relational-core/ast";
3
+ import { postgresCodecRegistry } from "@prisma-next/target-postgres/codecs";
4
+ import { parseMarkerRowSafely, rethrowMarkerReadError, withMarkerReadErrorHandling } from "@prisma-next/errors/execution";
5
+ import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
6
+ import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
7
+ import { PostgresTableSource, buildControlTableBootstrapQueries, buildSignMarkerBootstrapQueries, int4, int8, jsonb, pgTable, text, textArray, timestamptz } from "@prisma-next/target-postgres/contract-free";
8
+ import { parsePostgresDefault } from "@prisma-next/target-postgres/default-normalizer";
9
+ import { createResolveExistingEnumValues, enumStorageCompoundKey, readExistingEnumValues, readPostgresSchemaIrAnnotations } from "@prisma-next/target-postgres/enum-planning";
10
+ import { normalizeSchemaNativeType } from "@prisma-next/target-postgres/native-type-normalizer";
11
+ import { blindCast } from "@prisma-next/utils/casts";
12
+ import { ifDefined } from "@prisma-next/utils/defined";
13
+ import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
14
+ import { PG_ENUM_CODEC_ID, PG_TIMESTAMPTZ_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
15
+ import { createAstCodecRegistry, deriveParamMetadata, encodeParamsWithMetadata } from "@prisma-next/sql-runtime";
16
+ import { runtimeError } from "@prisma-next/framework-components/runtime";
17
+ //#region src/core/codec-lookup.ts
18
+ /**
19
+ * Build a {@link CodecLookup} populated with the Postgres-builtin codec definitions only.
20
+ *
21
+ * This is the default lookup used by `createPostgresAdapter()` and `new PostgresControlAdapter()` when called without a stack-derived lookup (e.g. from tests, or one-off scripts that don't compose a full stack).
22
+ *
23
+ * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`) are intentionally NOT included here: a bare adapter cannot see extensions. Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` / `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader, extension-inclusive lookup at construction time.
24
+ */
25
+ function createPostgresBuiltinCodecLookup() {
26
+ return extractCodecLookup([{
27
+ id: "postgres-builtin-codecs",
28
+ types: { codecTypes: { codecDescriptors: Array.from(postgresCodecRegistry.values()) } }
29
+ }]);
30
+ }
31
+ //#endregion
32
+ //#region ../../../1-framework/3-tooling/migration/dist/exports/ledger-origin.mjs
33
+ function ledgerOriginFromStored(originCoreHash) {
34
+ if (originCoreHash === null || originCoreHash === "" || originCoreHash === "sha256:empty") return null;
35
+ return originCoreHash;
36
+ }
37
+ //#endregion
38
+ //#region src/core/ddl-renderer.ts
39
+ var PostgresDdlVisitorImpl = class {
40
+ createTable(node) {
41
+ return `create table ${node.ifNotExists ? "if not exists " : ""}${node.schema ? `${node.schema}.${node.table}` : node.table} (\n ${node.columns.map((column) => renderColumn$1(column)).join(",\n ")}\n )`;
42
+ }
43
+ createSchema(node) {
44
+ return `create schema ${node.ifNotExists ? "if not exists " : ""}${node.schema}`;
45
+ }
46
+ };
47
+ const defaultVisitor = {
48
+ literal(node) {
49
+ const { value } = node;
50
+ if (typeof value === "string") return `default '${escapeLiteral(value)}'`;
51
+ if (typeof value === "number" || typeof value === "boolean") return `default ${String(value)}`;
52
+ if (value === null) return "default null";
53
+ return `default '${JSON.stringify(value)}'`;
54
+ },
55
+ function(node) {
56
+ if (node.expression === "autoincrement()") return "";
57
+ if (node.expression === "now()") return "default now()";
58
+ return `default (${node.expression})`;
59
+ }
60
+ };
61
+ function renderColumn$1(column) {
62
+ const parts = [column.name, column.type];
63
+ if (column.notNull) parts.push("not null");
64
+ if (column.primaryKey) parts.push("primary key");
65
+ const defaultClause = column.default ? column.default.accept(defaultVisitor) : "";
66
+ if (defaultClause.length > 0) parts.push(defaultClause);
67
+ return parts.join(" ");
68
+ }
69
+ function renderLoweredDdl(ast) {
70
+ const sql = ast.accept(new PostgresDdlVisitorImpl());
71
+ return Object.freeze({
72
+ sql,
73
+ params: Object.freeze([])
74
+ });
75
+ }
76
+ //#endregion
77
+ //#region src/core/enum-control-hooks.ts
78
+ const ENUM_INTROSPECT_QUERY = `
79
+ SELECT
80
+ n.nspname AS schema_name,
81
+ t.typname AS type_name,
82
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
83
+ FROM pg_type t
84
+ JOIN pg_namespace n ON t.typnamespace = n.oid
85
+ JOIN pg_enum e ON t.oid = e.enumtypid
86
+ WHERE n.nspname = $1
87
+ GROUP BY n.nspname, t.typname
88
+ ORDER BY n.nspname, t.typname
89
+ `;
90
+ function isStringArray(value) {
91
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
92
+ }
93
+ /**
94
+ * Parses a PostgreSQL array value into a JavaScript string array.
95
+ *
96
+ * The `pg` library returns `array_agg` results either as a JS array
97
+ * (when type parsers are configured) or as a string in PostgreSQL array
98
+ * literal format (`{value1,value2,...}`). Handles PG's quoting rules:
99
+ * - Elements containing commas, quotes, backslashes, or whitespace are
100
+ * double-quoted.
101
+ * - Inside quoted elements, `\"` represents `"` and `\\` represents `\`.
102
+ *
103
+ * Returns `null` when the input cannot be parsed as a PG array.
104
+ */
105
+ function parsePostgresArray(value) {
106
+ if (isStringArray(value)) return value;
107
+ if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
108
+ const inner = value.slice(1, -1);
109
+ if (inner === "") return [];
110
+ return parseArrayElements(inner);
111
+ }
112
+ return null;
113
+ }
114
+ function parseArrayElements(input) {
115
+ const result = [];
116
+ let i = 0;
117
+ while (i < input.length) {
118
+ if (input[i] === ",") {
119
+ i++;
120
+ continue;
121
+ }
122
+ if (input[i] === "\"") {
123
+ i++;
124
+ let element = "";
125
+ while (i < input.length && input[i] !== "\"") {
126
+ if (input[i] === "\\" && i + 1 < input.length) {
127
+ i++;
128
+ element += input[i];
129
+ } else element += input[i];
130
+ i++;
131
+ }
132
+ i++;
133
+ result.push(element);
134
+ } else {
135
+ const nextComma = input.indexOf(",", i);
136
+ if (nextComma === -1) {
137
+ result.push(input.slice(i).trim());
138
+ i = input.length;
139
+ } else {
140
+ result.push(input.slice(i, nextComma).trim());
141
+ i = nextComma;
142
+ }
143
+ }
144
+ }
145
+ return result;
146
+ }
147
+ /**
148
+ * Reads enum types from the live Postgres schema and returns them in
149
+ * the codec-typed annotation shape consumed by `control-adapter.ts`
150
+ * (which writes them under `schema.annotations.pg.storageTypes`).
151
+ */
152
+ async function introspectPostgresEnumTypes(options) {
153
+ const namespace = options.schemaName ?? "public";
154
+ const result = await options.driver.query(ENUM_INTROSPECT_QUERY, [namespace]);
155
+ const types = {};
156
+ for (const row of result.rows) {
157
+ const values = parsePostgresArray(row.values);
158
+ if (!values) throw new Error(`Failed to parse enum values for type "${row.type_name}": unexpected format: ${JSON.stringify(row.values)}`);
159
+ types[row.type_name] = {
160
+ codecId: PG_ENUM_CODEC_ID,
161
+ nativeType: row.type_name,
162
+ typeParams: { values }
163
+ };
164
+ }
165
+ return types;
166
+ }
167
+ //#endregion
168
+ //#region src/core/marker-ledger.ts
169
+ const CONTROL_CODECS = createAstCodecRegistry(postgresCodecRegistry);
170
+ const marker = pgTable({
171
+ name: "marker",
172
+ schema: "prisma_contract"
173
+ }, {
174
+ space: text(),
175
+ core_hash: text(),
176
+ profile_hash: text(),
177
+ contract_json: jsonb({ nullable: true }),
178
+ canonical_version: int4({ nullable: true }),
179
+ updated_at: timestamptz(),
180
+ app_tag: text({ nullable: true }),
181
+ meta: jsonb({ nullable: true }),
182
+ invariants: textArray()
183
+ });
184
+ /**
185
+ * Writeable subset of the `prisma_contract.ledger` table. Omits the
186
+ * DB-generated `id` (bigserial) and `created_at` (default `now()`) so the
187
+ * insert path doesn't have to pass them.
188
+ */
189
+ const ledger = pgTable({
190
+ name: "ledger",
191
+ schema: "prisma_contract"
192
+ }, {
193
+ space: text(),
194
+ migration_name: text(),
195
+ migration_hash: text(),
196
+ origin_core_hash: text({ nullable: true }),
197
+ destination_core_hash: text(),
198
+ operations: jsonb()
199
+ });
200
+ /**
201
+ * Read-side handle covering every column of `prisma_contract.ledger`,
202
+ * including the DB-generated `id` (for ORDER BY) and `created_at`.
203
+ */
204
+ const ledgerReadShape = pgTable({
205
+ name: "ledger",
206
+ schema: "prisma_contract"
207
+ }, {
208
+ id: int8(),
209
+ space: text(),
210
+ migration_name: text(),
211
+ migration_hash: text(),
212
+ origin_core_hash: text({ nullable: true }),
213
+ destination_core_hash: text(),
214
+ operations: jsonb(),
215
+ created_at: timestamptz()
216
+ });
217
+ const infoSchemaTables = pgTable({
218
+ name: "tables",
219
+ schema: "information_schema"
220
+ }, {
221
+ table_schema: text(),
222
+ table_name: text()
223
+ });
224
+ const NOW = new RawExpr({
225
+ parts: ["now()"],
226
+ returns: {
227
+ codecId: PG_TIMESTAMPTZ_CODEC_ID,
228
+ nullable: false
229
+ }
230
+ });
231
+ function mergeInvariants(current, incoming) {
232
+ return [...new Set([...current, ...incoming])].sort();
233
+ }
234
+ async function execute(lower, driver, query) {
235
+ const lowered = lower(query);
236
+ const encoded = await encodeParamsWithMetadata(lowered.params.map((slot) => {
237
+ if (slot.kind === "literal") return slot.value;
238
+ throw new Error("Postgres control DML lowered to a bind parameter, which is unsupported");
239
+ }), deriveParamMetadata(query), {}, CONTROL_CODECS);
240
+ return (await driver.query(lowered.sql, encoded)).rows;
241
+ }
242
+ //#endregion
243
+ //#region src/core/sql-renderer.ts
244
+ /**
245
+ * Postgres native types whose unknown-OID parameter inference is reliable in arbitrary expression positions. Parameters bound to a codec whose `meta.db.sql.postgres.nativeType` falls in this set are emitted as plain `$N`; everything else (including `json`, `jsonb`, extension types like `vector`, and unknown user types) is emitted as `$N::<nativeType>` so the planner picks an unambiguous overload.
246
+ *
247
+ * `json` / `jsonb` are intentionally excluded despite being Postgres builtins: their operator overloads make context inference unreliable in expression positions (e.g. `$1 -> 'key'` is ambiguous between the two).
248
+ *
249
+ * Spellings match the on-disk `meta.db.sql.postgres.nativeType` values in `@prisma-next/target-postgres`'s codec definitions, not the `udt_name` abbreviations that ADR 205 used as illustrative shorthand. The lookup-based cast policy compares against these strings directly.
250
+ */
251
+ const POSTGRES_INFERRABLE_NATIVE_TYPES = new Set([
252
+ "integer",
253
+ "smallint",
254
+ "bigint",
255
+ "real",
256
+ "double precision",
257
+ "numeric",
258
+ "boolean",
259
+ "text",
260
+ "character",
261
+ "character varying",
262
+ "timestamp",
263
+ "timestamp without time zone",
264
+ "timestamp with time zone",
265
+ "time",
266
+ "timetz",
267
+ "interval",
268
+ "bit",
269
+ "bit varying"
270
+ ]);
271
+ function renderTypedParam(index, codecId, codecLookup) {
272
+ if (codecId === void 0) return `$${index}`;
273
+ const meta = codecLookup.metaFor(codecId);
274
+ if (!(codecLookup.get(codecId) !== void 0 || meta !== void 0 || codecLookup.targetTypesFor(codecId) !== void 0)) throw new Error(`Postgres lowering: ParamRef carries codecId "${codecId}" but the assembled codec lookup has no entry for it. This usually indicates a missing extension pack in the runtime stack — register the pack that contributes this codec (e.g. \`extensionPacks: [pgvectorRuntime]\`), or use the codec directly from \`@prisma-next/target-postgres/codecs\` if it's a builtin.`);
275
+ const dbRecord = meta?.db;
276
+ const sqlBlock = isRecord(dbRecord) ? dbRecord["sql"] : void 0;
277
+ const dialectBlock = isRecord(sqlBlock) ? sqlBlock["postgres"] : void 0;
278
+ const nativeType = isRecord(dialectBlock) ? dialectBlock["nativeType"] : void 0;
279
+ if (typeof nativeType === "string" && !POSTGRES_INFERRABLE_NATIVE_TYPES.has(nativeType)) return `$${index}::${nativeType}`;
280
+ return `$${index}`;
281
+ }
282
+ function isRecord(value) {
283
+ return typeof value === "object" && value !== null;
284
+ }
285
+ /**
286
+ * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.
287
+ *
288
+ * Shared between the runtime (`PostgresAdapterImpl.lower`) and control (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time paths produce byte-identical output for the same AST.
289
+ */
290
+ function renderLoweredSql(ast, contract, codecLookup) {
291
+ const orderedRefs = collectOrderedParamRefs(ast);
292
+ const indexMap = /* @__PURE__ */ new Map();
293
+ const params = orderedRefs.map((ref, i) => {
294
+ indexMap.set(ref, i + 1);
295
+ return ref.kind === "prepared-param-ref" ? {
296
+ kind: "bind",
297
+ name: ref.name
298
+ } : {
299
+ kind: "literal",
300
+ value: ref.value
301
+ };
302
+ });
303
+ const pim = {
304
+ indexMap,
305
+ codecLookup
306
+ };
307
+ const node = ast;
308
+ let sql;
309
+ switch (node.kind) {
310
+ case "select":
311
+ sql = renderSelect(node, contract, pim);
312
+ break;
313
+ case "insert":
314
+ sql = renderInsert(node, contract, pim);
315
+ break;
316
+ case "update":
317
+ sql = renderUpdate(node, contract, pim);
318
+ break;
319
+ case "delete":
320
+ sql = renderDelete(node, contract, pim);
321
+ break;
322
+ case "raw-sql":
323
+ sql = renderRawSql(node, contract, pim);
324
+ break;
325
+ // v8 ignore next 4
326
+ default: throw new Error(`Unsupported AST node kind: ${node.kind}`);
327
+ }
328
+ return Object.freeze({
329
+ sql,
330
+ params: Object.freeze(params)
331
+ });
332
+ }
333
+ function renderLimitOffset(keyword, value, contract, pim) {
334
+ if (value === void 0) return "";
335
+ if (typeof value === "number") return `${keyword} ${value}`;
336
+ return `${keyword} ${renderExpr(value, contract, pim)}`;
337
+ }
338
+ function renderSelect(ast, contract, pim) {
339
+ return [
340
+ `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(ast.projection, contract, pim)}`,
341
+ `FROM ${renderSource(ast.from, contract, pim)}`,
342
+ ast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(" ") : "",
343
+ ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : "",
344
+ ast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(", ")}` : "",
345
+ ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : "",
346
+ ast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => {
347
+ return `${renderExpr(order.expr, contract, pim)} ${order.dir.toUpperCase()}`;
348
+ }).join(", ")}` : "",
349
+ renderLimitOffset("LIMIT", ast.limit, contract, pim),
350
+ renderLimitOffset("OFFSET", ast.offset, contract, pim)
351
+ ].filter((part) => part.length > 0).join(" ").trim();
352
+ }
353
+ function renderProjection(projection, contract, pim) {
354
+ return projection.map((item) => {
355
+ const alias = quoteIdentifier(item.alias);
356
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${alias}`;
357
+ return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;
358
+ }).join(", ");
359
+ }
360
+ function renderReturning(items, contract, pim) {
361
+ return items.map((item) => {
362
+ if (item.expr.kind === "column-ref") {
363
+ const rendered = renderColumn(item.expr);
364
+ return item.expr.column === item.alias ? rendered : `${rendered} AS ${quoteIdentifier(item.alias)}`;
365
+ }
366
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${quoteIdentifier(item.alias)}`;
367
+ return `${renderExpr(item.expr, contract, pim)} AS ${quoteIdentifier(item.alias)}`;
368
+ }).join(", ");
369
+ }
370
+ function renderDistinctPrefix(distinct, distinctOn, contract, pim) {
371
+ if (distinctOn && distinctOn.length > 0) return `DISTINCT ON (${distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(", ")}) `;
372
+ if (distinct) return "DISTINCT ";
373
+ return "";
374
+ }
375
+ function qualifyTableFromNamespaceCoordinate(table, contract) {
376
+ if (table instanceof PostgresTableSource && table.schema !== void 0) return `${quoteIdentifier(table.schema)}.${quoteIdentifier(table.name)}`;
377
+ if (table.namespaceId === void 0) return quoteIdentifier(table.name);
378
+ const namespace = contract.storage.namespaces[table.namespaceId];
379
+ if (namespace === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not present as a Postgres schema on the contract`);
380
+ const qualifyTable = namespace.qualifyTable;
381
+ if (qualifyTable === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not materialised as a Postgres schema on the contract`);
382
+ return qualifyTable.call(namespace, table.name);
383
+ }
384
+ function renderTableSource(source, contract) {
385
+ const qualified = qualifyTableFromNamespaceCoordinate(source, contract);
386
+ if (!source.alias) return qualified;
387
+ return `${qualified} AS ${quoteIdentifier(source.alias)}`;
388
+ }
389
+ function renderSource(source, contract, pim) {
390
+ const node = source;
391
+ switch (node.kind) {
392
+ case "table-source": return renderTableSource(node, contract);
393
+ case "derived-table-source": return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;
394
+ // v8 ignore next 4
395
+ default: throw new Error(`Unsupported source node kind: ${node.kind}`);
396
+ }
397
+ }
398
+ function assertScalarSubquery(query) {
399
+ if (query.projection.length !== 1) throw new Error("Subquery expressions must project exactly one column");
400
+ }
401
+ function renderSubqueryExpr(expr, contract, pim) {
402
+ assertScalarSubquery(expr.query);
403
+ return `(${renderSelect(expr.query, contract, pim)})`;
404
+ }
405
+ function renderWhere(expr, contract, pim) {
406
+ return renderExpr(expr, contract, pim);
407
+ }
408
+ function renderNullCheck(expr, contract, pim) {
409
+ const rendered = renderExpr(expr.expr, contract, pim);
410
+ const renderedExpr = isAtomicExpressionKind(expr.expr.kind) ? rendered : `(${rendered})`;
411
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
412
+ }
413
+ /**
414
+ * Atomic expression kinds whose rendered SQL is already self-delimited (a column reference, parameter, literal, function call, aggregate, etc.) and therefore does not need surrounding parentheses when used as the left operand of a postfix predicate like `IS NULL` or `IS NOT NULL`, or as either operand of a binary infix operator.
415
+ *
416
+ * Anything not in this set is treated as composite (binary, AND/OR/NOT, EXISTS, nested IS NULL, subqueries, operation templates) and gets wrapped to preserve grouping.
417
+ */
418
+ function isAtomicExpressionKind(kind) {
419
+ switch (kind) {
420
+ case "column-ref":
421
+ case "identifier-ref":
422
+ case "param-ref":
423
+ case "prepared-param-ref":
424
+ case "literal":
425
+ case "aggregate":
426
+ case "window-func":
427
+ case "json-object":
428
+ case "json-array-agg":
429
+ case "list": return true;
430
+ case "subquery":
431
+ case "operation":
432
+ case "binary":
433
+ case "and":
434
+ case "or":
435
+ case "exists":
436
+ case "null-check":
437
+ case "not":
438
+ case "raw-expr": return false;
439
+ }
440
+ }
441
+ function renderBinary(expr, contract, pim) {
442
+ if (expr.right.kind === "list" && expr.right.values.length === 0) {
443
+ if (expr.op === "in") return "FALSE";
444
+ if (expr.op === "notIn") return "TRUE";
445
+ }
446
+ const leftExpr = expr.left;
447
+ const left = renderExpr(leftExpr, contract, pim);
448
+ const leftRendered = leftExpr.kind === "operation" || leftExpr.kind === "subquery" ? `(${left})` : left;
449
+ const rightNode = expr.right;
450
+ let right;
451
+ switch (rightNode.kind) {
452
+ case "list":
453
+ right = renderListLiteral(rightNode, contract, pim);
454
+ break;
455
+ case "literal":
456
+ right = renderLiteral(rightNode);
457
+ break;
458
+ case "column-ref":
459
+ right = renderColumn(rightNode);
460
+ break;
461
+ case "param-ref":
462
+ case "prepared-param-ref":
463
+ right = renderParamRef(rightNode, pim);
464
+ break;
465
+ default:
466
+ right = renderExpr(rightNode, contract, pim);
467
+ break;
468
+ }
469
+ return `${leftRendered} ${{
470
+ eq: "=",
471
+ neq: "!=",
472
+ gt: ">",
473
+ lt: "<",
474
+ gte: ">=",
475
+ lte: "<=",
476
+ like: "LIKE",
477
+ in: "IN",
478
+ notIn: "NOT IN"
479
+ }[expr.op]} ${right}`;
480
+ }
481
+ function renderListLiteral(expr, contract, pim) {
482
+ if (expr.values.length === 0) return "(NULL)";
483
+ return `(${expr.values.map((v) => {
484
+ if (v.kind === "param-ref" || v.kind === "prepared-param-ref") return renderParamRef(v, pim);
485
+ if (v.kind === "literal") return renderLiteral(v);
486
+ return renderExpr(v, contract, pim);
487
+ }).join(", ")})`;
488
+ }
489
+ function renderColumn(ref) {
490
+ if (ref.table === "excluded") return `excluded.${quoteIdentifier(ref.column)}`;
491
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
492
+ }
493
+ function renderAggregateExpr(expr, contract, pim) {
494
+ const fn = expr.fn.toUpperCase();
495
+ if (!expr.expr) return `${fn}(*)`;
496
+ return `${fn}(${renderExpr(expr.expr, contract, pim)})`;
497
+ }
498
+ function renderWindowFuncExpr(expr, contract, pim) {
499
+ return `${expr.fn.toUpperCase()}(${expr.args.map((arg) => renderExpr(arg, contract, pim)).join(", ")}) OVER (${[expr.partitionBy && expr.partitionBy.length > 0 ? `PARTITION BY ${expr.partitionBy.map((e) => renderExpr(e, contract, pim)).join(", ")}` : "", expr.orderBy && expr.orderBy.length > 0 ? `ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : ""].filter((part) => part.length > 0).join(" ")})`;
500
+ }
501
+ function renderJsonObjectExpr(expr, contract, pim) {
502
+ return `json_build_object(${expr.entries.flatMap((entry) => {
503
+ const key = `'${escapeLiteral(entry.key)}'`;
504
+ if (entry.value.kind === "literal") return [key, renderLiteral(entry.value)];
505
+ return [key, renderExpr(entry.value, contract, pim)];
506
+ }).join(", ")})`;
507
+ }
508
+ function renderOrderByItems(items, contract, pim) {
509
+ return items.map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`).join(", ");
510
+ }
511
+ function renderJsonArrayAggExpr(expr, contract, pim) {
512
+ const aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : "";
513
+ const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;
514
+ if (expr.onEmpty === "emptyArray") return `coalesce(${aggregated}, json_build_array())`;
515
+ return aggregated;
516
+ }
517
+ function renderExpr(expr, contract, pim) {
518
+ const node = expr;
519
+ switch (node.kind) {
520
+ case "column-ref": return renderColumn(node);
521
+ case "identifier-ref": return quoteIdentifier(node.name);
522
+ case "operation": return renderOperation(node, contract, pim);
523
+ case "subquery": return renderSubqueryExpr(node, contract, pim);
524
+ case "aggregate": return renderAggregateExpr(node, contract, pim);
525
+ case "window-func": return renderWindowFuncExpr(node, contract, pim);
526
+ case "json-object": return renderJsonObjectExpr(node, contract, pim);
527
+ case "json-array-agg": return renderJsonArrayAggExpr(node, contract, pim);
528
+ case "binary": return renderBinary(node, contract, pim);
529
+ case "and":
530
+ if (node.exprs.length === 0) return "TRUE";
531
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" AND ")})`;
532
+ case "or":
533
+ if (node.exprs.length === 0) return "FALSE";
534
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" OR ")})`;
535
+ case "exists": return `${node.notExists ? "NOT " : ""}EXISTS (${renderSelect(node.subquery, contract, pim)})`;
536
+ case "null-check": return renderNullCheck(node, contract, pim);
537
+ case "not": return `NOT (${renderExpr(node.expr, contract, pim)})`;
538
+ case "param-ref":
539
+ case "prepared-param-ref": return renderParamRef(node, pim);
540
+ case "literal": return renderLiteral(node);
541
+ case "list": return renderListLiteral(node, contract, pim);
542
+ case "raw-expr": return renderRawExpr(node, contract, pim);
543
+ // v8 ignore next 4
544
+ default: throw new Error(`Unsupported expression node kind: ${node.kind}`);
545
+ }
546
+ }
547
+ function renderParamRef(ref, pim) {
548
+ const index = pim.indexMap.get(ref);
549
+ if (index === void 0) throw new Error("ParamRef not found in index map");
550
+ if (ref.kind === "prepared-param-ref") return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
551
+ if (ref.codec === void 0) throw runtimeError("RUNTIME.PARAM_REF_MISSING_CODEC", "Postgres renderer: ParamRef reached lowering without a bound CodecRef. Every column-bound ParamRef must carry a codec under the AST-bound codec contract. This usually indicates a builder path that constructed a ParamRef without threading the column codec.", {
552
+ paramIndex: index,
553
+ ...ifDefined("name", ref.name)
554
+ });
555
+ return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
556
+ }
557
+ function renderLiteral(expr) {
558
+ if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
559
+ if (typeof expr.value === "number" || typeof expr.value === "boolean") return String(expr.value);
560
+ if (typeof expr.value === "bigint") return String(expr.value);
561
+ if (expr.value === null) return "NULL";
562
+ if (expr.value === void 0) return "NULL";
563
+ if (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;
564
+ if (Array.isArray(expr.value)) return `ARRAY[${expr.value.map((v) => renderLiteral(new LiteralExpr(v))).join(", ")}]`;
565
+ const json = JSON.stringify(expr.value);
566
+ if (json === void 0) return "NULL";
567
+ return `'${escapeLiteral(json)}'`;
568
+ }
569
+ function renderOperation(expr, contract, pim) {
570
+ const self = renderExpr(expr.self, contract, pim);
571
+ const args = expr.args.map((arg) => {
572
+ return renderExpr(arg, contract, pim);
573
+ });
574
+ return expr.lowering.template.replace(/\{\{self\}\}|\{\{arg(\d+)\}\}/g, (token, argIndex) => {
575
+ if (token === "{{self}}") return self;
576
+ const arg = args[Number(argIndex)];
577
+ if (arg === void 0) throw new Error(`Operation lowering template for "${expr.method}" referenced missing argument {{arg${argIndex}}}; template has ${args.length} arg(s)`);
578
+ return arg;
579
+ });
580
+ }
581
+ function renderJoin(join, contract, pim) {
582
+ return `${join.joinType.toUpperCase()} JOIN ${join.lateral ? "LATERAL " : ""}${renderSource(join.source, contract, pim)} ON ${renderJoinOn(join.on, contract, pim)}`;
583
+ }
584
+ function renderJoinOn(on, contract, pim) {
585
+ if (on.kind === "eq-col-join-on") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;
586
+ return renderWhere(on, contract, pim);
587
+ }
588
+ function getInsertColumnOrder(rows, contract, tableRef) {
589
+ const tableName = tableRef.name;
590
+ const orderedColumns = [];
591
+ const seenColumns = /* @__PURE__ */ new Set();
592
+ for (const row of rows) for (const column of Object.keys(row)) {
593
+ if (seenColumns.has(column)) continue;
594
+ seenColumns.add(column);
595
+ orderedColumns.push(column);
596
+ }
597
+ if (orderedColumns.length > 0) return orderedColumns;
598
+ let table;
599
+ if (tableRef.namespaceId !== void 0) table = contract.storage.namespaces[tableRef.namespaceId]?.entries.table[tableName];
600
+ if (table === void 0) for (const ns of Object.values(contract.storage.namespaces)) {
601
+ const found = ns.entries.table[tableName];
602
+ if (found !== void 0) {
603
+ table = found;
604
+ break;
605
+ }
606
+ }
607
+ if (!table) throw new Error(`INSERT target table not found in contract storage: ${tableName}`);
608
+ return Object.keys(table.columns);
609
+ }
610
+ function renderInsertValue(value, contract, pim) {
611
+ if (!value || value.kind === "default-value") return "DEFAULT";
612
+ switch (value.kind) {
613
+ case "param-ref":
614
+ case "prepared-param-ref": return renderParamRef(value, pim);
615
+ case "column-ref": return renderColumn(value);
616
+ case "raw-expr": return renderExpr(value, contract, pim);
617
+ // v8 ignore next 4
618
+ default: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);
619
+ }
620
+ }
621
+ function renderInsert(ast, contract, pim) {
622
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
623
+ const rows = ast.rows;
624
+ if (rows.length === 0) throw new Error("INSERT requires at least one row");
625
+ const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);
626
+ return `${(() => {
627
+ if (!hasExplicitValues) {
628
+ if (rows.length === 1) return `INSERT INTO ${table} DEFAULT VALUES`;
629
+ const defaultColumns = getInsertColumnOrder(rows, contract, ast.table);
630
+ if (defaultColumns.length === 0) return `INSERT INTO ${table} VALUES ${rows.map(() => "()").join(", ")}`;
631
+ const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));
632
+ const defaultRow = `(${defaultColumns.map(() => "DEFAULT").join(", ")})`;
633
+ return `INSERT INTO ${table} (${quotedColumns.join(", ")}) VALUES ${rows.map(() => defaultRow).join(", ")}`;
634
+ }
635
+ const columnOrder = getInsertColumnOrder(rows, contract, ast.table);
636
+ const columns = columnOrder.map((column) => quoteIdentifier(column));
637
+ const values = rows.map((row) => {
638
+ return `(${columnOrder.map((column) => renderInsertValue(row[column], contract, pim)).join(", ")})`;
639
+ }).join(", ");
640
+ return `INSERT INTO ${table} (${columns.join(", ")}) VALUES ${values}`;
641
+ })()}${ast.onConflict ? (() => {
642
+ const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));
643
+ if (conflictColumns.length === 0) throw new Error("INSERT onConflict requires at least one conflict column");
644
+ const action = ast.onConflict.action;
645
+ switch (action.kind) {
646
+ case "do-nothing": return ` ON CONFLICT (${conflictColumns.join(", ")}) DO NOTHING`;
647
+ case "do-update-set": {
648
+ const updateEntries = Object.entries(action.set);
649
+ if (updateEntries.length === 0) throw new Error("INSERT onConflict do-update-set requires at least one assignment");
650
+ const updates = updateEntries.map(([colName, value]) => {
651
+ return `${quoteIdentifier(colName)} = ${renderExpr(value, contract, pim)}`;
652
+ });
653
+ return ` ON CONFLICT (${conflictColumns.join(", ")}) DO UPDATE SET ${updates.join(", ")}`;
654
+ }
655
+ // v8 ignore next 4
656
+ default: throw new Error(`Unsupported onConflict action: ${action.kind}`);
657
+ }
658
+ })() : ""}${ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : ""}`;
659
+ }
660
+ function renderUpdate(ast, contract, pim) {
661
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
662
+ const setEntries = Object.entries(ast.set);
663
+ if (setEntries.length === 0) throw new Error("UPDATE requires at least one SET assignment");
664
+ const setClauses = setEntries.map(([col, val]) => {
665
+ return `${quoteIdentifier(col)} = ${renderExpr(val, contract, pim)}`;
666
+ });
667
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : "";
668
+ const returningClause = ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : "";
669
+ return `UPDATE ${table} SET ${setClauses.join(", ")}${whereClause}${returningClause}`;
670
+ }
671
+ function renderDelete(ast, contract, pim) {
672
+ return `DELETE FROM ${qualifyTableFromNamespaceCoordinate(ast.table, contract)}${ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : ""}${ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : ""}`;
673
+ }
674
+ function renderRawSql(ast, contract, pim) {
675
+ const out = [];
676
+ for (let i = 0; i < ast.fragments.length; i++) {
677
+ out.push(ast.fragments[i] ?? "");
678
+ if (i < ast.args.length) {
679
+ const arg = ast.args[i];
680
+ if (arg !== void 0) out.push(renderExpr(arg, contract, pim));
681
+ }
682
+ }
683
+ return out.join("");
684
+ }
685
+ function renderRawExpr(node, contract, pim) {
686
+ return node.parts.map((part) => typeof part === "string" ? part : renderExpr(part, contract, pim)).join("");
687
+ }
688
+ //#endregion
689
+ //#region src/core/control-adapter.ts
690
+ const POSTGRES_MARKER_TABLE = "prisma_contract.marker";
691
+ const POSTGRES_LEDGER_TABLE = "prisma_contract.ledger";
692
+ /**
693
+ * Postgres control plane adapter for control-plane operations like introspection.
694
+ * Provides target-specific implementations for control-plane domain actions.
695
+ */
696
+ var PostgresControlAdapter = class {
697
+ familyId = "sql";
698
+ targetId = "postgres";
699
+ codecLookup;
700
+ /**
701
+ * @param codecLookup - Codec lookup used by the SQL renderer to resolve
702
+ * per-codec metadata at lower-time. Defaults to a Postgres-builtins-only
703
+ * lookup when omitted. Stack-aware callers
704
+ * (`SqlControlAdapterDescriptor.create(stack)`) supply
705
+ * `stack.codecLookup` so extension codecs are visible to the renderer.
706
+ */
707
+ constructor(codecLookup) {
708
+ this.codecLookup = codecLookup ?? createPostgresBuiltinCodecLookup();
709
+ }
710
+ /**
711
+ * Target-specific normalizer for raw Postgres default expressions.
712
+ * Used by schema verification to normalize raw defaults before comparison.
713
+ */
714
+ normalizeDefault = parsePostgresDefault;
715
+ /**
716
+ * Target-specific normalizer for Postgres schema native type names.
717
+ * Used by schema verification to normalize introspected type names
718
+ * before comparison with contract native types.
719
+ */
720
+ normalizeNativeType = normalizeSchemaNativeType;
721
+ /**
722
+ * Bridges native `PostgresEnumStorageEntry` IR walks against the Postgres
723
+ * introspection shape (`schema.annotations.pg.storageTypes`). Lets
724
+ * the family-level schema verifier walk enum types without reaching
725
+ * into target-specific annotation layouts itself.
726
+ */
727
+ resolveExistingEnumValues = (schema, enumType, namespaceId) => {
728
+ return readExistingEnumValues(schema, namespaceId === UNBOUND_NAMESPACE_ID ? readPostgresSchemaIrAnnotations(schema).schema ?? "public" : namespaceId, enumType.nativeType);
729
+ };
730
+ resolveExistingEnumValuesForContract = (contract) => createResolveExistingEnumValues(contract.storage);
731
+ bootstrapControlTableQueries() {
732
+ return buildControlTableBootstrapQueries();
733
+ }
734
+ bootstrapSignMarkerQueries() {
735
+ return buildSignMarkerBootstrapQueries();
736
+ }
737
+ /**
738
+ * Lower a SQL query AST into a Postgres-flavored `{ sql, params }` payload.
739
+ *
740
+ * Delegates to the shared `renderLoweredSql` renderer so the control adapter
741
+ * emits byte-identical SQL to `PostgresAdapterImpl.lower()` for the same AST
742
+ * and contract. Used at migration plan/emit time (e.g. by `dataTransform`)
743
+ * without instantiating the runtime adapter.
744
+ */
745
+ lower(ast, context) {
746
+ if (isDdlNode(ast)) return renderLoweredDdl(ast);
747
+ return renderLoweredSql(ast, context.contract, this.codecLookup);
748
+ }
749
+ /**
750
+ * Reads the contract marker from `prisma_contract.marker`. Probes
751
+ * `information_schema.tables` first so a fresh database (where the
752
+ * `prisma_contract` schema doesn't yet exist) returns `null` instead of a
753
+ * "relation does not exist" error — some Postgres wire-protocol clients
754
+ * (e.g. PGlite's TCP proxy) don't fully recover from extended-protocol
755
+ * parse errors, so we probe before reading.
756
+ */
757
+ async readMarker(driver, space) {
758
+ const result = await this.readMarkerDiscriminated(driver, space);
759
+ return result.kind === "present" ? result.record : null;
760
+ }
761
+ async readMarkerDiscriminated(driver, space) {
762
+ return withMarkerReadErrorHandling(() => this.readMarkerResult(driver, space), {
763
+ space,
764
+ markerLocation: POSTGRES_MARKER_TABLE
765
+ });
766
+ }
767
+ /**
768
+ * Reads every row from `prisma_contract.marker` and returns them keyed
769
+ * by `space`. Mirrors the existence probe in {@link readMarker}: a
770
+ * fresh database without the `prisma_contract` schema returns an empty
771
+ * map rather than raising "relation does not exist".
772
+ */
773
+ async readAllMarkers(driver) {
774
+ return withMarkerReadErrorHandling(() => this.readAllMarkersResult(driver), {
775
+ space: APP_SPACE_ID,
776
+ markerLocation: POSTGRES_MARKER_TABLE
777
+ });
778
+ }
779
+ async readAllMarkersResult(driver) {
780
+ const lower = (query) => this.lower(query, { contract: void 0 });
781
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("marker"))).build())).length === 0) return /* @__PURE__ */ new Map();
782
+ await this.assertMarkerTableHasSpaceColumn(driver, APP_SPACE_ID);
783
+ const rows = blindCast(await execute(lower, driver, marker.select(marker.space, marker.core_hash, marker.profile_hash, marker.contract_json, marker.canonical_version, marker.updated_at, marker.app_tag, marker.meta, marker.invariants).build()));
784
+ const out = /* @__PURE__ */ new Map();
785
+ for (const row of rows) out.set(row.space, parseMarkerRowSafely(row, parseContractMarkerRow, {
786
+ space: row.space,
787
+ markerLocation: POSTGRES_MARKER_TABLE
788
+ }));
789
+ return out;
790
+ }
791
+ /**
792
+ * Reads per-migration ledger rows from `prisma_contract.ledger` in apply
793
+ * order. Probes `information_schema.tables` first so a fresh database
794
+ * without the ledger table returns `[]` instead of raising "relation does
795
+ * not exist".
796
+ */
797
+ async readLedger(driver, space) {
798
+ return withMarkerReadErrorHandling(() => this.readLedgerResult(driver, space), {
799
+ space: space ?? "*",
800
+ markerLocation: POSTGRES_LEDGER_TABLE
801
+ });
802
+ }
803
+ async readLedgerResult(driver, space) {
804
+ const lower = (query) => this.lower(query, { contract: void 0 });
805
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("ledger"))).build())).length === 0) return [];
806
+ const base = ledgerReadShape.select(ledgerReadShape.space, ledgerReadShape.migration_name, ledgerReadShape.migration_hash, ledgerReadShape.origin_core_hash, ledgerReadShape.destination_core_hash, ledgerReadShape.operations, ledgerReadShape.created_at);
807
+ return blindCast(await execute(lower, driver, (space !== void 0 ? base.where(ledgerReadShape.space.eq(space)) : base).orderBy(ledgerReadShape.id).build())).map((row) => {
808
+ const appliedAt = row.created_at instanceof Date ? row.created_at : new Date(row.created_at);
809
+ return {
810
+ space: row.space,
811
+ migrationName: row.migration_name,
812
+ migrationHash: row.migration_hash,
813
+ from: ledgerOriginFromStored(row.origin_core_hash),
814
+ to: row.destination_core_hash,
815
+ appliedAt,
816
+ operationCount: Array.isArray(row.operations) ? row.operations.length : 0
817
+ };
818
+ });
819
+ }
820
+ /**
821
+ * Stamps the initial marker row for `space` via the shared contract-free DML
822
+ * builder, lowered through {@link lower} and executed on the driver. See the
823
+ * `SqlControlAdapter.initMarker` contract.
824
+ */
825
+ async insertMarker(driver, space, destination) {
826
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.insert({
827
+ space,
828
+ core_hash: destination.storageHash,
829
+ profile_hash: destination.profileHash,
830
+ contract_json: null,
831
+ canonical_version: null,
832
+ updated_at: NOW,
833
+ app_tag: null,
834
+ meta: {},
835
+ invariants: destination.invariants ?? []
836
+ }).build());
837
+ }
838
+ async initMarker(driver, space, destination) {
839
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.upsert({
840
+ space,
841
+ core_hash: destination.storageHash,
842
+ profile_hash: destination.profileHash,
843
+ contract_json: null,
844
+ canonical_version: null,
845
+ updated_at: NOW,
846
+ app_tag: null,
847
+ meta: {},
848
+ invariants: destination.invariants ?? []
849
+ }).onConflict(marker.space).doUpdate((excluded) => ({
850
+ core_hash: excluded.core_hash,
851
+ profile_hash: excluded.profile_hash,
852
+ contract_json: excluded.contract_json,
853
+ canonical_version: excluded.canonical_version,
854
+ updated_at: NOW,
855
+ app_tag: excluded.app_tag,
856
+ meta: excluded.meta,
857
+ invariants: excluded.invariants
858
+ })).build());
859
+ }
860
+ /**
861
+ * Compare-and-swap advance of the marker row for `space`. See the
862
+ * `SqlControlAdapter.updateMarker` contract.
863
+ */
864
+ async updateMarker(driver, space, expectedFrom, destination) {
865
+ const currentInvariants = destination.invariants === void 0 ? [] : (await this.readMarker(driver, space))?.invariants ?? [];
866
+ const mergedInvariants = destination.invariants === void 0 ? void 0 : mergeInvariants(currentInvariants, destination.invariants);
867
+ return (await execute((q) => this.lower(q, { contract: void 0 }), driver, marker.update().set({
868
+ core_hash: destination.storageHash,
869
+ profile_hash: destination.profileHash,
870
+ updated_at: NOW,
871
+ ...mergedInvariants !== void 0 ? { invariants: mergedInvariants } : {}
872
+ }).where(marker.space.eq(space).and(marker.core_hash.eq(expectedFrom))).returning(marker.space).build())).length > 0;
873
+ }
874
+ /**
875
+ * Appends a ledger entry for `space`. See the
876
+ * `SqlControlAdapter.writeLedgerEntry` contract.
877
+ */
878
+ async writeLedgerEntry(driver, space, entry) {
879
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, ledger.insert({
880
+ space,
881
+ migration_name: entry.migrationName,
882
+ migration_hash: entry.migrationHash,
883
+ origin_core_hash: entry.from,
884
+ destination_core_hash: entry.to,
885
+ operations: entry.operations
886
+ }).build());
887
+ }
888
+ async assertMarkerTableHasSpaceColumn(driver, space) {
889
+ const rows = (await driver.query(`select column_name
890
+ from information_schema.columns
891
+ where table_schema = 'prisma_contract'
892
+ and table_name = 'marker'`)).rows;
893
+ if (rows.length === 0) return;
894
+ if (!rows.every((row) => typeof row.column_name === "string")) return;
895
+ if (rows.some((row) => row.column_name === "space")) return;
896
+ rethrowMarkerReadError(/* @__PURE__ */ new Error("column \"space\" does not exist"), {
897
+ space,
898
+ markerLocation: POSTGRES_MARKER_TABLE
899
+ });
900
+ }
901
+ async readMarkerResult(driver, space) {
902
+ const lower = (query) => this.lower(query, { contract: void 0 });
903
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("marker"))).build())).length === 0) return { kind: "no-table" };
904
+ await this.assertMarkerTableHasSpaceColumn(driver, space);
905
+ const row = (await execute(lower, driver, marker.select(marker.core_hash, marker.profile_hash, marker.contract_json, marker.canonical_version, marker.updated_at, marker.app_tag, marker.meta, marker.invariants).where(marker.space.eq(space)).build()))[0];
906
+ if (!row) return { kind: "absent" };
907
+ return {
908
+ kind: "present",
909
+ record: parseContractMarkerRow(row)
910
+ };
911
+ }
912
+ /**
913
+ * Introspects a Postgres database schema and returns a raw SqlSchemaIR.
914
+ *
915
+ * This is a pure schema discovery operation that queries the Postgres catalog
916
+ * and returns the schema structure without type mapping or contract enrichment.
917
+ * Type mapping and enrichment are handled separately by enrichment helpers.
918
+ *
919
+ * When `contract` is provided and its storage declares more than one
920
+ * namespace (or any explicit bound namespace), the adapter walks every
921
+ * declared namespace and merges the per-schema introspection results
922
+ * into a single `SqlSchemaIR`. `UNBOUND_NAMESPACE_ID` resolves to the
923
+ * connection's `current_schema()` so late-bound tables follow the
924
+ * runtime `search_path`. When no contract is passed, the adapter falls
925
+ * back to introspecting the single `schema` argument (defaulting to
926
+ * `'public'`).
927
+ *
928
+ * Uses batched queries to minimize database round trips (6 queries per
929
+ * schema walked).
930
+ *
931
+ * @param driver - SqlControlDriverInstance<'postgres'> instance for executing queries
932
+ * @param contract - Optional contract for contract-guided introspection (multi-namespace walk, filtering)
933
+ * @param schema - Schema name to introspect when no contract is provided (defaults to 'public')
934
+ * @returns Promise resolving to SqlSchemaIR representing the live database schema
935
+ */
936
+ async introspect(driver, contract, schema = "public") {
937
+ const declaredNamespaces = extractContractNamespaceIds(contract);
938
+ const ir = declaredNamespaces.length > 0 ? await this.introspectNamespaces(driver, declaredNamespaces) : await this.introspectSchema(driver, schema);
939
+ const existingSchemas = await this.listExistingSchemas(driver);
940
+ const annotations = ir.annotations ?? {};
941
+ const pg = annotations.pg ?? {};
942
+ return {
943
+ ...ir,
944
+ annotations: {
945
+ ...annotations,
946
+ pg: {
947
+ ...pg,
948
+ existingSchemas
949
+ }
950
+ }
951
+ };
952
+ }
953
+ /**
954
+ * Lists every non-system schema present in the connected database.
955
+ * The introspection consumer (`verifyPostgresNamespacePresence`)
956
+ * treats the result as the authoritative ground truth — declared
957
+ * namespaces whose `ddlSchemaName` is missing from this list become
958
+ * `missing_schema` issues, and the planner emits the matching
959
+ * `CREATE SCHEMA` before table DDL.
960
+ */
961
+ async listExistingSchemas(driver) {
962
+ return (await driver.query(`SELECT nspname
963
+ FROM pg_catalog.pg_namespace
964
+ WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
965
+ AND nspname NOT LIKE 'pg_temp_%'
966
+ AND nspname NOT LIKE 'pg_toast_temp_%'
967
+ ORDER BY nspname`)).rows.map((row) => row.nspname);
968
+ }
969
+ /**
970
+ * Walks every declared namespace, resolving `UNBOUND_NAMESPACE_ID` to
971
+ * the connection's `current_schema()`, and merges the per-schema results
972
+ * into a single `SqlSchemaIR`. The merged `tables` map is flat (keyed by
973
+ * table name) so callers that look up by `tableName` see every contract
974
+ * table regardless of which namespace it lives in.
975
+ */
976
+ async introspectNamespaces(driver, namespaceIds) {
977
+ const resolvedSchemas = await Promise.all(namespaceIds.map(async (id) => {
978
+ if (id === UNBOUND_NAMESPACE_ID) {
979
+ const { rows } = await driver.query("SELECT current_schema() AS current_schema");
980
+ return rows[0]?.current_schema ?? "public";
981
+ }
982
+ return id;
983
+ }));
984
+ const uniqueSchemas = Array.from(new Set(resolvedSchemas));
985
+ const perSchema = await Promise.all(uniqueSchemas.map((s) => this.introspectSchema(driver, s)));
986
+ const mergedTables = {};
987
+ for (const ir of perSchema) for (const [tableName, table] of Object.entries(ir.tables)) mergedTables[tableName] = table;
988
+ const mergedStorageTypes = {};
989
+ for (let i = 0; i < perSchema.length; i++) {
990
+ const ir = perSchema[i];
991
+ const pg = blindCast(ir?.annotations?.["pg"])?.storageTypes;
992
+ if (!pg) continue;
993
+ for (const [key, value] of Object.entries(pg)) mergedStorageTypes[key] = value;
994
+ }
995
+ const firstAnnotations = perSchema[0]?.annotations;
996
+ const firstPg = blindCast(firstAnnotations?.["pg"]) ?? {};
997
+ return {
998
+ tables: mergedTables,
999
+ ...ifDefined("annotations", {
1000
+ ...firstAnnotations,
1001
+ pg: {
1002
+ ...firstPg,
1003
+ ...ifDefined("storageTypes", Object.keys(mergedStorageTypes).length > 0 ? mergedStorageTypes : void 0)
1004
+ }
1005
+ })
1006
+ };
1007
+ }
1008
+ /**
1009
+ * Introspects a single Postgres schema and returns a raw SqlSchemaIR
1010
+ * containing only the tables in that schema. Used by `introspect` as
1011
+ * the per-namespace walk.
1012
+ */
1013
+ async introspectSchema(driver, schema) {
1014
+ const [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult] = await Promise.all([
1015
+ driver.query(`SELECT table_name
1016
+ FROM information_schema.tables
1017
+ WHERE table_schema = $1
1018
+ AND table_type = 'BASE TABLE'
1019
+ ORDER BY table_name`, [schema]),
1020
+ driver.query(`SELECT
1021
+ c.table_name,
1022
+ column_name,
1023
+ data_type,
1024
+ udt_name,
1025
+ is_nullable,
1026
+ character_maximum_length,
1027
+ numeric_precision,
1028
+ numeric_scale,
1029
+ column_default,
1030
+ format_type(a.atttypid, a.atttypmod) AS formatted_type
1031
+ FROM information_schema.columns c
1032
+ JOIN pg_catalog.pg_class cl
1033
+ ON cl.relname = c.table_name
1034
+ JOIN pg_catalog.pg_namespace ns
1035
+ ON ns.nspname = c.table_schema
1036
+ AND ns.oid = cl.relnamespace
1037
+ JOIN pg_catalog.pg_attribute a
1038
+ ON a.attrelid = cl.oid
1039
+ AND a.attname = c.column_name
1040
+ AND a.attnum > 0
1041
+ AND NOT a.attisdropped
1042
+ WHERE c.table_schema = $1
1043
+ ORDER BY c.table_name, c.ordinal_position`, [schema]),
1044
+ driver.query(`SELECT
1045
+ tc.table_name,
1046
+ tc.constraint_name,
1047
+ kcu.column_name,
1048
+ kcu.ordinal_position
1049
+ FROM information_schema.table_constraints tc
1050
+ JOIN information_schema.key_column_usage kcu
1051
+ ON tc.constraint_name = kcu.constraint_name
1052
+ AND tc.table_schema = kcu.table_schema
1053
+ AND tc.table_name = kcu.table_name
1054
+ WHERE tc.table_schema = $1
1055
+ AND tc.constraint_type = 'PRIMARY KEY'
1056
+ ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),
1057
+ driver.query(`SELECT
1058
+ tc.table_name,
1059
+ tc.constraint_name,
1060
+ kcu.column_name,
1061
+ kcu.ordinal_position,
1062
+ ref_ns.nspname AS referenced_table_schema,
1063
+ ref_cl.relname AS referenced_table_name,
1064
+ ref_att.attname AS referenced_column_name,
1065
+ rc.delete_rule,
1066
+ rc.update_rule
1067
+ FROM information_schema.table_constraints tc
1068
+ JOIN information_schema.key_column_usage kcu
1069
+ ON tc.constraint_name = kcu.constraint_name
1070
+ AND tc.table_schema = kcu.table_schema
1071
+ AND tc.table_name = kcu.table_name
1072
+ JOIN pg_catalog.pg_constraint pgc
1073
+ ON pgc.conname = tc.constraint_name
1074
+ AND pgc.connamespace = (
1075
+ SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema
1076
+ )
1077
+ JOIN pg_catalog.pg_class ref_cl
1078
+ ON ref_cl.oid = pgc.confrelid
1079
+ JOIN pg_catalog.pg_namespace ref_ns
1080
+ ON ref_ns.oid = ref_cl.relnamespace
1081
+ JOIN pg_catalog.pg_attribute ref_att
1082
+ ON ref_att.attrelid = pgc.confrelid
1083
+ AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]
1084
+ JOIN information_schema.referential_constraints rc
1085
+ ON rc.constraint_name = tc.constraint_name
1086
+ AND rc.constraint_schema = tc.table_schema
1087
+ WHERE tc.table_schema = $1
1088
+ AND tc.constraint_type = 'FOREIGN KEY'
1089
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1090
+ driver.query(`SELECT
1091
+ tc.table_name,
1092
+ tc.constraint_name,
1093
+ kcu.column_name,
1094
+ kcu.ordinal_position
1095
+ FROM information_schema.table_constraints tc
1096
+ JOIN information_schema.key_column_usage kcu
1097
+ ON tc.constraint_name = kcu.constraint_name
1098
+ AND tc.table_schema = kcu.table_schema
1099
+ AND tc.table_name = kcu.table_name
1100
+ WHERE tc.table_schema = $1
1101
+ AND tc.constraint_type = 'UNIQUE'
1102
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1103
+ driver.query(`SELECT
1104
+ i.tablename,
1105
+ i.indexname,
1106
+ ix.indisunique,
1107
+ a.attname,
1108
+ k.ord AS index_position,
1109
+ am.amname,
1110
+ ic.reloptions
1111
+ FROM pg_indexes i
1112
+ JOIN pg_class ic ON ic.relname = i.indexname
1113
+ JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1
1114
+ JOIN pg_index ix ON ix.indexrelid = ic.oid
1115
+ JOIN pg_am am ON am.oid = ic.relam
1116
+ JOIN pg_class t ON t.oid = ix.indrelid
1117
+ JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1
1118
+ JOIN LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY AS k(attnum, ord) ON true
1119
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND a.attnum > 0
1120
+ WHERE i.schemaname = $1
1121
+ AND NOT EXISTS (
1122
+ SELECT 1
1123
+ FROM information_schema.table_constraints tc
1124
+ WHERE tc.table_schema = $1
1125
+ AND tc.table_name = i.tablename
1126
+ AND tc.constraint_name = i.indexname
1127
+ )
1128
+ ORDER BY i.tablename, i.indexname, k.ord`, [schema])
1129
+ ]);
1130
+ const columnsByTable = groupBy(columnsResult.rows, "table_name");
1131
+ const pksByTable = groupBy(pkResult.rows, "table_name");
1132
+ const fksByTable = groupBy(fkResult.rows, "table_name");
1133
+ const uniquesByTable = groupBy(uniqueResult.rows, "table_name");
1134
+ const indexesByTable = groupBy(indexResult.rows, "tablename");
1135
+ const pkConstraintsByTable = /* @__PURE__ */ new Map();
1136
+ for (const row of pkResult.rows) {
1137
+ let constraints = pkConstraintsByTable.get(row.table_name);
1138
+ if (!constraints) {
1139
+ constraints = /* @__PURE__ */ new Set();
1140
+ pkConstraintsByTable.set(row.table_name, constraints);
1141
+ }
1142
+ constraints.add(row.constraint_name);
1143
+ }
1144
+ const tables = {};
1145
+ for (const tableRow of tablesResult.rows) {
1146
+ const tableName = tableRow.table_name;
1147
+ const columns = {};
1148
+ for (const colRow of columnsByTable.get(tableName) ?? []) {
1149
+ let nativeType = colRow.udt_name;
1150
+ const formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;
1151
+ if (formattedType) nativeType = formattedType;
1152
+ else if (colRow.data_type === "character varying" || colRow.data_type === "character") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;
1153
+ else nativeType = colRow.data_type;
1154
+ else if (colRow.data_type === "numeric" || colRow.data_type === "decimal") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;
1155
+ else if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;
1156
+ else nativeType = colRow.data_type;
1157
+ else nativeType = colRow.udt_name || colRow.data_type;
1158
+ columns[colRow.column_name] = {
1159
+ name: colRow.column_name,
1160
+ nativeType,
1161
+ nullable: colRow.is_nullable === "YES",
1162
+ ...ifDefined("default", colRow.column_default ?? void 0)
1163
+ };
1164
+ }
1165
+ const pkRows = [...pksByTable.get(tableName) ?? []];
1166
+ const primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);
1167
+ const primaryKey = primaryKeyColumns.length > 0 ? {
1168
+ columns: primaryKeyColumns,
1169
+ ...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}
1170
+ } : void 0;
1171
+ const foreignKeysMap = /* @__PURE__ */ new Map();
1172
+ for (const fkRow of fksByTable.get(tableName) ?? []) {
1173
+ const existing = foreignKeysMap.get(fkRow.constraint_name);
1174
+ if (existing) {
1175
+ existing.columns.push(fkRow.column_name);
1176
+ existing.referencedColumns.push(fkRow.referenced_column_name);
1177
+ } else foreignKeysMap.set(fkRow.constraint_name, {
1178
+ columns: [fkRow.column_name],
1179
+ referencedTable: fkRow.referenced_table_name,
1180
+ referencedSchema: fkRow.referenced_table_schema,
1181
+ referencedColumns: [fkRow.referenced_column_name],
1182
+ name: fkRow.constraint_name,
1183
+ deleteRule: fkRow.delete_rule,
1184
+ updateRule: fkRow.update_rule
1185
+ });
1186
+ }
1187
+ const foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({
1188
+ columns: Object.freeze([...fk.columns]),
1189
+ referencedTable: fk.referencedTable,
1190
+ referencedSchema: fk.referencedSchema,
1191
+ referencedColumns: Object.freeze([...fk.referencedColumns]),
1192
+ name: fk.name,
1193
+ ...ifDefined("onDelete", mapReferentialAction(fk.deleteRule)),
1194
+ ...ifDefined("onUpdate", mapReferentialAction(fk.updateRule))
1195
+ }));
1196
+ const pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();
1197
+ const uniquesMap = /* @__PURE__ */ new Map();
1198
+ for (const uniqueRow of uniquesByTable.get(tableName) ?? []) {
1199
+ if (pkConstraints.has(uniqueRow.constraint_name)) continue;
1200
+ const existing = uniquesMap.get(uniqueRow.constraint_name);
1201
+ if (existing) existing.columns.push(uniqueRow.column_name);
1202
+ else uniquesMap.set(uniqueRow.constraint_name, {
1203
+ columns: [uniqueRow.column_name],
1204
+ name: uniqueRow.constraint_name
1205
+ });
1206
+ }
1207
+ const uniques = Array.from(uniquesMap.values()).map((uq) => ({
1208
+ columns: Object.freeze([...uq.columns]),
1209
+ name: uq.name
1210
+ }));
1211
+ const indexesMap = /* @__PURE__ */ new Map();
1212
+ for (const idxRow of indexesByTable.get(tableName) ?? []) {
1213
+ if (!idxRow.attname) continue;
1214
+ const existing = indexesMap.get(idxRow.indexname);
1215
+ if (existing) existing.columns.push(idxRow.attname);
1216
+ else {
1217
+ const indexType = idxRow.amname && idxRow.amname !== "btree" ? idxRow.amname : void 0;
1218
+ const indexOptions = parsePgReloptions(idxRow.reloptions, idxRow.indexname);
1219
+ indexesMap.set(idxRow.indexname, {
1220
+ columns: [idxRow.attname],
1221
+ name: idxRow.indexname,
1222
+ unique: idxRow.indisunique,
1223
+ type: indexType,
1224
+ options: indexOptions
1225
+ });
1226
+ }
1227
+ }
1228
+ const indexes = Array.from(indexesMap.values()).map((idx) => ({
1229
+ columns: Object.freeze([...idx.columns]),
1230
+ name: idx.name,
1231
+ unique: idx.unique,
1232
+ ...idx.type !== void 0 && { type: idx.type },
1233
+ ...idx.options !== void 0 && { options: idx.options }
1234
+ }));
1235
+ tables[tableName] = {
1236
+ name: tableName,
1237
+ columns,
1238
+ ...ifDefined("primaryKey", primaryKey),
1239
+ foreignKeys,
1240
+ uniques,
1241
+ indexes
1242
+ };
1243
+ }
1244
+ const rawStorageTypes = await introspectPostgresEnumTypes({
1245
+ driver,
1246
+ schemaName: schema
1247
+ });
1248
+ const storageTypes = {};
1249
+ for (const [typeName, annotation] of Object.entries(rawStorageTypes)) storageTypes[enumStorageCompoundKey(schema, typeName)] = annotation;
1250
+ return {
1251
+ tables,
1252
+ annotations: { pg: {
1253
+ schema,
1254
+ version: await this.getPostgresVersion(driver),
1255
+ ...ifDefined("storageTypes", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)
1256
+ } }
1257
+ };
1258
+ }
1259
+ /**
1260
+ * Gets the Postgres version from the database.
1261
+ */
1262
+ async getPostgresVersion(driver) {
1263
+ return ((await driver.query("SELECT version() AS version", [])).rows[0]?.version ?? "").match(/PostgreSQL (\d+\.\d+)/)?.[1] ?? "unknown";
1264
+ }
1265
+ };
1266
+ /**
1267
+ * Extracts the namespace coordinate ids declared on a contract's storage,
1268
+ * or returns an empty array when no contract (or no storage / namespaces)
1269
+ * is present. Used by `PostgresControlAdapter.introspect` to decide
1270
+ * between the multi-namespace walk and the single-schema fallback.
1271
+ */
1272
+ function extractContractNamespaceIds(contract) {
1273
+ if (contract === null || typeof contract !== "object") return [];
1274
+ const storage = contract.storage;
1275
+ if (storage === null || typeof storage !== "object") return [];
1276
+ const namespaces = storage.namespaces;
1277
+ if (namespaces === null || typeof namespaces !== "object") return [];
1278
+ return Object.keys(namespaces);
1279
+ }
1280
+ function normalizeFormattedType(formattedType, dataType, udtName) {
1281
+ if (formattedType === "integer") return "int4";
1282
+ if (formattedType === "smallint") return "int2";
1283
+ if (formattedType === "bigint") return "int8";
1284
+ if (formattedType === "real") return "float4";
1285
+ if (formattedType === "double precision") return "float8";
1286
+ if (formattedType === "boolean") return "bool";
1287
+ if (formattedType.startsWith("varchar")) return formattedType.replace("varchar", "character varying");
1288
+ if (formattedType.startsWith("bpchar")) return formattedType.replace("bpchar", "character");
1289
+ if (formattedType.startsWith("varbit")) return formattedType.replace("varbit", "bit varying");
1290
+ if (dataType === "timestamp with time zone" || udtName === "timestamptz") return formattedType.replace("timestamp", "timestamptz").replace(" with time zone", "").trim();
1291
+ if (dataType === "timestamp without time zone" || udtName === "timestamp") return formattedType.replace(" without time zone", "").trim();
1292
+ if (dataType === "time with time zone" || udtName === "timetz") return formattedType.replace("time", "timetz").replace(" with time zone", "").trim();
1293
+ if (dataType === "time without time zone" || udtName === "time") return formattedType.replace(" without time zone", "").trim();
1294
+ if (formattedType.startsWith("\"") && formattedType.endsWith("\"")) return formattedType.slice(1, -1);
1295
+ return formattedType;
1296
+ }
1297
+ const PG_REFERENTIAL_ACTION_MAP = {
1298
+ "NO ACTION": "noAction",
1299
+ RESTRICT: "restrict",
1300
+ CASCADE: "cascade",
1301
+ "SET NULL": "setNull",
1302
+ "SET DEFAULT": "setDefault"
1303
+ };
1304
+ /**
1305
+ * Maps a Postgres referential action rule to the canonical SqlReferentialAction.
1306
+ * Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.
1307
+ * Throws for unrecognized rules to prevent silent data loss.
1308
+ */
1309
+ function mapReferentialAction(rule) {
1310
+ const mapped = PG_REFERENTIAL_ACTION_MAP[rule];
1311
+ if (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
1312
+ if (mapped === "noAction") return void 0;
1313
+ return mapped;
1314
+ }
1315
+ /**
1316
+ * Groups an array of objects by a specified key.
1317
+ * Returns a Map for O(1) lookup by group key.
1318
+ */
1319
+ /**
1320
+ * Parses a `pg_class.reloptions` array into a `Record<string, string>`.
1321
+ *
1322
+ * Postgres returns reloptions as a `text[]` whose entries are `key=value`
1323
+ * strings; the value side is always a string regardless of the underlying
1324
+ * scalar type. The verifier compares contract options to introspected
1325
+ * options after coercing both sides to strings, so keeping the raw text
1326
+ * here is correct.
1327
+ *
1328
+ * Returns `undefined` when the input is null/empty (no WITH clause).
1329
+ */
1330
+ function parsePgReloptions(reloptions, indexName) {
1331
+ if (!reloptions || reloptions.length === 0) return;
1332
+ const result = {};
1333
+ for (const entry of reloptions) {
1334
+ const eq = entry.indexOf("=");
1335
+ if (eq === -1) throw new Error(`Postgres introspection: malformed reloption entry "${entry}" on index "${indexName}" (expected "key=value")`);
1336
+ const key = entry.slice(0, eq);
1337
+ result[key] = entry.slice(eq + 1);
1338
+ }
1339
+ return Object.keys(result).length > 0 ? result : void 0;
1340
+ }
1341
+ function groupBy(items, key) {
1342
+ const map = /* @__PURE__ */ new Map();
1343
+ for (const item of items) {
1344
+ const groupKey = item[key];
1345
+ let group = map.get(groupKey);
1346
+ if (!group) {
1347
+ group = [];
1348
+ map.set(groupKey, group);
1349
+ }
1350
+ group.push(item);
1351
+ }
1352
+ return map;
1353
+ }
1354
+ //#endregion
1355
+ export { createPostgresBuiltinCodecLookup as i, renderLoweredSql as n, renderLoweredDdl as r, PostgresControlAdapter as t };
1356
+
1357
+ //# sourceMappingURL=control-adapter-1Yv2bsSN.mjs.map