@prisma/orm-sqlite 8.0.0-rc.18-dev.20 → 8.0.0-rc.18-dev.22

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 @@
1
+ export * from "@prisma/orm-framework/contract/validate-once";
@@ -0,0 +1,2 @@
1
+ export * from "@prisma/orm-framework/contract/validate-once";
2
+ export {};
@@ -1,4 +1,4 @@
1
- import { a as SqliteOptionsWithContractJson, c as sqlite, i as SqliteOptionsWithContract, n as SqliteOptions, r as SqliteOptionsBase, s as SqliteTargetId, t as SqliteClient } from "./sqlite-BOF4sYko-PDYW__5e.mjs";
1
+ import { a as SqliteTargetId, n as SqliteOptions, o as sqlite, r as SqliteOptionsBase, t as SqliteClient } from "./sqlite-ACJ_xaqh-BEpUGh9k.mjs";
2
2
  import { Runtime, SqlRuntimeBase } from "@prisma/orm-family-sql/runtime";
3
3
  import "@prisma/orm-target-sqlite/driver/runtime";
4
4
  import { Contract } from "@prisma/orm-framework/contract/types";
@@ -20,5 +20,5 @@ type SqliteBindingInput = {
20
20
  interface SqliteRuntime extends Runtime {}
21
21
  declare class SqliteRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> extends SqlRuntimeBase<TContract> {}
22
22
  //#endregion
23
- export { type SqliteBindingInput, type SqliteClient, type SqliteOptions, type SqliteOptionsBase, type SqliteOptionsWithContract, type SqliteOptionsWithContractJson, type SqliteRuntime, SqliteRuntimeImpl, type SqliteTargetId, sqlite as default };
23
+ export { type SqliteBindingInput, type SqliteClient, type SqliteOptions, type SqliteOptionsBase, type SqliteRuntime, SqliteRuntimeImpl, type SqliteTargetId, sqlite as default };
24
24
  //# sourceMappingURL=runtime.d.mts.map
package/dist/runtime.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { t as buildSqliteStaticContext } from "./sqlite-static-CX2elTbu-CoM_gcs_.mjs";
1
+ import { i as validateSqliteContract, t as buildSqliteStaticContext } from "./sqlite-static-DweoQJlB-B10H1xWF.mjs";
2
2
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
3
3
  import sqliteAdapter from "@prisma/orm-target-sqlite/adapter/runtime";
4
4
  import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
5
5
  import { sql } from "@prisma/orm-family-sql/builder/runtime";
6
6
  import { SqlRuntimeBase, activitySource, createExecutionContext, createSqlExecutionStack, delegatingActivitySource, withTransaction } from "@prisma/orm-family-sql/runtime";
7
- import sqliteTarget, { SqliteContractSerializer } from "@prisma/orm-target-sqlite/target/runtime";
7
+ import sqliteTarget from "@prisma/orm-target-sqlite/target/runtime";
8
8
  import { assertDefined } from "@prisma/orm-framework/utils/assertions";
9
9
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
10
10
  import sqliteDriver from "@prisma/orm-target-sqlite/driver/runtime";
@@ -35,15 +35,25 @@ function unboundOrm(orm) {
35
35
  assertDefined(value, "the unbound namespace always exists on a sqlite builder output");
36
36
  return blindCast(value);
37
37
  }
38
- function resolveContract(options) {
39
- const serializer = new SqliteContractSerializer();
40
- if ("contractJson" in options && options.contractJson !== void 0) return blindCast(serializer.deserializeContract(options.contractJson));
41
- const contract = options.contract;
42
- assertDefined(contract, "a contract or contractJson is required");
43
- return blindCast(serializer.deserializeContract(serializer.serializeContract(contract)));
44
- }
38
+ /**
39
+ * Creates a lazy SQLite client. The client infers its contract type from `contract`: a value from
40
+ * `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is
41
+ * validated once, however many clients are built from it. The database opens on the first query
42
+ * or `connect()`.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { contractFromJson } from '@prisma/orm-sqlite/static';
47
+ * import sqlite from '@prisma/orm-sqlite/runtime';
48
+ * import type { Contract } from './contract.d';
49
+ * import contractJson from './contract.json' with { type: 'json' };
50
+ *
51
+ * export const contract = contractFromJson<Contract>(contractJson);
52
+ * export const db = sqlite({ contract, path: './dev.db' });
53
+ * ```
54
+ */
45
55
  function sqlite(options) {
46
- const contract = resolveContract(options);
56
+ const contract = validateSqliteContract(options.contract);
47
57
  let binding = resolveOptionalSqliteBinding(options);
48
58
  const stack = createSqlExecutionStack({
49
59
  target: sqliteTarget,
@@ -56,7 +66,7 @@ function sqlite(options) {
56
66
  stack,
57
67
  driver: sqliteDriver
58
68
  });
59
- const { sql: sql$1, raw: rawSqlTag, enums } = buildSqliteStaticContext(context, stack.adapter.rawCodecInferer);
69
+ const { sql: sql$1, raw: rawSqlTag, enums } = buildSqliteStaticContext(contract, context, stack.adapter.rawCodecInferer);
60
70
  let runtimeInstance;
61
71
  let runtimeDriver;
62
72
  let driverConnected = false;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/runtime.mjs"],"sourcesContent":["import { t as buildSqliteStaticContext } from \"./sqlite-static-CX2elTbu.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport sqliteDriver from \"@internal/driver-sqlite/runtime\";\nimport { instantiateExecutionStack } from \"@internal/framework-components/execution\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { sql } from \"@internal/sql-builder/runtime\";\nimport { orm, prepareQuery } from \"@internal/sql-orm-client\";\nimport { SqlRuntimeBase, activitySource, createExecutionContext, createSqlExecutionStack, delegatingActivitySource, withTransaction } from \"@internal/sql-runtime\";\nimport sqliteTarget, { SqliteContractSerializer } from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast, castAs } from \"@internal/utils/casts\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/errors.ts\nfunction sqliteError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\n//#endregion\n//#region src/runtime/binding.ts\nfunction resolveSqliteBinding(input) {\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: input.path\n\t};\n}\nfunction resolveOptionalSqliteBinding(options) {\n\tif (options.path === void 0) return;\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: options.path\n\t};\n}\n//#endregion\n//#region src/runtime/sqlite-runtime.ts\nvar SqliteRuntimeImpl = class extends SqlRuntimeBase {};\n//#endregion\n//#region src/runtime/sqlite.ts\nfunction unboundOrm(orm) {\n\tconst value = orm[UNBOUND_NAMESPACE_ID];\n\tassertDefined(value, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn blindCast(value);\n}\nfunction resolveContract(options) {\n\tconst serializer = new SqliteContractSerializer();\n\tif (\"contractJson\" in options && options.contractJson !== void 0) return blindCast(serializer.deserializeContract(options.contractJson));\n\tconst contract = options.contract;\n\tassertDefined(contract, \"a contract or contractJson is required\");\n\treturn blindCast(serializer.deserializeContract(serializer.serializeContract(contract)));\n}\nfunction sqlite(options) {\n\tconst contract = resolveContract(options);\n\tlet binding = resolveOptionalSqliteBinding(options);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\tdriver: sqliteDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst context = createExecutionContext({\n\t\tcontract,\n\t\tstack,\n\t\tdriver: sqliteDriver\n\t});\n\tconst { sql: sql$1, raw: rawSqlTag, enums } = buildSqliteStaticContext(context, stack.adapter.rawCodecInferer);\n\tlet runtimeInstance;\n\tlet runtimeDriver;\n\tlet driverConnected = false;\n\tlet connectPromise;\n\tlet closePromise;\n\tlet backgroundConnectError;\n\tlet closed = false;\n\tlet ownedDispose;\n\tconst connectDriver = async (resolvedBinding) => {\n\t\tif (driverConnected) return;\n\t\tif (!runtimeDriver) throw new InternalError(\"SQLite runtime driver missing\");\n\t\tif (connectPromise) return connectPromise;\n\t\tconnectPromise = runtimeDriver.connect(resolvedBinding).then(() => {\n\t\t\tdriverConnected = true;\n\t\t}).catch((err) => {\n\t\t\tbackgroundConnectError = err;\n\t\t\tconnectPromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn connectPromise;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\tif (backgroundConnectError !== void 0) throw backgroundConnectError;\n\t\tif (runtimeInstance) return runtimeInstance;\n\t\tconst stackInstance = instantiateExecutionStack(stack);\n\t\tconst driverDescriptor = stack.driver;\n\t\tif (!driverDescriptor) throw new InternalError(\"Driver descriptor missing from execution stack\");\n\t\tconst driver = driverDescriptor.create();\n\t\townedDispose = () => driver.close();\n\t\truntimeDriver = driver;\n\t\tif (binding !== void 0) connectDriver(binding).catch(() => void 0);\n\t\truntimeInstance = new SqliteRuntimeImpl({\n\t\t\tcontext,\n\t\t\tadapter: stackInstance.adapter,\n\t\t\tdriver,\n\t\t\t...ifDefined(\"verifyMarker\", options.verifyMarker),\n\t\t\t...ifDefined(\"middleware\", options.middleware),\n\t\t\t...ifDefined(\"log\", options.log),\n\t\t\tcloseRefusal: \"at-once\"\n\t\t});\n\t\treturn runtimeInstance;\n\t};\n\tconst orm$1 = unboundOrm(orm({\n\t\tcontext,\n\t\truntime: {\n\t\t\tquery(plan) {\n\t\t\t\treturn getRuntime().query(plan);\n\t\t\t},\n\t\t\texecute(plan) {\n\t\t\t\treturn getRuntime().execute(plan);\n\t\t\t},\n\t\t\tconnection() {\n\t\t\t\treturn getRuntime().connection();\n\t\t\t},\n\t\t\t[activitySource]: delegatingActivitySource(() => getRuntime())\n\t\t}\n\t}));\n\tfunction prepare(declaration, callback) {\n\t\treturn prepareQuery(getRuntime(), declaration, callback);\n\t}\n\treturn {\n\t\tsql: sql$1,\n\t\torm: orm$1,\n\t\tenums,\n\t\traw: rawSqlTag,\n\t\tcontext,\n\t\tcontract,\n\t\tstack,\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\t\tif (driverConnected || connectPromise) throw sqliteError(\"DRIVER.ALREADY_CONNECTED\", \"SQLite client already connected\", { meta: { extension: \"sqlite\" } });\n\t\t\tbackgroundConnectError = void 0;\n\t\t\tif (bindingInput !== void 0) binding = resolveSqliteBinding(bindingInput);\n\t\t\tif (binding === void 0) throw sqliteError(\"RUNTIME.BINDING_MISSING\", \"SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).\", { meta: { extension: \"sqlite\" } });\n\t\t\tconst runtime = getRuntime();\n\t\t\tif (driverConnected) return runtime;\n\t\t\tawait connectDriver(binding);\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tprepare,\n\t\ttransaction(fn) {\n\t\t\tlet runtime;\n\t\t\ttry {\n\t\t\t\truntime = getRuntime();\n\t\t\t} catch (err) {\n\t\t\t\treturn Promise.reject(err);\n\t\t\t}\n\t\t\treturn withTransaction(runtime, (txCtx) => {\n\t\t\t\tconst rawCodecInferer = stack.adapter.rawCodecInferer;\n\t\t\t\tconst txSqlNamespace = sql({\n\t\t\t\t\tcontext,\n\t\t\t\t\trawCodecInferer\n\t\t\t\t})[UNBOUND_NAMESPACE_ID];\n\t\t\t\tassertDefined(txSqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\t\t\t\tconst txSql = blindCast(txSqlNamespace);\n\t\t\t\tconst txOrm = unboundOrm(orm({\n\t\t\t\t\truntime: {\n\t\t\t\t\t\tquery(plan) {\n\t\t\t\t\t\t\treturn txCtx.query(plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\texecute(plan) {\n\t\t\t\t\t\t\treturn txCtx.execute(plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[activitySource]: delegatingActivitySource(() => txCtx)\n\t\t\t\t\t},\n\t\t\t\t\tcontext\n\t\t\t\t}));\n\t\t\t\treturn fn(Object.assign(castAs(Object.create(txCtx)), {\n\t\t\t\t\tsql: txSql,\n\t\t\t\t\torm: txOrm,\n\t\t\t\t\tenums\n\t\t\t\t}));\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) return closePromise;\n\t\t\tclosed = true;\n\t\t\tclosePromise = (async () => {\n\t\t\t\tawait connectPromise?.catch(() => void 0);\n\t\t\t\tawait ownedDispose?.();\n\t\t\t})();\n\t\t\treturn closePromise;\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { SqliteRuntimeImpl, sqlite as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":"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"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/runtime.mjs"],"sourcesContent":["import { i as validateSqliteContract, t as buildSqliteStaticContext } from \"./sqlite-static-DweoQJlB.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport sqliteDriver from \"@internal/driver-sqlite/runtime\";\nimport { instantiateExecutionStack } from \"@internal/framework-components/execution\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { sql } from \"@internal/sql-builder/runtime\";\nimport { orm, prepareQuery } from \"@internal/sql-orm-client\";\nimport { SqlRuntimeBase, activitySource, createExecutionContext, createSqlExecutionStack, delegatingActivitySource, withTransaction } from \"@internal/sql-runtime\";\nimport sqliteTarget from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast, castAs } from \"@internal/utils/casts\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/errors.ts\nfunction sqliteError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\n//#endregion\n//#region src/runtime/binding.ts\nfunction resolveSqliteBinding(input) {\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: input.path\n\t};\n}\nfunction resolveOptionalSqliteBinding(options) {\n\tif (options.path === void 0) return;\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: options.path\n\t};\n}\n//#endregion\n//#region src/runtime/sqlite-runtime.ts\nvar SqliteRuntimeImpl = class extends SqlRuntimeBase {};\n//#endregion\n//#region src/runtime/sqlite.ts\nfunction unboundOrm(orm) {\n\tconst value = orm[UNBOUND_NAMESPACE_ID];\n\tassertDefined(value, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn blindCast(value);\n}\n/**\n* Creates a lazy SQLite client. The client infers its contract type from `contract`: a value from\n* `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is\n* validated once, however many clients are built from it. The database opens on the first query\n* or `connect()`.\n*\n* @example\n* ```ts\n* import { contractFromJson } from '@prisma/orm-sqlite/static';\n* import sqlite from '@prisma/orm-sqlite/runtime';\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* export const db = sqlite({ contract, path: './dev.db' });\n* ```\n*/\nfunction sqlite(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tlet binding = resolveOptionalSqliteBinding(options);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\tdriver: sqliteDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst context = createExecutionContext({\n\t\tcontract,\n\t\tstack,\n\t\tdriver: sqliteDriver\n\t});\n\tconst { sql: sql$1, raw: rawSqlTag, enums } = buildSqliteStaticContext(contract, context, stack.adapter.rawCodecInferer);\n\tlet runtimeInstance;\n\tlet runtimeDriver;\n\tlet driverConnected = false;\n\tlet connectPromise;\n\tlet closePromise;\n\tlet backgroundConnectError;\n\tlet closed = false;\n\tlet ownedDispose;\n\tconst connectDriver = async (resolvedBinding) => {\n\t\tif (driverConnected) return;\n\t\tif (!runtimeDriver) throw new InternalError(\"SQLite runtime driver missing\");\n\t\tif (connectPromise) return connectPromise;\n\t\tconnectPromise = runtimeDriver.connect(resolvedBinding).then(() => {\n\t\t\tdriverConnected = true;\n\t\t}).catch((err) => {\n\t\t\tbackgroundConnectError = err;\n\t\t\tconnectPromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn connectPromise;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\tif (backgroundConnectError !== void 0) throw backgroundConnectError;\n\t\tif (runtimeInstance) return runtimeInstance;\n\t\tconst stackInstance = instantiateExecutionStack(stack);\n\t\tconst driverDescriptor = stack.driver;\n\t\tif (!driverDescriptor) throw new InternalError(\"Driver descriptor missing from execution stack\");\n\t\tconst driver = driverDescriptor.create();\n\t\townedDispose = () => driver.close();\n\t\truntimeDriver = driver;\n\t\tif (binding !== void 0) connectDriver(binding).catch(() => void 0);\n\t\truntimeInstance = new SqliteRuntimeImpl({\n\t\t\tcontext,\n\t\t\tadapter: stackInstance.adapter,\n\t\t\tdriver,\n\t\t\t...ifDefined(\"verifyMarker\", options.verifyMarker),\n\t\t\t...ifDefined(\"middleware\", options.middleware),\n\t\t\t...ifDefined(\"log\", options.log),\n\t\t\tcloseRefusal: \"at-once\"\n\t\t});\n\t\treturn runtimeInstance;\n\t};\n\tconst orm$1 = unboundOrm(orm({\n\t\tcontext,\n\t\truntime: {\n\t\t\tquery(plan) {\n\t\t\t\treturn getRuntime().query(plan);\n\t\t\t},\n\t\t\texecute(plan) {\n\t\t\t\treturn getRuntime().execute(plan);\n\t\t\t},\n\t\t\tconnection() {\n\t\t\t\treturn getRuntime().connection();\n\t\t\t},\n\t\t\t[activitySource]: delegatingActivitySource(() => getRuntime())\n\t\t}\n\t}));\n\tfunction prepare(declaration, callback) {\n\t\treturn prepareQuery(getRuntime(), declaration, callback);\n\t}\n\treturn {\n\t\tsql: sql$1,\n\t\torm: orm$1,\n\t\tenums,\n\t\traw: rawSqlTag,\n\t\tcontext,\n\t\tcontract,\n\t\tstack,\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\t\tif (driverConnected || connectPromise) throw sqliteError(\"DRIVER.ALREADY_CONNECTED\", \"SQLite client already connected\", { meta: { extension: \"sqlite\" } });\n\t\t\tbackgroundConnectError = void 0;\n\t\t\tif (bindingInput !== void 0) binding = resolveSqliteBinding(bindingInput);\n\t\t\tif (binding === void 0) throw sqliteError(\"RUNTIME.BINDING_MISSING\", \"SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).\", { meta: { extension: \"sqlite\" } });\n\t\t\tconst runtime = getRuntime();\n\t\t\tif (driverConnected) return runtime;\n\t\t\tawait connectDriver(binding);\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tprepare,\n\t\ttransaction(fn) {\n\t\t\tlet runtime;\n\t\t\ttry {\n\t\t\t\truntime = getRuntime();\n\t\t\t} catch (err) {\n\t\t\t\treturn Promise.reject(err);\n\t\t\t}\n\t\t\treturn withTransaction(runtime, (txCtx) => {\n\t\t\t\tconst rawCodecInferer = stack.adapter.rawCodecInferer;\n\t\t\t\tconst txSqlNamespace = sql({\n\t\t\t\t\tcontext,\n\t\t\t\t\trawCodecInferer\n\t\t\t\t})[UNBOUND_NAMESPACE_ID];\n\t\t\t\tassertDefined(txSqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\t\t\t\tconst txSql = blindCast(txSqlNamespace);\n\t\t\t\tconst txOrm = unboundOrm(orm({\n\t\t\t\t\truntime: {\n\t\t\t\t\t\tquery(plan) {\n\t\t\t\t\t\t\treturn txCtx.query(plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\texecute(plan) {\n\t\t\t\t\t\t\treturn txCtx.execute(plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[activitySource]: delegatingActivitySource(() => txCtx)\n\t\t\t\t\t},\n\t\t\t\t\tcontext\n\t\t\t\t}));\n\t\t\t\treturn fn(Object.assign(castAs(Object.create(txCtx)), {\n\t\t\t\t\tsql: txSql,\n\t\t\t\t\torm: txOrm,\n\t\t\t\t\tenums\n\t\t\t\t}));\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) return closePromise;\n\t\t\tclosed = true;\n\t\t\tclosePromise = (async () => {\n\t\t\t\tawait connectPromise?.catch(() => void 0);\n\t\t\t\tawait ownedDispose?.();\n\t\t\t})();\n\t\t\treturn closePromise;\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { SqliteRuntimeImpl, sqlite as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":"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"}
@@ -7,7 +7,7 @@ import { ExtractCodecTypes, SqlStorage } from "@prisma/orm-family-sql/contract/t
7
7
  import { Db, RawLane } from "@prisma/orm-family-sql/builder/types";
8
8
  import { CodecTypesBase } from "@prisma/orm-family-sql/relational-core/expression";
9
9
  import { Preparable, SqlQueryPlan } from "@prisma/orm-family-sql/relational-core/plan";
10
- //#region ../../../3-extensions/sqlite/dist/sqlite-BOF4sYko.d.mts
10
+ //#region ../../../3-extensions/sqlite/dist/sqlite-ACJ_xaqh.d.mts
11
11
  //#region src/static/sqlite-static.d.ts
12
12
  type UnboundSql$1<TContract extends Contract<SqlStorage>> = Db<TContract>[typeof UNBOUND_NAMESPACE_ID];
13
13
  type UnboundEnums<TContract extends Contract<SqlStorage>> = NamespacedEnums<TContract>[typeof UNBOUND_NAMESPACE_ID];
@@ -18,8 +18,17 @@ interface SqliteStaticContext<TContract extends Contract<SqlStorage>> {
18
18
  readonly sql: UnboundSql$1<TContract>;
19
19
  readonly raw: RawLane<TContract>;
20
20
  }
21
+ /**
22
+ * The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where
23
+ * loading `node:sqlite` is not wanted.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const { enums } = sqliteStatic({ contract: contractFromJson<Contract>(contractJson) });
28
+ * ```
29
+ */
21
30
  declare function sqliteStatic<TContract extends Contract<SqlStorage>>(options: {
22
- readonly contractJson: unknown;
31
+ readonly contract: TContract;
23
32
  readonly extensions?: readonly SqlRuntimeExtensionDescriptor<SqliteTargetId>[];
24
33
  }): SqliteStaticContext<TContract>;
25
34
  //#endregion
@@ -56,22 +65,28 @@ interface SqliteOptionsBase {
56
65
  readonly verifyMarker?: VerifyMarkerOption;
57
66
  readonly log?: Log;
58
67
  }
59
- type SqliteOptionsWithContract<TContract extends Contract<SqlStorage>> = {
60
- readonly path?: string;
61
- } & SqliteOptionsBase & {
68
+ type SqliteOptions<TContract extends Contract<SqlStorage>> = SqliteOptionsBase & {
62
69
  readonly contract: TContract;
63
- readonly contractJson?: never;
64
- };
65
- type SqliteOptionsWithContractJson<TContract extends Contract<SqlStorage>> = {
66
70
  readonly path?: string;
67
- readonly _contract?: TContract;
68
- } & SqliteOptionsBase & {
69
- readonly contractJson: unknown;
70
- readonly contract?: never;
71
71
  };
72
- type SqliteOptions<TContract extends Contract<SqlStorage>> = SqliteOptionsWithContract<TContract> | SqliteOptionsWithContractJson<TContract>;
73
- declare function sqlite<TContract extends Contract<SqlStorage>>(options: SqliteOptionsWithContract<TContract>): SqliteClient<TContract>;
74
- declare function sqlite<TContract extends Contract<SqlStorage>>(options: SqliteOptionsWithContractJson<TContract>): SqliteClient<TContract>;
72
+ /**
73
+ * Creates a lazy SQLite client. The client infers its contract type from `contract`: a value from
74
+ * `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is
75
+ * validated once, however many clients are built from it. The database opens on the first query
76
+ * or `connect()`.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import { contractFromJson } from '@prisma/orm-sqlite/static';
81
+ * import sqlite from '@prisma/orm-sqlite/runtime';
82
+ * import type { Contract } from './contract.d';
83
+ * import contractJson from './contract.json' with { type: 'json' };
84
+ *
85
+ * export const contract = contractFromJson<Contract>(contractJson);
86
+ * export const db = sqlite({ contract, path: './dev.db' });
87
+ * ```
88
+ */
89
+ declare function sqlite<TContract extends Contract<SqlStorage>>(options: SqliteOptions<TContract>): SqliteClient<TContract>;
75
90
  //#endregion
76
- export { SqliteOptionsWithContractJson as a, sqlite as c, SqliteOptionsWithContract as i, sqliteStatic as l, SqliteOptions as n, SqliteStaticContext as o, SqliteOptionsBase as r, SqliteTargetId as s, SqliteClient as t };
77
- //# sourceMappingURL=sqlite-BOF4sYko-PDYW__5e.d.mts.map
91
+ export { SqliteTargetId as a, SqliteStaticContext as i, SqliteOptions as n, sqlite as o, SqliteOptionsBase as r, sqliteStatic as s, SqliteClient as t };
92
+ //# sourceMappingURL=sqlite-ACJ_xaqh-BEpUGh9k.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-ACJ_xaqh-BEpUGh9k.d.mts","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-ACJ_xaqh.d.mts"],"mappings":";;;;;;;;;;;KAUK,aAAa,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC5E,aAAa,kBAAkB,SAAS,eAAe,gBAAgB,kBAAkB;UACpF,oBAAoB,kBAAkB,SAAS;WAC9C,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,aAAa;WACpB,KAAK,aAAa;WAClB,KAAK,QAAQ;;;;;;;;;;;iBAWP,aAAa,kBAAkB,SAAS,aAAa;WAC3D,UAAU;WACV,sBAAsB,8BAA8B;IAC3D,oBAAoB;;;KAGnB;KACA,UAAU,kBAAkB,SAAS,eAAe,kBAAkB,IAAI;KAC1E,WAAW,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC1E,WAAW,kBAAkB,SAAS,eAAe,UAAU,kBAAkB;UAC5E,yBAAyB,kBAAkB,SAAS,qBAAqB;WACxE,KAAK,WAAW;WAChB,KAAK,WAAW;WAChB,OAAO,oBAAoB;;UAE5B,aAAa,kBAAkB,SAAS;WACvC,KAAK,WAAW;WAChB,KAAK,WAAW;WAChB,OAAO,oBAAoB;WAC3B,KAAK,QAAQ;WACb,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,4BAA4B;EAC5C,QAAQ;aACG;MACP,QAAQ;EACZ,WAAW;EACX,QAAQ,UAAU,YAAY,KAAK,UAAU,eAAe,8BAA8B,WAAW,iBAAiB,kBAAkB,YAAY,aAAa,GAAG,WAAW,QAAQ,eAAe,OAAO,IAAI,QAAQ,aAAa,sBAAsB,GAAG,KAAK;EACpQ,YAAY,GAAG,KAAK,IAAI,yBAAyB,eAAe,YAAY,KAAK,QAAQ;EACzF,SAAS;GACR,OAAO,iBAAiB;;UAEjB;WACC,sBAAsB,8BAA8B;WACpD,sBAAsB;WACtB,eAAe;WACf,MAAM;;KAEZ,cAAc,kBAAkB,SAAS,eAAe;WAClD,UAAU;WACV;;;;;;;;;;;;;;;;;;;iBAmBM,OAAO,kBAAkB,SAAS,aAAa,SAAS,cAAc,aAAa,aAAa"}
@@ -0,0 +1,81 @@
1
+ import sqliteAdapter from "@prisma/orm-target-sqlite/adapter/runtime";
2
+ import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
3
+ import { createRawLane, sql } from "@prisma/orm-family-sql/builder/runtime";
4
+ import { createExecutionContext, createSqlExecutionStack } from "@prisma/orm-family-sql/runtime";
5
+ import sqliteTarget, { SqliteContractSerializer } from "@prisma/orm-target-sqlite/target/runtime";
6
+ import { assertDefined } from "@prisma/orm-framework/utils/assertions";
7
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
8
+ import { validateContractOnce } from "@prisma/orm-framework/contract/validate-once";
9
+ import { buildNamespacedEnums } from "@prisma/orm-framework/contract/enum-accessor";
10
+ //#region ../../../3-extensions/sqlite/dist/sqlite-static-DweoQJlB.mjs
11
+ var version = "8.0.0-rc.18-dev.22";
12
+ const serializer = new SqliteContractSerializer();
13
+ const validator = `${sqliteTarget.targetId}@${version}`;
14
+ /**
15
+ * Validates an emitted SQLite `contract.json` and returns it as the contract type the application
16
+ * names, ready to pass to `sqlite({ contract })` and `sqliteStatic({ contract })`. Clients built
17
+ * from the result do not validate it again.
18
+ *
19
+ * The returned value's top level is frozen; its nested objects are not. Do not change `json` or the
20
+ * returned value after the call: clients built from the value later do not validate it again.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import type { Contract } from './contract.d';
25
+ * import contractJson from './contract.json' with { type: 'json' };
26
+ *
27
+ * export const contract = contractFromJson<Contract>(contractJson);
28
+ * ```
29
+ */
30
+ function contractFromJson(json) {
31
+ return validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));
32
+ }
33
+ function validateSqliteContract(contract) {
34
+ return validateContractOnce(contract, validator, () => serializer.deserializeContract(serializer.serializeContract(contract)));
35
+ }
36
+ function buildSqliteStaticContext(contract, context, rawCodecInferer) {
37
+ const sqlNamespace = sql({
38
+ context,
39
+ rawCodecInferer
40
+ })[UNBOUND_NAMESPACE_ID];
41
+ assertDefined(sqlNamespace, "the unbound namespace always exists on a sqlite builder output");
42
+ const sqlDb = blindCast(sqlNamespace);
43
+ const raw = createRawLane({
44
+ context,
45
+ rawCodecInferer
46
+ });
47
+ const enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];
48
+ assertDefined(enums, "the unbound namespace always exists on a sqlite builder output");
49
+ return {
50
+ context,
51
+ contract,
52
+ enums,
53
+ sql: sqlDb,
54
+ raw
55
+ };
56
+ }
57
+ /**
58
+ * The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where
59
+ * loading `node:sqlite` is not wanted.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const { enums } = sqliteStatic({ contract: contractFromJson<Contract>(contractJson) });
64
+ * ```
65
+ */
66
+ function sqliteStatic(options) {
67
+ const contract = validateSqliteContract(options.contract);
68
+ const stack = createSqlExecutionStack({
69
+ target: sqliteTarget,
70
+ adapter: sqliteAdapter,
71
+ extensions: options.extensions ?? []
72
+ });
73
+ return buildSqliteStaticContext(contract, createExecutionContext({
74
+ contract,
75
+ stack
76
+ }), stack.adapter.rawCodecInferer);
77
+ }
78
+ //#endregion
79
+ export { validateSqliteContract as i, contractFromJson as n, sqliteStatic as r, buildSqliteStaticContext as t };
80
+
81
+ //# sourceMappingURL=sqlite-static-DweoQJlB-B10H1xWF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-static-DweoQJlB-B10H1xWF.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-static-DweoQJlB.mjs"],"sourcesContent":["import sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { createExecutionContext, createSqlExecutionStack } from \"@internal/sql-runtime\";\nimport sqliteTarget, { SqliteContractSerializer } from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { validateContractOnce } from \"@internal/contract/validate-once\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\n//#region package.json\nvar version = \"8.0.0-rc.18-dev.22\";\n//#endregion\n//#region src/static/contract-from-json.ts\nconst serializer = new SqliteContractSerializer();\nconst validator = `${sqliteTarget.targetId}@${version}`;\n/**\n* Validates an emitted SQLite `contract.json` and returns it as the contract type the application\n* names, ready to pass to `sqlite({ contract })` and `sqliteStatic({ contract })`. Clients built\n* from the result do not validate it again.\n*\n* The returned value's top level is frozen; its nested objects are not. Do not change `json` or the\n* returned value after the call: clients built from the value later do not validate it again.\n*\n* @example\n* ```ts\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* ```\n*/\nfunction contractFromJson(json) {\n\treturn validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));\n}\nfunction validateSqliteContract(contract) {\n\treturn validateContractOnce(contract, validator, () => serializer.deserializeContract(serializer.serializeContract(contract)));\n}\n//#endregion\n//#region src/static/sqlite-static.ts\nfunction buildSqliteStaticContext(contract, context, rawCodecInferer) {\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\tconst sqlDb = blindCast(sqlNamespace);\n\tconst raw = createRawLane({\n\t\tcontext,\n\t\trawCodecInferer\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract,\n\t\tenums,\n\t\tsql: sqlDb,\n\t\traw\n\t};\n}\n/**\n* The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where\n* loading `node:sqlite` is not wanted.\n*\n* @example\n* ```ts\n* const { enums } = sqliteStatic({ contract: contractFromJson<Contract>(contractJson) });\n* ```\n*/\nfunction sqliteStatic(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildSqliteStaticContext(contract, createExecutionContext({\n\t\tcontract,\n\t\tstack\n\t}), stack.adapter.rawCodecInferer);\n}\n//#endregion\nexport { validateSqliteContract as i, sqliteStatic as n, contractFromJson as r, buildSqliteStaticContext as t };\n\n//# sourceMappingURL=sqlite-static-DweoQJlB.mjs.map"],"mappings":";;;;;;;;;;AAUA,IAAI,UAAU;AAGd,MAAM,aAAa,IAAI,yBAAyB;AAChD,MAAM,YAAY,GAAG,aAAa,SAAS,GAAG;;;;;;;;;;;;;;;;;AAiB9C,SAAS,iBAAiB,MAAM;CAC/B,OAAO,qBAAqB,MAAM,YAAY,UAAU,WAAW,oBAAoB,KAAK,CAAC;AAC9F;AACA,SAAS,uBAAuB,UAAU;CACzC,OAAO,qBAAqB,UAAU,iBAAiB,WAAW,oBAAoB,WAAW,kBAAkB,QAAQ,CAAC,CAAC;AAC9H;AAGA,SAAS,yBAAyB,UAAU,SAAS,iBAAiB;CACrE,MAAM,eAAe,IAAI;EACxB;EACA;CACD,CAAC,CAAC,CAAC;CACH,cAAc,cAAc,gEAAgE;CAC5F,MAAM,QAAQ,UAAU,YAAY;CACpC,MAAM,MAAM,cAAc;EACzB;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,SAAS,YAAY,QAAQ,eAAe,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;CACzI,cAAc,OAAO,gEAAgE;CACrF,OAAO;EACN;EACA;EACA;EACA,KAAK;EACL;CACD;AACD;;;;;;;;;;AAUA,SAAS,aAAa,SAAS;CAC9B,MAAM,WAAW,uBAAuB,QAAQ,QAAQ;CACxD,MAAM,QAAQ,wBAAwB;EACrC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,yBAAyB,UAAU,uBAAuB;EAChE;EACA;CACD,CAAC,GAAG,MAAM,QAAQ,eAAe;AAClC"}
package/dist/static.d.mts CHANGED
@@ -1,2 +1,25 @@
1
- import { l as sqliteStatic, o as SqliteStaticContext } from "./sqlite-BOF4sYko-PDYW__5e.mjs";
2
- export { type SqliteStaticContext, sqliteStatic as default };
1
+ import { i as SqliteStaticContext, s as sqliteStatic } from "./sqlite-ACJ_xaqh-BEpUGh9k.mjs";
2
+ import { Contract } from "@prisma/orm-framework/contract/types";
3
+ import { SqlStorage } from "@prisma/orm-family-sql/contract/types";
4
+ //#region ../../../3-extensions/sqlite/dist/static.d.mts
5
+ //#region src/static/contract-from-json.d.ts
6
+ /**
7
+ * Validates an emitted SQLite `contract.json` and returns it as the contract type the application
8
+ * names, ready to pass to `sqlite({ contract })` and `sqliteStatic({ contract })`. Clients built
9
+ * from the result do not validate it again.
10
+ *
11
+ * The returned value's top level is frozen; its nested objects are not. Do not change `json` or the
12
+ * returned value after the call: clients built from the value later do not validate it again.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import type { Contract } from './contract.d';
17
+ * import contractJson from './contract.json' with { type: 'json' };
18
+ *
19
+ * export const contract = contractFromJson<Contract>(contractJson);
20
+ * ```
21
+ */
22
+ declare function contractFromJson<TContract extends Contract<SqlStorage>>(json: unknown): TContract;
23
+ //#endregion
24
+ export { type SqliteStaticContext, contractFromJson, sqliteStatic as default };
25
+ //# sourceMappingURL=static.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"static.d.mts","names":[],"sources":["../../../../3-extensions/sqlite/dist/static.d.mts"],"mappings":";;;;;;;;;;;;;;;;;;;;;iBAoBiB,iBAAiB,kBAAkB,SAAS,aAAa,gBAAgB"}
package/dist/static.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as sqliteStatic } from "./sqlite-static-CX2elTbu-CoM_gcs_.mjs";
2
- export { sqliteStatic as default };
1
+ import { n as contractFromJson, r as sqliteStatic } from "./sqlite-static-DweoQJlB-B10H1xWF.mjs";
2
+ export { contractFromJson, sqliteStatic as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/orm-sqlite",
3
- "version": "8.0.0-rc.18-dev.20",
3
+ "version": "8.0.0-rc.18-dev.22",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -10,17 +10,17 @@
10
10
  "skills"
11
11
  ],
12
12
  "dependencies": {
13
- "@prisma/orm-family-sql": "8.0.0-rc.18-dev.20",
14
- "@prisma/orm-framework": "8.0.0-rc.18-dev.20",
15
- "@prisma/orm-target-sqlite": "8.0.0-rc.18-dev.20",
16
- "@prisma/orm-toolchain": "8.0.0-rc.18-dev.20",
13
+ "@prisma/orm-family-sql": "8.0.0-rc.18-dev.22",
14
+ "@prisma/orm-framework": "8.0.0-rc.18-dev.22",
15
+ "@prisma/orm-target-sqlite": "8.0.0-rc.18-dev.22",
16
+ "@prisma/orm-toolchain": "8.0.0-rc.18-dev.22",
17
17
  "pathe": "^2.0.3",
18
18
  "tinyglobby": "^0.2.17"
19
19
  },
20
20
  "devDependencies": {
21
- "@internal/sqlite": "8.0.0-rc.18-dev.20",
22
- "@repo/tsconfig": "8.0.0-rc.18-dev.20",
23
- "@repo/tsdown": "8.0.0-rc.18-dev.20",
21
+ "@internal/sqlite": "8.0.0-rc.18-dev.22",
22
+ "@repo/tsconfig": "8.0.0-rc.18-dev.22",
23
+ "@repo/tsdown": "8.0.0-rc.18-dev.22",
24
24
  "tsdown": "0.22.14",
25
25
  "typescript": "5.9.3"
26
26
  },
@@ -67,6 +67,7 @@
67
67
  "./contract/resolve-domain-model": "./dist/contract__resolve-domain-model.mjs",
68
68
  "./contract/types": "./dist/contract__types.mjs",
69
69
  "./contract/validate-domain": "./dist/contract__validate-domain.mjs",
70
+ "./contract/validate-once": "./dist/contract__validate-once.mjs",
70
71
  "./contract-builder": "./dist/contract-builder.mjs",
71
72
  "./control": "./dist/control.mjs",
72
73
  "./driver": "./dist/driver.mjs",
@@ -15,7 +15,7 @@ description: >-
15
15
  ORM 7 or earlier (schema.prisma + @prisma/client).
16
16
  metadata:
17
17
  library: '@prisma/orm-sqlite'
18
- library_version: '8.0.0-rc.18-dev.20'
18
+ library_version: '8.0.0-rc.18-dev.22'
19
19
  version: '2026-09-12'
20
20
  ---
21
21
 
@@ -63,7 +63,7 @@ Open the reference whose triggers match the task. If more than one matches, open
63
63
  | Migration graph, refs, plan origin | [`references/migration-model.md`](references/migration-model.md) | migration graph, refs, `migration ref set` / `list` / `delete`, the `db` ref, `--advance-ref`, `--no-advance-ref`, `migration plan --from`, `from: (baseline)` in plan output, greenfield / from-scratch plan, baseline, first migration before deploy (Composer / CD-managed databases), chaining migrations, retrofitting migrations onto an existing database, `MIGRATION.HASH_NOT_IN_GRAPH`, `MIGRATION.PATH_UNREACHABLE` at plan/chain time |
64
64
  | Review migrations on deploy | [`references/migration-review.md`](references/migration-review.md) | "what migrations are going to run", "what runs on deploy / merge", merge conflict, diamond convergence, concurrent migrations, migration status, ref management for CI, staging / production environment refs, `MIGRATION.MARKER_NOT_IN_HISTORY`, `MIGRATION.MISSING_INVARIANTS`, `db migrate --show` |
65
65
  | Write queries | [`references/queries.md`](references/queries.md) | query, where, select, project, orderBy, limit, offset, take, skip, include, lookup, first, all, count, aggregate, groupBy, create, update, delete, upsert, returning, transaction, `db.orm`, `db.sql`, `runtime.query(plan)` vs `runtime.execute(plan)`, `db.prepare` / prepared statements, streaming / `for await`, many-to-many `include` and nested `connect`, `and` / `or` / `not` from `@prisma/orm-postgres/orm-client`, `db.query.from(...)` (Mongo pipeline), namespace-aware accessors, `.all()` Thenable, single-use iterators (`RUNTIME.ITERATOR_CONSUMED`), target-declared aggregate types (`count`, integer `sum`, and integer `avg` are `number`; `count` and integer `sum` throw outside ±(2^53 − 1) rather than round, while `avg` is a fraction already and carries no guard; `countBigInt` / `sumBigInt` / `avgDecimal` are the lossless forms, `avgDecimal` on PostgreSQL only), custom collection class (`extends Collection`), `with` and query fragments (`QueryFragment`, `Filtered`, `Ordered`), shared query fragments and scopes (`db.orm.fragment(fields, body)` for a filter on every model with given fields, `CodecField`, `db.orm.public.Post.fragment(...)` for a shared `select` / `include`, `orderByField` for an order or sort parameter from a request), drizzle-style, kysely-style. Naming types (§ *Naming model and result types*): "type of my model", "return type of a query", `ResultType`, `Scalars`, `Shape`, `models` / `Models` namespace in `contract.d.ts`, `Models.public_User`, Prisma 7 `Prisma.User` / `GetPayload` / `UserGetPayload` equivalents. Postgres/SQLite specifics: [`references/queries-postgres.md`](references/queries-postgres.md); Mongo specifics: [`references/queries-mongo.md`](references/queries-mongo.md) |
66
- | Wire the runtime | [`references/runtime.md`](references/runtime.md) | `db.ts`, `postgres<Contract>(...)` / `sqlite<Contract>(...)` / `mongo<Contract>(...)` façades, middleware composition (lints, budgets, cache via `@prisma/orm-extension-middleware-cache`, custom `activityEnded` middleware, `@prisma/orm-postgres/family-runtime`), `DATABASE_URL`, `.env`, connection pool / `poolOptions`, dev vs prod config, transactions, read replicas, multi-database, script won't exit / hangs, `db.close` / `pool.end`, `await using` / `[Symbol.asyncDispose]` |
66
+ | Wire the runtime | [`references/runtime.md`](references/runtime.md) | `db.ts`, `contractFromJson<Contract>(...)`, `postgres({ contract })` / `sqlite({ contract })` / `mongo({ contract })` façades, middleware composition (lints, budgets, cache via `@prisma/orm-extension-middleware-cache`, custom `activityEnded` middleware, `@prisma/orm-postgres/family-runtime`), `DATABASE_URL`, `.env`, connection pool / `poolOptions`, dev vs prod config, transactions, read replicas, multi-database, script won't exit / hangs, `db.close` / `pool.end`, `await using` / `[Symbol.asyncDispose]` |
67
67
  | Build-tool integration | [`references/build.md`](references/build.md) | Vite plugin (`@internal/vite-plugin-contract-emit`, Vite 7/8), `vite.config.ts`, contract emit on save, HMR / dev server, Next.js / Webpack / esbuild / Rollup / Turbopack (named gaps, not fabricated) |
68
68
  | Supabase | [`references/supabase.md`](references/supabase.md) | `@internal/extension-supabase`, RLS, row level security, policies (`policy_select` / `policy_update` / `@@rls`, `auth.uid()`), role binding (`asUser(jwt)` / `asAnon()` / `asServiceRole()`), `auth.users`, cross-space FKs to `supabase:auth.AuthUser`, JWT / JWKS (`SUPABASE_JWKS_URL`, `SUPABASE_JWT_SECRET`), `SUPABASE.JWT_INVALID`, `SUPABASE.CONFIG_INVALID`, `RoleBoundDb`, session pooler |
69
69
  | Debug an error | [`references/debug.md`](references/debug.md) | any structured error envelope (code, severity, why, fix, nextActions, meta), emit failed, query won't typecheck, query crashed, migration won't apply, `MIGRATION.HASH_MISMATCH`, `MIGRATION.RUNNER_FAILED`, `BUDGET.ROWS_EXCEEDED`, `BUDGET.TIME_EXCEEDED`, `RUNTIME.ABORTED`, `RUNTIME.TEMPORAL_UNAVAILABLE`, `PLAN.HASH_MISMATCH`, `CONTRACT.MARKER_MISSING`, `CONFIG.*` / `CLI.*` / `CONTRACT.*` / `MIGRATION.*` / `ORM.*` / `RUNTIME.*` codes, legacy `PN-*` codes, exit code 4 findings, drift, capability missing, planner conflict, EXPLAIN, query log, script won't exit / close connection |
@@ -40,7 +40,7 @@ Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`
40
40
 
41
41
  ## Key Concepts
42
42
 
43
- - **The `@internal/<target>` façade is the only surface user-authored code imports from.** For a Postgres app: `@internal/postgres/config`, `@internal/postgres/contract-builder`, `@internal/postgres/control`, `@internal/postgres/runtime`. Mongo has the same layout (`@internal/mongo/config`, `@internal/mongo/contract-builder`, `@internal/mongo/runtime`). Each extension publishes its own façade — `@internal/extension-pgvector/control`, `@internal/extension-postgis/control`, `@internal/extension-paradedb/control`. **Never reach into `@internal/cli/*`, `@internal/family-*`, `@internal/target-*`, `@internal/adapter-*`, `@internal/driver-*`, or `@internal/sql-contract-*` from user code.** The façade bakes the family / target / adapter / driver wiring in. See *Common Pitfalls* #4.
43
+ - **The `@internal/<target>` façade is the only surface user-authored code imports from.** For a Postgres app: `@internal/postgres/config`, `@internal/postgres/contract-builder`, `@internal/postgres/control`, `@internal/postgres/runtime`, `@internal/postgres/static`. Mongo has the same layout (`@internal/mongo/config`, `@internal/mongo/contract-builder`, `@internal/mongo/runtime`, `@internal/mongo/static`). Each extension publishes its own façade — `@internal/extension-pgvector/control`, `@internal/extension-postgis/control`, `@internal/extension-paradedb/control`. **Never reach into `@internal/cli/*`, `@internal/family-*`, `@internal/target-*`, `@internal/adapter-*`, `@internal/driver-*`, or `@internal/sql-contract-*` from user code.** The façade bakes the family / target / adapter / driver wiring in. See *Common Pitfalls* #4.
44
44
  - **Contract source.** A file the framework reads and lowers to the canonical Contract IR. Two flavours, both first-class:
45
45
  - **`contract.prisma` (PSL)** — schema-flavoured DSL. Canonical for typical apps and brownfield Prisma users. Wired by `contract: './<path>/contract.prisma'` — the target config (`ormConfig`, below) detects the `.prisma` extension and routes through the PSL provider. The first line of every `.prisma` file is `// use prisma-8`; `orm init` and `contract infer` write it, and the language server only serves diagnostics, completion, and formatting on files that carry it (it still recognises the header earlier releases wrote and rewrites it on Format).
46
46
  - **`contract.ts` (TypeScript builder)** — programmatic authoring with `defineContract({...}, ({ field, model, rel, type }) => ({...}))` from `@internal/postgres/contract-builder` (or `@internal/mongo/contract-builder`). Wired by `contract: './<path>/contract.ts'` — the façade detects the `.ts` extension and routes through the TS provider. Use when you need programmatic composition (per-tenant variants, generated fields) or constructs PSL doesn't yet express (e.g. registering a parameterised extension type — see pgvector's contract).
@@ -68,7 +68,7 @@ These symptoms are not structured envelopes — route on the message text and ch
68
68
  | Symptom | Next move |
69
69
  |---|---|
70
70
  | `TypeError: db.end is not a function` | The runtime client does not expose `db.end()` — that's the `node-postgres` pool API (`pool.end()`). The right call is `await db.close()`. See `references/runtime.md` § *Running as a script (teardown)*. |
71
- | Script hangs after queries print / process won't exit | On Postgres the façade-owned `pg.Pool` keeps the event loop alive. Call `await db.close()` before the script returns, or `await using db = postgres<Contract>(...)` at the top of a script module (do NOT put `await using` inside a request handler — block-scoped, would close per-request). See `references/runtime.md` § *Running as a script (teardown)*. |
71
+ | Script hangs after queries print / process won't exit | On Postgres the façade-owned `pg.Pool` keeps the event loop alive. Call `await db.close()` before the script returns, or `await using db = postgres({ contract, ... })` at the top of a script module (do NOT put `await using` inside a request handler — block-scoped, would close per-request). See `references/runtime.md` § *Running as a script (teardown)*. |
72
72
  | `Error('Postgres client is closed')` / `Error('SQLite client is closed')` / `Error('Mongo client is closed')` | The client was closed via `db.close()` (terminal state). Remove the early `close()`, reorder so `close()` runs last after all queries, or construct a new `db` if reconnection is intended. See `references/runtime.md` § *Running as a script (teardown)*. |
73
73
 
74
74
  ## Routing — symptom and code → next move
@@ -114,7 +114,7 @@ The single source of truth: read the envelope, find the row by `code`, follow th
114
114
  | `RUNTIME.ABORTED` (`details.phase` = `encode\|decode\|stream\|beforeEncode\|onRow`) | Runtime, when an `AbortSignal` fires mid-execute | Cancellation, not a bug; surface to the caller. |
115
115
  | `SqlQueryError` (no dotted code) | Raw-SQL paths surfacing a driver error | Inspect `sqlState` + `constraint` + `table` + `column`. Postgres `23505` = unique violation, `23503` = foreign-key violation, etc. Fix the data or the schema. |
116
116
  | TypeScript error mentioning a capability (e.g. `returning()` not on the type, `include` of a many-relation off a many-load) | Authoring-time, before any envelope fires | Capability gates are declared in the **contract** (`capabilities` block, namespaced by target/family), not in `prisma.config.ts`. Route to `references/contract.md` for capability declaration and to `references/queries.md` for which method gates on which capability. Re-emit (`pnpm prisma contract emit`) after enabling. |
117
- | TypeScript error mentioning a missing field/method on `db.orm.<ns>.<Model>` or a stale `Contract` shape | Authoring-time | Re-emit (`pnpm prisma contract emit`); confirm `db.ts` instantiates with `postgres<Contract>(...)` (the single type parameter propagates the contract types). See `references/runtime.md` and `references/contract.md`. |
117
+ | TypeScript error mentioning a missing field/method on `db.orm.<ns>.<Model>` or a stale `Contract` shape | Authoring-time | Re-emit (`pnpm prisma contract emit`); confirm `db.ts` builds its contract with `contractFromJson<Contract>(contractJson)` and passes it to `postgres({ contract })` (the client infers the contract types from it). See `references/runtime.md` and `references/contract.md`. |
118
118
 
119
119
  If the envelope's `code` is not in this table, follow the envelope's `fix` field literally — it's the framework's first-party next move. If `fix` is empty or unhelpful, escalate via `references/feedback.md`.
120
120
 
@@ -263,17 +263,18 @@ MigrationCLI.run(import.meta.url, M);
263
263
 
264
264
  Replace both `placeholder(...)` calls with query-plan closures built from `endContract`. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
265
265
 
266
- Build the query builder against `endContract` so the storage hashes line up — using a different contract reference raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres<End>({ contractJson: endContract })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with only the two `placeholder(...)` arrows replaced (the operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered):
266
+ Build the query builder against `endContract` so the storage hashes line up — using a different contract reference raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with only the two `placeholder(...)` arrows replaced (the operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered):
267
267
 
268
268
  ```typescript
269
269
  import { col, Migration, MigrationCLI } from '@internal/postgres/migration';
270
270
  import postgres from '@internal/postgres/runtime';
271
+ import { contractFromJson } from '@internal/postgres/static';
271
272
  import type { Contract as End } from '../../snapshots/93f07d1b…c9e1e5a2/contract';
272
273
  import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };
273
274
  import type { Contract as Start } from '../../snapshots/f62a4154…d07dddc/contract';
274
275
  import startContract from '../../snapshots/f62a4154…d07dddc/contract.json' with { type: 'json' };
275
276
 
276
- const { sql: db, contract } = postgres<End>({ contractJson: endContract });
277
+ const { sql: db, contract } = postgres({ contract: contractFromJson<End>(endContract) });
277
278
 
278
279
  export default class M extends Migration<Start, End> {
279
280
  override readonly startContractJson = startContract;
@@ -6,7 +6,7 @@ Shared concepts (result consumption, script teardown, cross-target pitfalls, cap
6
6
 
7
7
  ## Key Concepts
8
8
 
9
- **Mongo** (`mongo<Contract>(...)` from `@internal/mongo/runtime`):
9
+ **Mongo** (`mongo({ contract, ... })` from `@internal/mongo/runtime`):
10
10
 
11
11
  - **`db.orm.<root>`** — ORM, lowercased plural contract root (`db.orm.users`, `db.orm.posts`). Same fluent chaining; `.where({ field: value })` object equality is the idiomatic filter form.
12
12
  - **`db.query`** — typed aggregation-pipeline builder. Start with `db.query.from('<root>')`, chain `.match(...)` / `.project(...)` / `.group(...)` / `.lookup(...)`, terminal with `.build()`. Run via `(await db.runtime()).query(plan)` for anything that returns documents; `execute(plan)` is only for a write you want an affected count from, and it throws `RUNTIME.MONGO_STATISTICS_UNSUPPORTED` on a find or aggregate.
@@ -6,7 +6,7 @@ Shared concepts (result consumption, script teardown, cross-target pitfalls, cap
6
6
 
7
7
  ## Key Concepts
8
8
 
9
- **Postgres** (`postgres<Contract>(...)` from `@internal/postgres/runtime`):
9
+ **Postgres** (`postgres({ contract, ... })` from `@internal/postgres/runtime`):
10
10
 
11
11
  - **`db.orm.<ns>.<Model>`** — ORM, PascalCase model name (`db.orm.public.User`). Fluent `.where(...).select(...).orderBy(...).all()`, fully typed against `Contract`. Default lane for CRUD with relations.
12
12
  - **`db.sql.<ns>.<table>`** — SQL builder, lowercase storage name (`db.sql.public.user`). Produces a *plan*. A plan that returns rows (`select`, or a write with `.returning(...)`) runs through `db.runtime().query(plan)`; a write with no `RETURNING` runs through `db.runtime().execute(plan)`, which resolves `{ affectedRows }`. Use when the ORM is too high-level — explicit `JOIN`, computed projections, set operations, window functions.
@@ -32,7 +32,7 @@ This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, S
32
32
  - **Contract**: the data model. Authored as `contract.prisma` (PSL, the canonical surface) or `contract.ts` (TypeScript builder). The framework reads it and emits two artefacts: `contract.json` (runtime IR) and `contract.d.ts` (types).
33
33
  - **Target**: the backing store. Today: `postgres` or `mongodb`. Picked at `init` time; baked into the `@internal/<target>` façade the scaffold imports from.
34
34
  - **Authoring mode**: how you write the contract. `psl` (Prisma Schema Language, default) or `typescript` (programmatic builder, optionally paired with the Vite plugin for auto-emit during `vite dev` — see `references/build.md`).
35
- - **Façade packages.** The scaffold installs exactly one façade per target — `@internal/postgres` (or `@internal/mongo`). User code imports from façade subpaths (`@internal/postgres/config`, `@internal/postgres/runtime`, `@internal/postgres/contract-builder`). The façade bakes in the family / target / adapter / driver wiring; never reach past it. See `references/contract.md` for the full list.
35
+ - **Façade packages.** The scaffold installs exactly one façade per target — `@internal/postgres` (or `@internal/mongo`). User code imports from façade subpaths (`@internal/postgres/config`, `@internal/postgres/runtime`, `@internal/postgres/static`, `@internal/postgres/contract-builder`). The façade bakes in the family / target / adapter / driver wiring; never reach past it. See `references/contract.md` for the full list.
36
36
  - **`db.ts`**: the runtime entry point. Lives next to the contract source at `src/prisma/db.ts`. Imports the contract artefacts and exports a `db` value the rest of the app uses.
37
37
  - **Marker**: a row in the `prisma_contract.marker` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets PN detect drift between contract and live DB. Created by `db init` (greenfield / first-touch orientation) or `db sign` (brownfield).
38
38
 
@@ -27,8 +27,8 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
27
27
 
28
28
  ## Key Concepts
29
29
 
30
- - **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@internal/<target>` façade (`@internal/postgres/runtime`, `@internal/sqlite/runtime`, or `@internal/mongo/runtime`), the contract artefacts (`contract.json` + the `Contract` type from `contract.d.ts`), and any middleware. Exports a `db` value the rest of your app imports. On a per-request runtime, `db.ts` imports `postgresServerless` from `@internal/postgres/serverless` instead and exports the serverless client `postgres`; see *Workflow — Serverless and per-request runtimes*.
31
- - **The façade's runtime factory is the only surface user-authored `db.ts` imports from.** Each factory is a *default* export. For Postgres: `import postgres from '@internal/postgres/runtime'`; SQLite: `import sqlite from '@internal/sqlite/runtime'`; Mongo: `import mongo from '@internal/mongo/runtime'`. The factory signature is `<Target><Contract>(options)` — a single type parameter (the `Contract` type from `contract.d.ts`), and one options object.
30
+ - **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@internal/<target>` façade (`@internal/postgres/runtime`, `@internal/sqlite/runtime`, or `@internal/mongo/runtime`), `contractFromJson` from the same façade's `/static` entry point, the contract artefacts (`contract.json` + the `Contract` type from `contract.d.ts`), and any middleware. Exports the typed `contract` and a `db` value the rest of your app imports. On a per-request runtime, `db.ts` imports `postgresServerless` from `@internal/postgres/serverless` instead and exports the serverless client `postgres`; see *Workflow — Serverless and per-request runtimes*.
31
+ - **`db.ts` imports only from the façade's `/runtime` and `/static` entry points.** Each factory is a *default* export. For Postgres: `import postgres from '@internal/postgres/runtime'`; SQLite: `import sqlite from '@internal/sqlite/runtime'`; Mongo: `import mongo from '@internal/mongo/runtime'`. The factory takes one options object and no type argument: it infers the contract type from `contract`. Turn the emitted JSON into a typed value once with `contractFromJson<Contract>(contractJson)` from the façade's `/static` entry point (`@internal/postgres/static`, `@internal/sqlite/static`, `@internal/mongo/static`; Supabase uses the Postgres one). That call is the only place you write the `Contract` type argument. A contract written in TypeScript with `defineContract` is already a typed value and goes to `{ contract }` directly. A contract value is validated once, however many clients use it.
32
32
  - **Lazy connect.** The factory does not connect to the database synchronously. `db.sql` and `db.orm` are available immediately; the driver / pool is instantiated on the first call that needs a runtime (or when you explicitly call `await db.connect({ url })`, which binds the client to that URL), and the pool opens its first database connection on the first query. This is why `db.ts` can be imported in modules that load before the env is ready.
33
33
  - **Middleware composes in order.** Every hook runs in the order of the `middleware: [...]` array — the first middleware's `beforeEncode` sees the statement first, and `intercept.onQuery` handlers are consulted in registration order with the first non-`undefined` result winning. Register a cache first so it gets first claim on a hit. Every middleware's `activityEnded` still fires on a cache hit, with `result.source: 'middleware'`.
34
34
  - **`prisma.config.ts` vs `.env`.** The config (`definePrismaConfig({ orm: ormConfig({ contract, db, extensions, migrations }) })` — see `references/contract.md`) is for static project shape: contract path, installed extensions, migrations directory, default connection string. `.env` is for per-environment values (`DATABASE_URL`, secrets). Nothing reads `.env` on its own: the scaffolded `prisma.config.ts` starts with `import 'dotenv/config'`, and that import is what loads `.env` into `process.env` before the config (and the CLI running it) reads `process.env['DATABASE_URL']`. Keep the import; a config without it sees no `.env` values. Hardcoding `DATABASE_URL` in the config file leaks credentials and bypasses per-env overrides.
@@ -36,18 +36,21 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
36
36
 
37
37
  ## Workflow — Basic `db.ts`
38
38
 
39
- The concept: `db.ts` is the seam between the emitted contract artefacts (target-shaped) and the runtime that executes queries against them. Three imports are required — the runtime factory, the `Contract` type (so the static query surfaces are typed), and the JSON artefact (so the runtime validates the structure at construct time).
39
+ The concept: `db.ts` is the seam between the emitted contract artefacts (target-shaped) and the runtime that executes queries against them. Four imports are required — the runtime factory, `contractFromJson` from the façade's `/static` entry point, the `Contract` type (so the static query surfaces are typed), and the JSON artefact (which `contractFromJson` validates once).
40
40
 
41
41
  `init` scaffolds something like this (for `--target postgres`):
42
42
 
43
43
  ```typescript
44
44
  // src/prisma/db.ts
45
45
  import postgres from '@internal/postgres/runtime';
46
+ import { contractFromJson } from '@internal/postgres/static';
46
47
  import type { Contract } from './contract.d';
47
48
  import contractJson from './contract.json' with { type: 'json' };
48
49
 
49
- export const db = postgres<Contract>({
50
- contractJson,
50
+ export const contract = contractFromJson<Contract>(contractJson);
51
+
52
+ export const db = postgres({
53
+ contract,
51
54
  url: process.env['DATABASE_URL']!,
52
55
  });
53
56
  ```
@@ -56,7 +59,7 @@ export const db = postgres<Contract>({
56
59
 
57
60
  Three things to know:
58
61
 
59
- - **`<Contract>` type parameter is required.** Without it, the static surfaces collapse to a generic shape and you lose autocomplete on model names. Always import `Contract` from the emitted `./contract.d.ts`.
62
+ - **Name `Contract` on `contractFromJson`, not on the client.** `contractFromJson<Contract>(contractJson)` is where the JSON gets its type; without the type argument, the static surfaces collapse to a generic shape and you lose autocomplete on model names. Always import `Contract` from the emitted `./contract.d.ts`. The clients take no type argument and no `contractJson` option.
60
63
  - **`with { type: 'json' }` is required.** Node's ESM JSON-import-attribute spec. Without it, the import errors.
61
64
  - **`url` is optional at construct time.** If `DATABASE_URL` is not set when `db.ts` loads, the factory still returns a client; you can call `await db.connect({ url })` later. The factory throws lazily — only when a runtime is actually needed.
62
65
 
@@ -84,10 +87,9 @@ await db.close();
84
87
  ```typescript
85
88
  // src/scripts/hello.ts — top-level await in a script module
86
89
  import postgres from '@internal/postgres/runtime';
87
- import type { Contract } from '../prisma/contract.d';
88
- import contractJson from '../prisma/contract.json' with { type: 'json' };
90
+ import { contract } from '../prisma/db';
89
91
 
90
- await using db = postgres<Contract>({ contractJson, url: process.env.DATABASE_URL! });
92
+ await using db = postgres({ contract, url: process.env.DATABASE_URL! });
91
93
 
92
94
  const user = await db.orm.public.User.first();
93
95
  console.log(user);
@@ -103,7 +105,7 @@ This is the most important rule in this section. `await using db = postgres(...)
103
105
  ```typescript
104
106
  // DO NOT do this — closes the pool after every request.
105
107
  app.get('/users', async (req, res) => {
106
- await using db = postgres<Contract>({ contractJson, url: process.env.DATABASE_URL! });
108
+ await using db = postgres({ contract, url: process.env.DATABASE_URL! });
107
109
  const users = await db.orm.public.User.all();
108
110
  res.json(users);
109
111
  });
@@ -113,7 +115,7 @@ The right server pattern is a **module-level singleton** in `db.ts`, imported by
113
115
 
114
116
  ```typescript
115
117
  // src/prisma/db.ts — constructed once, lives for the process
116
- export const db = postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
118
+ export const db = postgres({ contract, url: process.env.DATABASE_URL });
117
119
 
118
120
  // src/routes/users.ts
119
121
  import { db } from '../prisma/db';
@@ -142,10 +144,12 @@ The concept: a per-request runtime (Cloudflare Workers + Hyperdrive, AWS Lambda,
142
144
  ```typescript
143
145
  // src/prisma/db.ts — the serverless client: module scope, built once per isolate, holds no database connection
144
146
  import postgresServerless from '@internal/postgres/serverless';
147
+ import { contractFromJson } from '@internal/postgres/static';
145
148
  import type { Contract } from './contract.d';
146
149
  import contractJson from './contract.json' with { type: 'json' };
147
150
 
148
- export const postgres = postgresServerless<Contract>({ contractJson });
151
+ export const contract = contractFromJson<Contract>(contractJson);
152
+ export const postgres = postgresServerless({ contract });
149
153
 
150
154
  // src/worker.ts
151
155
  import { postgres } from './prisma/db';
@@ -215,12 +219,15 @@ Both are exported from the façade's `family-runtime` subpath — `@prisma/orm-p
215
219
 
216
220
  ```typescript
217
221
  import postgres from '@internal/postgres/runtime';
222
+ import { contractFromJson } from '@internal/postgres/static';
218
223
  import { budgets, lints } from '@prisma/orm-postgres/family-runtime';
219
224
  import type { Contract } from './contract.d';
220
225
  import contractJson from './contract.json' with { type: 'json' };
221
226
 
222
- export const db = postgres<Contract>({
223
- contractJson,
227
+ export const contract = contractFromJson<Contract>(contractJson);
228
+
229
+ export const db = postgres({
230
+ contract,
224
231
  url: process.env['DATABASE_URL'],
225
232
  middleware: [
226
233
  lints({
@@ -259,8 +266,8 @@ import {
259
266
  export const cache = createCacheMiddleware({
260
267
  store: createInMemoryCacheStore({ maxEntries: 1_000, ttlMs: 60_000 }),
261
268
  });
262
- export const db = postgres<Contract>({
263
- contractJson,
269
+ export const db = postgres({
270
+ contract,
264
271
  url: process.env['DATABASE_URL']!,
265
272
  middleware: [cache, lints(), budgets({ maxRows: 10_000 })],
266
273
  });
@@ -298,8 +305,8 @@ The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pr
298
305
 
299
306
  ```typescript
300
307
  // Default — URL string, factory constructs the pool.
301
- postgres<Contract>({
302
- contractJson,
308
+ postgres({
309
+ contract,
303
310
  url: process.env['DATABASE_URL'],
304
311
  poolOptions: {
305
312
  connectionTimeoutMillis: 20_000,
@@ -312,7 +319,7 @@ postgres<Contract>({
312
319
  // BYO pool — pass a pg.Pool you already created.
313
320
  import { Pool } from 'pg';
314
321
  const pool = new Pool({ connectionString: process.env['DATABASE_URL'] });
315
- postgres<Contract>({ contractJson, pg: pool });
322
+ postgres({ contract, pg: pool });
316
323
  ```
317
324
 
318
325
  The `url` and `pg` keys are mutually exclusive at the type level; passing both errors.
@@ -326,8 +333,8 @@ The concept: one `DATABASE_URL` per environment; the rest of the `db.ts` shape i
326
333
  ```typescript
327
334
  const isProd = process.env['NODE_ENV'] === 'production';
328
335
 
329
- export const db = postgres<Contract>({
330
- contractJson,
336
+ export const db = postgres({
337
+ contract,
331
338
  url: process.env['DATABASE_URL']!,
332
339
  middleware: isProd
333
340
  ? [slowQueryWarning({ thresholdMs: 250 })]
@@ -363,10 +370,12 @@ After the switch (Mongo):
363
370
  ```typescript
364
371
  // src/prisma/db.ts (Mongo)
365
372
  import mongo from '@internal/mongo/runtime';
373
+ import { contractFromJson } from '@internal/mongo/static';
366
374
  import type { Contract } from './contract.d';
367
375
  import contractJson from './contract.json' with { type: 'json' };
368
376
 
369
- export const db = mongo<Contract>({ contractJson, url: process.env['DATABASE_URL'] });
377
+ export const contract = contractFromJson<Contract>(contractJson);
378
+ export const db = mongo({ contract, url: process.env['DATABASE_URL'] });
370
379
  ```
371
380
 
372
381
  SQLite:
@@ -374,10 +383,12 @@ SQLite:
374
383
  ```typescript
375
384
  // src/prisma/db.ts (SQLite)
376
385
  import sqlite from '@internal/sqlite/runtime';
386
+ import { contractFromJson } from '@internal/sqlite/static';
377
387
  import type { Contract } from './contract.d';
378
388
  import contractJson from './contract.json' with { type: 'json' };
379
389
 
380
- export const db = sqlite<Contract>({ contractJson, path: 'app.db' });
390
+ export const contract = contractFromJson<Contract>(contractJson);
391
+ export const db = sqlite({ contract, path: 'app.db' });
381
392
  ```
382
393
 
383
394
  `path` is optional at construct time (you can call `db.connect({ path })` later); omit it and the façade still returns a client. The SQLite façade exposes the same `db.sql`, `db.orm`, `db.transaction(...)`, `db.close()`, and `[Symbol.asyncDispose]` surfaces as Postgres, with one addressing difference: SQLite has no schemas, so `db.sql` and `db.orm` are the unbound namespace itself (`db.orm.User`, `db.sql.user`) instead of Postgres's `db.orm.public.User` / `db.sql.public.user`. The Mongo façade shares `db.orm`, `db.close()`, and `[Symbol.asyncDispose]` but has no `db.sql` and no `db.transaction(...)`.
@@ -396,13 +407,13 @@ The runtime side (this skill) is the same regardless: `db.ts` reads `contract.js
396
407
  ## Common Pitfalls
397
408
 
398
409
  1. **Hardcoding `DATABASE_URL` in `prisma.config.ts`.** Leaks credentials; bypasses per-environment overrides. Use `.env`.
399
- 2. **Omitting the `<Contract>` type parameter** in `postgres<Contract>(...)`. Without it, static surfaces collapse to a generic shape and you lose autocomplete for models. There is no second type parameter — the older two-param signature (`postgres<Contract, TypeMaps>`) is gone.
410
+ 2. **Writing the type argument on the client, or passing `contractJson`.** `postgres<Contract>({ contractJson })` no longer compiles: the clients take `{ contract }` and infer its type. Write `contractFromJson<Contract>(contractJson)` and pass the result. Omitting `<Contract>` there collapses the static surfaces to a generic shape and you lose autocomplete for models.
400
411
  3. **Forgetting `with { type: 'json' }` on the contract import.** Required by Node's ESM JSON-import-attribute spec.
401
412
  4. **Middleware order matters.** Registration order is hook order; put the cache first so its `intercept.onActivity` and `intercept.onQuery` are consulted first.
402
413
  5. **Importing middleware from a non-existent package or subpath.** There is no `@internal/postgres/middleware` subpath and no `@internal/middleware-telemetry` package. `lints` / `budgets` / `SqlMiddleware` come from `@prisma/orm-postgres/family-runtime`; the cache comes from `@prisma/orm-extension-middleware-cache`; a query log or telemetry hook is a custom `activityEnded` middleware (above).
403
414
  6. **Confabulating lint / budget option names.** Lints take `severities` (with the five keys above), not `requireWhere` / `maxRowsWithoutLimit`. Budgets use `maxLatencyMs` (not `maxDurationMs`) plus `maxRows` / `defaultTableRows` / `tableRows`. When in doubt, read the source.
404
415
  7. **Switching targets without re-emitting.** The contract artefacts are target-shaped; emit after the target change.
405
- 8. **Script hangs after queries finish on Postgres.** The `pg.Pool` keeps Node's event loop alive. Solution: `await db.close()` before the script returns, or `await using db = postgres<Contract>(...)` at the top of a script module. Do not put `await using db = postgres(...)` inside a request handler — it's block-scoped and would close the pool after every request. The right server pattern is a module-level singleton in `db.ts` that lives for the process lifetime. On a per-request runtime, use `postgresServerless()` and `await using db = await postgres.connect({ url })` in the handler instead (see *Workflow — Serverless and per-request runtimes*).
416
+ 8. **Script hangs after queries finish on Postgres.** The `pg.Pool` keeps Node's event loop alive. Solution: `await db.close()` before the script returns, or `await using db = postgres({ contract, ... })` at the top of a script module. Do not put `await using db = postgres(...)` inside a request handler — it's block-scoped and would close the pool after every request. The right server pattern is a module-level singleton in `db.ts` that lives for the process lifetime. On a per-request runtime, use `postgresServerless()` and `await using db = await postgres.connect({ url })` in the handler instead (see *Workflow — Serverless and per-request runtimes*).
406
417
 
407
418
  ## What Prisma 8 doesn't do yet
408
419
 
@@ -417,15 +428,15 @@ This skill is intentionally body-only; `prisma orm init --help`, the target `def
417
428
 
418
429
  ## Checklist
419
430
 
420
- - [ ] `db.ts` imports the runtime factory from `@internal/<target>/runtime` (`postgres`, `sqlite`, or `mongo`) and the `Contract` type from `./contract.d`.
431
+ - [ ] `db.ts` imports the runtime factory from `@internal/<target>/runtime` (`postgres`, `sqlite`, or `mongo`), `contractFromJson` from `@internal/<target>/static`, and the `Contract` type from `./contract.d`.
421
432
  - [ ] `with { type: 'json' }` on the contract JSON import.
422
- - [ ] `<Contract>` is the single type parameter on `postgres<Contract>(...)` (no second parameter).
433
+ - [ ] `Contract` is named once, on `contractFromJson<Contract>(contractJson)`, and the client gets `{ contract }` with no type argument.
423
434
  - [ ] `DATABASE_URL` lives in `.env`, not in `prisma.config.ts`.
424
435
  - [ ] Middleware ordered intentionally (cache first when used).
425
436
  - [ ] `lints` / `budgets` imported from `@prisma/orm-postgres/family-runtime` and using the verified option keys (`severities`, `maxLatencyMs`, `maxRows`, `tableRows`).
426
437
  - [ ] Per-env divergence (if any) gated by `NODE_ENV` or similar.
427
438
  - [ ] Did NOT hardcode credentials in any committed file.
428
- - [ ] Did NOT confabulate a `@internal/postgres/middleware` subpath, a `@internal/middleware-telemetry` package, a `@internal/postgres-extension-audit` package, or a second type parameter on `postgres<...>`.
439
+ - [ ] Did NOT confabulate a `@internal/postgres/middleware` subpath, a `@internal/middleware-telemetry` package, a `@internal/postgres-extension-audit` package, or a type argument or `contractJson` option on `postgres(...)`.
429
440
  - [ ] Did NOT claim `db.transaction(...)` exists on the Mongo façade — only Postgres and SQLite expose it.
430
441
  - [ ] Did NOT confabulate read-replica / multi-DB / extra pool config — pointed at *What Prisma 8 doesn't do yet* and routed to `references/feedback.md`.
431
442
  - [ ] For build-system / dev-server prompts (Vite plugin, Next.js plugin, …) routed to `references/build.md`.
@@ -108,11 +108,14 @@ The concept: instead of the stock `postgres()` factory, a Supabase app builds it
108
108
  ```typescript
109
109
  // src/prisma/db.ts
110
110
  import { supabase } from '@internal/extension-supabase/runtime';
111
+ import { contractFromJson } from '@internal/postgres/static';
111
112
  import type { Contract } from './contract.d';
112
113
  import contractJson from './contract.json' with { type: 'json' };
113
114
 
114
- export const db = await supabase<Contract>({
115
- contractJson,
115
+ export const contract = contractFromJson<Contract>(contractJson);
116
+
117
+ export const db = await supabase({
118
+ contract,
116
119
  url: process.env['DATABASE_URL'], // direct Postgres connection — see pitfalls
117
120
  jwksUrl: process.env['SUPABASE_JWKS_URL'], // https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json
118
121
  // Legacy HS256 projects use jwtSecret: process.env['SUPABASE_JWT_SECRET'] instead — exactly one of the two.
@@ -223,7 +226,7 @@ The concept: the runtime needs a **direct, session-capable** Postgres connection
223
226
  - [ ] `extensions: [supabasePack]` (the `pack` export) in `ormConfig({...})` inside `definePrismaConfig({ orm: ... })`.
224
227
  - [ ] Cross-space FK typed `supabase:auth.AuthUser` with explicit `fields` / `references` (+ `onDelete` if wanted).
225
228
  - [ ] Every policy target model carries `@@rls`; predicates quote camelCase columns and cast for `auth.uid()`.
226
- - [ ] `db.ts` uses `await supabase<Contract>({ contractJson, url, jwksUrl | jwtSecret })` — exactly one JWT key source; `jwksUrl` for current projects, `jwtSecret` only for legacy HS256.
229
+ - [ ] `db.ts` uses `await supabase({ contract, url, jwksUrl | jwtSecret })`, with `contract` from `contractFromJson<Contract>(contractJson)` of `@internal/postgres/static` — exactly one JWT key source; `jwksUrl` for current projects, `jwtSecret` only for legacy HS256.
227
230
  - [ ] Queries go through a `RoleBoundDb` from `asUser` / `asAnon` / `asServiceRole`; `asUser` is awaited.
228
231
  - [ ] `auth.*` / `storage.*` reads go through `asServiceRole().supabase` only, after the one-time narrow grant (`GRANT USAGE ON SCHEMA auth` + `GRANT SELECT` on the tables you read).
229
232
  - [ ] No per-table grants added for your own `public` tables — Supabase default privileges cover them; RLS does the protecting.
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-BOF4sYko-PDYW__5e.d.mts","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-BOF4sYko.d.mts"],"mappings":";;;;;;;;;;;KAUK,aAAa,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC5E,aAAa,kBAAkB,SAAS,eAAe,gBAAgB,kBAAkB;UACpF,oBAAoB,kBAAkB,SAAS;WAC9C,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,aAAa;WACpB,KAAK,aAAa;WAClB,KAAK,QAAQ;;iBAEP,aAAa,kBAAkB,SAAS,aAAa;WAC3D;WACA,sBAAsB,8BAA8B;IAC3D,oBAAoB;;;KAGnB;KACA,UAAU,kBAAkB,SAAS,eAAe,kBAAkB,IAAI;KAC1E,WAAW,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC1E,WAAW,kBAAkB,SAAS,eAAe,UAAU,kBAAkB;UAC5E,yBAAyB,kBAAkB,SAAS,qBAAqB;WACxE,KAAK,WAAW;WAChB,KAAK,WAAW;WAChB,OAAO,oBAAoB;;UAE5B,aAAa,kBAAkB,SAAS;WACvC,KAAK,WAAW;WAChB,KAAK,WAAW;WAChB,OAAO,oBAAoB;WAC3B,KAAK,QAAQ;WACb,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,4BAA4B;EAC5C,QAAQ;aACG;MACP,QAAQ;EACZ,WAAW;EACX,QAAQ,UAAU,YAAY,KAAK,UAAU,eAAe,8BAA8B,WAAW,iBAAiB,kBAAkB,YAAY,aAAa,GAAG,WAAW,QAAQ,eAAe,OAAO,IAAI,QAAQ,aAAa,sBAAsB,GAAG,KAAK;EACpQ,YAAY,GAAG,KAAK,IAAI,yBAAyB,eAAe,YAAY,KAAK,QAAQ;EACzF,SAAS;GACR,OAAO,iBAAiB;;UAEjB;WACC,sBAAsB,8BAA8B;WACpD,sBAAsB;WACtB,eAAe;WACf,MAAM;;KAEZ,0BAA0B,kBAAkB,SAAS;WAC/C;IACP;WACO,UAAU;WACV;;KAEN,8BAA8B,kBAAkB,SAAS;WACnD;WACA,YAAY;IACnB;WACO;WACA;;KAEN,cAAc,kBAAkB,SAAS,eAAe,0BAA0B,aAAa,8BAA8B;iBACjH,OAAO,kBAAkB,SAAS,aAAa,SAAS,0BAA0B,aAAa,aAAa;iBAC5G,OAAO,kBAAkB,SAAS,aAAa,SAAS,8BAA8B,aAAa,aAAa"}
@@ -1,46 +0,0 @@
1
- import sqliteAdapter from "@prisma/orm-target-sqlite/adapter/runtime";
2
- import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
3
- import { createRawLane, sql } from "@prisma/orm-family-sql/builder/runtime";
4
- import { createExecutionContext, createSqlExecutionStack } from "@prisma/orm-family-sql/runtime";
5
- import sqliteTarget, { SqliteContractSerializer } from "@prisma/orm-target-sqlite/target/runtime";
6
- import { assertDefined } from "@prisma/orm-framework/utils/assertions";
7
- import { blindCast } from "@prisma/orm-framework/utils/casts";
8
- import { buildNamespacedEnums } from "@prisma/orm-framework/contract/enum-accessor";
9
- //#region ../../../3-extensions/sqlite/dist/sqlite-static-CX2elTbu.mjs
10
- function buildSqliteStaticContext(context, rawCodecInferer) {
11
- const sqlNamespace = sql({
12
- context,
13
- rawCodecInferer
14
- })[UNBOUND_NAMESPACE_ID];
15
- assertDefined(sqlNamespace, "the unbound namespace always exists on a sqlite builder output");
16
- const sqlDb = blindCast(sqlNamespace);
17
- const raw = createRawLane({
18
- context,
19
- rawCodecInferer
20
- });
21
- const enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];
22
- assertDefined(enums, "the unbound namespace always exists on a sqlite builder output");
23
- return {
24
- context,
25
- contract: context.contract,
26
- enums,
27
- sql: sqlDb,
28
- raw
29
- };
30
- }
31
- function sqliteStatic(options) {
32
- const contract = blindCast(new SqliteContractSerializer().deserializeContract(options.contractJson));
33
- const stack = createSqlExecutionStack({
34
- target: sqliteTarget,
35
- adapter: sqliteAdapter,
36
- extensions: options.extensions ?? []
37
- });
38
- return buildSqliteStaticContext(createExecutionContext({
39
- contract,
40
- stack
41
- }), stack.adapter.rawCodecInferer);
42
- }
43
- //#endregion
44
- export { sqliteStatic as n, buildSqliteStaticContext as t };
45
-
46
- //# sourceMappingURL=sqlite-static-CX2elTbu-CoM_gcs_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-static-CX2elTbu-CoM_gcs_.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-static-CX2elTbu.mjs"],"sourcesContent":["import sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { createExecutionContext, createSqlExecutionStack } from \"@internal/sql-runtime\";\nimport sqliteTarget, { SqliteContractSerializer } from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\n//#region src/static/sqlite-static.ts\nfunction buildSqliteStaticContext(context, rawCodecInferer) {\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\tconst sqlDb = blindCast(sqlNamespace);\n\tconst raw = createRawLane({\n\t\tcontext,\n\t\trawCodecInferer\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract: context.contract,\n\t\tenums,\n\t\tsql: sqlDb,\n\t\traw\n\t};\n}\nfunction sqliteStatic(options) {\n\tconst contract = blindCast(new SqliteContractSerializer().deserializeContract(options.contractJson));\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildSqliteStaticContext(createExecutionContext({\n\t\tcontract,\n\t\tstack\n\t}), stack.adapter.rawCodecInferer);\n}\n//#endregion\nexport { sqliteStatic as n, buildSqliteStaticContext as t };\n\n//# sourceMappingURL=sqlite-static-CX2elTbu.mjs.map"],"mappings":";;;;;;;;;AASA,SAAS,yBAAyB,SAAS,iBAAiB;CAC3D,MAAM,eAAe,IAAI;EACxB;EACA;CACD,CAAC,CAAC,CAAC;CACH,cAAc,cAAc,gEAAgE;CAC5F,MAAM,QAAQ,UAAU,YAAY;CACpC,MAAM,MAAM,cAAc;EACzB;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,SAAS,YAAY,QAAQ,eAAe,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;CACzI,cAAc,OAAO,gEAAgE;CACrF,OAAO;EACN;EACA,UAAU,QAAQ;EAClB;EACA,KAAK;EACL;CACD;AACD;AACA,SAAS,aAAa,SAAS;CAC9B,MAAM,WAAW,UAAU,IAAI,yBAAyB,CAAC,CAAC,oBAAoB,QAAQ,YAAY,CAAC;CACnG,MAAM,QAAQ,wBAAwB;EACrC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,yBAAyB,uBAAuB;EACtD;EACA;CACD,CAAC,GAAG,MAAM,QAAQ,eAAe;AAClC"}