viborm 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/adapters.mjs +1 -1
  3. package/dist/bun-sql.d.mts +1 -1
  4. package/dist/bun-sql.mjs +1 -1
  5. package/dist/bun-sqlite.d.mts +1 -1
  6. package/dist/bun-sqlite.mjs +1 -1
  7. package/dist/cache/cloudflare-kv.d.mts +1 -1
  8. package/dist/cache/memory.d.mts +1 -1
  9. package/dist/cache.d.mts +1 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/{client-3FqgR4eS.d.mts → client-D-XiaClb.d.mts} +1 -1
  12. package/dist/{client-DUulrWw5.mjs → client-DACEO6tS.mjs} +2 -2
  13. package/dist/client-DACEO6tS.mjs.map +1 -0
  14. package/dist/client.d.mts +1 -1
  15. package/dist/config.d.mts +1 -1
  16. package/dist/d1.d.mts +1 -1
  17. package/dist/d1.mjs +1 -1
  18. package/dist/d1.mjs.map +1 -1
  19. package/dist/driver.d.mts +1 -1
  20. package/dist/{index-oVv9RLt5.d.mts → index-Ci8b13Lm.d.mts} +18 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +1 -1
  23. package/dist/instrumentation.d.mts +1 -1
  24. package/dist/instrumentation.mjs +1 -1
  25. package/dist/libsql.d.mts +1 -1
  26. package/dist/libsql.mjs +1 -1
  27. package/dist/migrations/mysql.d.mts +4 -4
  28. package/dist/migrations/postgres.d.mts +4 -4
  29. package/dist/migrations/sqlite.d.mts +4 -4
  30. package/dist/migrations/tenant.d.mts +2 -2
  31. package/dist/migrations.d.mts +4 -4
  32. package/dist/mysql2.d.mts +1 -1
  33. package/dist/mysql2.mjs +1 -1
  34. package/dist/neon-http.d.mts +1 -1
  35. package/dist/neon-http.mjs +1 -1
  36. package/dist/{object-store-C56-FLkl.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
  37. package/dist/permissions.d.mts +1 -1
  38. package/dist/pg.d.mts +1 -1
  39. package/dist/pg.mjs +1 -1
  40. package/dist/pglite.d.mts +1 -1
  41. package/dist/pglite.mjs +1 -1
  42. package/dist/planetscale.d.mts +1 -1
  43. package/dist/planetscale.mjs +1 -1
  44. package/dist/{planner-C3KX6S85.d.mts → planner-CUcPdJwD.d.mts} +1 -1
  45. package/dist/postgres.d.mts +1 -1
  46. package/dist/postgres.mjs +1 -1
  47. package/dist/schema/json.d.mts +1 -1
  48. package/dist/schema.d.mts +1 -1
  49. package/dist/soft-delete.d.mts +1 -1
  50. package/dist/{sqlite-adapter-B3dRr5fl.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
  51. package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
  52. package/dist/sqlite3.d.mts +1 -1
  53. package/dist/sqlite3.mjs +1 -1
  54. package/dist/validation.d.mts +1 -1
  55. package/dist/version-DLtcW9kn.mjs +2 -0
  56. package/dist/{version-B9azgPiR.mjs.map → version-DLtcW9kn.mjs.map} +1 -1
  57. package/package.json +1 -1
  58. package/dist/client-DUulrWw5.mjs.map +0 -1
  59. package/dist/sqlite-adapter-B3dRr5fl.mjs.map +0 -1
  60. package/dist/version-B9azgPiR.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $t as ExtensionResultConsumerState, A as Schema, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Gt as defineExtension, Ht as PlacedControl, I as Links, Kt as StatementContext, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Rt as defaultOmit, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Wn as IndexDefinition, Wt as ClientExtension, Y as VibSchema, Zt as ExtensionCacheState, _ as ObservationCompletion, _n as UnwrapPendingOperation, an as InferSelectInclude, dr as ObjectSchema, gn as PendingOperation, in as GroupByResultType, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as BatchPayload, on as RawOperation, qt as StatementHandler, rn as CountResultType, tn as AggregateResultType, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation } from "./index-oVv9RLt5.mjs";
1
+ import { $t as ExtensionResultConsumerState, A as Schema, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Gt as defineExtension, Ht as PlacedControl, I as Links, Kt as StatementContext, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Rt as defaultOmit, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Wn as IndexDefinition, Wt as ClientExtension, Y as VibSchema, Zt as ExtensionCacheState, _ as ObservationCompletion, _n as UnwrapPendingOperation, an as InferSelectInclude, dr as ObjectSchema, gn as PendingOperation, in as GroupByResultType, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as BatchPayload, on as RawOperation, qt as StatementHandler, rn as CountResultType, tn as AggregateResultType, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation } from "./index-Ci8b13Lm.mjs";
2
2
  export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type ClientTypeState, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-C3KX6S85.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-CUcPdJwD.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-Dw0FR78e.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
1
+ import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/d1.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,n}from"./normalized-result-BF7gr4_b.mjs";import{m as r}from"./error-mapping-6op318w6.mjs";import{p as i}from"./validation-gwZYm3Yn.mjs";import{a,n as o,r as s}from"./client-DUulrWw5.mjs";import{c,t as l}from"./driver-DseQwbsu.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-C5_KQPZn.mjs";import{t as p}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as m}from"./sqlite-adapter-B3dRr5fl.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,n){if(!t(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(t))||!t(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(n,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,r,i);return n(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,n}from"./normalized-result-BF7gr4_b.mjs";import{m as r}from"./error-mapping-6op318w6.mjs";import{p as i}from"./validation-gwZYm3Yn.mjs";import{a,n as o,r as s}from"./client-DACEO6tS.mjs";import{c,t as l}from"./driver-DseQwbsu.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-C5_KQPZn.mjs";import{t as p}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as m}from"./sqlite-adapter-CLWY4B8w.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,n){if(!t(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(t))||!t(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(n,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256,countsCascadedChanges:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,r,i);return n(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
2
2
  //# sourceMappingURL=d1.mjs.map
package/dist/d1.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`. D1 compiles\n // with an expression depth of 100 (\"Expression tree is too large\"):\n // relation filters nest as derived tables and conjunctions as balanced\n // trees (d1-permissions-verbs W-W3, W-W7). D1 refuses a statement over 100 KB: a\n // relation body a statement repeats is stated once (d1-permissions-placement\n // W-P10's update form), and a compound SELECT over 5 terms (\"too many terms\n // in compound SELECT\", witnessed by d1-permissions-statement-budget W-K2f).\n // D1 bounds no relations: it takes PostgreSQL's (256, Neki's) because\n // below it walks kept in place serve a few rows faster (a take-10 read at\n // 50x the permissions fixture: 0.6 ms, 5.2 ms as reaching sets), and above\n // it the compact form keeps the largest reads well inside 100 KB.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n deepExpressions: false,\n sharedRelationBodies: true,\n compoundSelectTerms: 5,\n relationsPerStatement: 256,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"scAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CAAC,CAC9C,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAGtE,SAAgB,8BACd,EAC2B,CAC3B,IAAM,EAAW,EAA2B,EAAI,CAChD,GAAI,CAAC,EAAU,MAAO,UACtB,IAAM,EAAW,gBAAgB,EAAS,CACpC,EAAU,GAAU,MAe1B,OAdK,EACD,EAAa,IAAI,EAAQ,CACpB,OAEL,EAAkB,IAAI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B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
1
+ {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`. D1 compiles\n // with an expression depth of 100 (\"Expression tree is too large\"):\n // relation filters nest as derived tables and conjunctions as balanced\n // trees (d1-permissions-verbs W-W3, W-W7). D1 refuses a statement over 100 KB: a\n // relation body a statement repeats is stated once (d1-permissions-placement\n // W-P10's update form), and a compound SELECT over 5 terms (\"too many terms\n // in compound SELECT\", witnessed by d1-permissions-statement-budget W-K2f).\n // D1 bounds no relations: it takes PostgreSQL's (256, Neki's) because\n // below it walks kept in place serve a few rows faster (a take-10 read at\n // 50x the permissions fixture: 0.6 ms, 5.2 ms as reaching sets), and above\n // it the compact form keeps the largest reads well inside 100 KB.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n deepExpressions: false,\n sharedRelationBodies: true,\n compoundSelectTerms: 5,\n relationsPerStatement: 256,\n countsCascadedChanges: true,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"scAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CAAC,CAC9C,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAGtE,SAAgB,8BACd,EAC2B,CAC3B,IAAM,EAAW,EAA2B,EAAI,CAChD,GAAI,CAAC,EAAU,MAAO,UACtB,IAAM,EAAW,gBAAgB,EAAS,CACpC,EAAU,GAAU,MAe1B,OAdK,EACD,EAAa,IAAI,EAAQ,CACpB,OAEL,EAAkB,IAAI,EAAQ,CACzB,EACJ,MAAM,EAAS,MAAQ,EAAE,CACzB,KAAM,GAAU,EAAM,OAAS,QAAU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,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
package/dist/driver.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { An as BatchQuery, Ci as UniqueConstraintError, En as sqliteResultParser, Li as isRetryableError, Mn as Dialect, Nn as QueryExecutionContext, Pn as QueryResult, Si as NotNullConstraintError, ai as FeatureNotSupportedError, bi as CheckConstraintError, f as SQLITE_MIGRATION_CAPABILITY, fi as QueryError, h as DriverResultParser, ii as ConnectionError, l as AnyDriver, ni as TransactionError, p as SqliteMigrationCapability, u as Driver, xi as ForeignKeyError } from "./index-oVv9RLt5.mjs";
1
+ import { An as BatchQuery, Ci as UniqueConstraintError, En as sqliteResultParser, Li as isRetryableError, Mn as Dialect, Nn as QueryExecutionContext, Pn as QueryResult, Si as NotNullConstraintError, ai as FeatureNotSupportedError, bi as CheckConstraintError, f as SQLITE_MIGRATION_CAPABILITY, fi as QueryError, h as DriverResultParser, ii as ConnectionError, l as AnyDriver, ni as TransactionError, p as SqliteMigrationCapability, u as Driver, xi as ForeignKeyError } from "./index-Ci8b13Lm.mjs";
2
2
  export { type AnyDriver, type BatchQuery, CheckConstraintError, ConnectionError, type Dialect, Driver, type DriverResultParser, FeatureNotSupportedError, ForeignKeyError, NotNullConstraintError, QueryError, type QueryExecutionContext, type QueryResult, SQLITE_MIGRATION_CAPABILITY, type SqliteMigrationCapability, TransactionError, UniqueConstraintError, isRetryableError, sqliteResultParser };
@@ -691,6 +691,16 @@ interface DatabaseAdapterCapabilities {
691
691
  * unbounded, so neither.
692
692
  */
693
693
  relationsPerStatement?: number;
694
+ /**
695
+ * Whether the transport's affected-row count of an `UPDATE` or `DELETE`
696
+ * also counts the rows a foreign key's cascade changed: Cloudflare D1's
697
+ * `meta.changes` reports 3 for one post deleted with its two junction rows,
698
+ * where SQLite's own count is 1. The engine then counts the rows such a
699
+ * statement writes by returning one marker per row, where the count is an
700
+ * answer (`updateMany` / `deleteMany`) or a check (a captured mutation).
701
+ * Absent: false.
702
+ */
703
+ countsCascadedChanges?: boolean;
694
704
  }
695
705
  //#endregion
696
706
  //#region src/adapters/adapter-core-types.d.ts
@@ -14015,6 +14025,12 @@ interface SQLiteAdapterOptions {
14015
14025
  * they test (`capabilities.relationsPerStatement`). Absent: unbounded.
14016
14026
  */
14017
14027
  readonly relationsPerStatement?: number;
14028
+ /**
14029
+ * Whether the transport's affected-row count also counts the rows a foreign
14030
+ * key's cascade changed (`capabilities.countsCascadedChanges`): Cloudflare
14031
+ * D1's `meta.changes` does. Defaults to `false`, SQLite's own count.
14032
+ */
14033
+ readonly countsCascadedChanges?: boolean;
14018
14034
  }
14019
14035
  declare function sqliteJsonEquals(left: Sql, right: Sql): Sql;
14020
14036
  declare class SQLiteAdapter implements DatabaseAdapter {
@@ -14024,7 +14040,8 @@ declare class SQLiteAdapter implements DatabaseAdapter {
14024
14040
  deepExpressions,
14025
14041
  sharedRelationBodies,
14026
14042
  compoundSelectTerms,
14027
- relationsPerStatement
14043
+ relationsPerStatement,
14044
+ countsCascadedChanges
14028
14045
  }?: SQLiteAdapterOptions);
14029
14046
  raw: (sqlString: string) => Sql;
14030
14047
  identifiers: {
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $n as AutoGenerate, $r as ValidationErrorSource, $t as ExtensionResultConsumerState, Ai as CacheConfigurationError, B as VariantToOneRelation, Bi as wrapError, Bn as ModelFieldRefs, Br as JsonNull, Ci as UniqueConstraintError, Cr as IsoDateSchema, Ct as s, Di as isNotNullConstraintError, Dr as EnumSchema, Dt as renderSchemaType, Ei as isForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as VibORMError, Ft as VibORMClient, Gi as GeoPolygon, Gn as IndexOptions, Gt as defineExtension, H as BigIntScalar, Hi as GeoArea, Hn as isFieldRef, Hr as JsonNullSentinel, Ht as PlacedControl, I as Links, Ii as VibORMErrorCode, It as VibORMConfig, Jn as Model, Jt as AccumulatedExtensionState, Ki as DecimalDescriptor, Kr as AnyRelation, Kt as StatementContext, L as RelationLinks, Li as isRetryableError, Ln as StringSchema, Lr as AnyJsonNullSentinel, Lt as createClient, M as ClientSchema, Mi as CacheInvalidTTLError, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheOperationNotCacheableError, Nr as BigIntSchema, Nt as ExtensionState, Oi as isUniqueConstraintError, Ot as validateOperationPayload, P as Linked, Pi as PrismaErrorCode, Qn as DecimalSchema, Qr as ValidationError, Qt as ExtensionContributionState, R as ModelShape, Ri as isVibORMError, Rn as AnyFieldRef, Rr as AnyNull, Si as NotNullConstraintError, St as ModelToManyRelation, Ti as isCheckConstraintError, Tr as IsoTimestampSchema, Tt as getOperationPayloadSchema, Ui as GeoBounds, Un as AnyModel, Ur as isJsonNullSentinel, V as Scalar, Vi as DiagnosticDisclosure, Vn as createModelFieldRefs, Vr as JsonNullKind, Vt as NoControls, Wi as GeoPoint, Wn as IndexDefinition, Wt as ClientExtension, Xn as ModelState, Xr as RelationCardinality, Xt as EmptyClientExtensionState, Y as VibSchema, Yn as ModelInternal, Yr as ReferentialAction, Yt as ClientExtensionState, Zn as UpdateState, Zr as RelationSlot, Zt as ExtensionCacheState, _ as ObservationCompletion, _i as isUnsupportedOperationError, _n as UnwrapPendingOperation, _r as InputJsonValue, _t as DateScalar, ai as FeatureNotSupportedError, ar as UpdateState$1, bi as CheckConstraintError, bt as ModelToOneRelation, ci as NestedWriteError, cn as validateSchemaOrThrow, cr as VectorSchema, ct as StringScalar, di as QueryEngineError, dn as SchemaValidationIssue, dr as ObjectSchema, dt as JsonScalar, ei as isValidationError, en as MergeExtensionState, fi as QueryError, fn as Severity, ft as IntScalar, gi as isPendingOperationError, gn as PendingOperation, gt as DateTimeScalar, hi as isNotFoundError, hr as NumberSchema, ht as TimeScalar, ii as ConnectionError, ji as CacheInvalidKeyError, jr as BlobSchema, jt as ExtendedClient, ki as isValueTooLongError, kr as BooleanSchema, kt as ClientTypeState, li as NotFoundError, ln as SchemaValidationError, lt as PointScalar, mi as isClientInitializationError, mr as IntegerSchema, mt as DecimalScalar, ni as TransactionError, nr as InitialScalarState, oi as ForbiddenError, on as RawOperation, ot as NumericScalar, pi as UnsupportedOperationError, pn as ValidationResult, pt as EnumScalar, qi as Decimal, qn as InitialModelState, qr as Getter, qt as StatementHandler, ri as ClientInitializationError, rr as ScalarState, si as NestedWriteAssertionError, sn as validateSchema, st as VectorScalar, ti as InvalidTransactionInputError, tr as GeneratorDefaultBrand, ui as PendingOperationError, un as isSchemaValidationError, ur as PointSchema, ut as NumberScalar, v as ObservationUnit, vi as MigrationError, vn as UnwrapPendingOperations, vr as JsonSchema, vt as BooleanScalar, wi as ValueTooLongError, wr as IsoTimeSchema, wt as getSchemas, xi as ForeignKeyError, xt as ReferencesStage, y as ObserveHandler, yi as isMigrationError, yn as isPendingOperation, yr as JsonValue, yt as BlobScalar, z as VariantToManyRelation, zi as toPrismaErrorCode, zn as FieldRef, zr as DbNull } from "./index-oVv9RLt5.mjs";
1
+ import { $n as AutoGenerate, $r as ValidationErrorSource, $t as ExtensionResultConsumerState, Ai as CacheConfigurationError, B as VariantToOneRelation, Bi as wrapError, Bn as ModelFieldRefs, Br as JsonNull, Ci as UniqueConstraintError, Cr as IsoDateSchema, Ct as s, Di as isNotNullConstraintError, Dr as EnumSchema, Dt as renderSchemaType, Ei as isForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as VibORMError, Ft as VibORMClient, Gi as GeoPolygon, Gn as IndexOptions, Gt as defineExtension, H as BigIntScalar, Hi as GeoArea, Hn as isFieldRef, Hr as JsonNullSentinel, Ht as PlacedControl, I as Links, Ii as VibORMErrorCode, It as VibORMConfig, Jn as Model, Jt as AccumulatedExtensionState, Ki as DecimalDescriptor, Kr as AnyRelation, Kt as StatementContext, L as RelationLinks, Li as isRetryableError, Ln as StringSchema, Lr as AnyJsonNullSentinel, Lt as createClient, M as ClientSchema, Mi as CacheInvalidTTLError, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheOperationNotCacheableError, Nr as BigIntSchema, Nt as ExtensionState, Oi as isUniqueConstraintError, Ot as validateOperationPayload, P as Linked, Pi as PrismaErrorCode, Qn as DecimalSchema, Qr as ValidationError, Qt as ExtensionContributionState, R as ModelShape, Ri as isVibORMError, Rn as AnyFieldRef, Rr as AnyNull, Si as NotNullConstraintError, St as ModelToManyRelation, Ti as isCheckConstraintError, Tr as IsoTimestampSchema, Tt as getOperationPayloadSchema, Ui as GeoBounds, Un as AnyModel, Ur as isJsonNullSentinel, V as Scalar, Vi as DiagnosticDisclosure, Vn as createModelFieldRefs, Vr as JsonNullKind, Vt as NoControls, Wi as GeoPoint, Wn as IndexDefinition, Wt as ClientExtension, Xn as ModelState, Xr as RelationCardinality, Xt as EmptyClientExtensionState, Y as VibSchema, Yn as ModelInternal, Yr as ReferentialAction, Yt as ClientExtensionState, Zn as UpdateState, Zr as RelationSlot, Zt as ExtensionCacheState, _ as ObservationCompletion, _i as isUnsupportedOperationError, _n as UnwrapPendingOperation, _r as InputJsonValue, _t as DateScalar, ai as FeatureNotSupportedError, ar as UpdateState$1, bi as CheckConstraintError, bt as ModelToOneRelation, ci as NestedWriteError, cn as validateSchemaOrThrow, cr as VectorSchema, ct as StringScalar, di as QueryEngineError, dn as SchemaValidationIssue, dr as ObjectSchema, dt as JsonScalar, ei as isValidationError, en as MergeExtensionState, fi as QueryError, fn as Severity, ft as IntScalar, gi as isPendingOperationError, gn as PendingOperation, gt as DateTimeScalar, hi as isNotFoundError, hr as NumberSchema, ht as TimeScalar, ii as ConnectionError, ji as CacheInvalidKeyError, jr as BlobSchema, jt as ExtendedClient, ki as isValueTooLongError, kr as BooleanSchema, kt as ClientTypeState, li as NotFoundError, ln as SchemaValidationError, lt as PointScalar, mi as isClientInitializationError, mr as IntegerSchema, mt as DecimalScalar, ni as TransactionError, nr as InitialScalarState, oi as ForbiddenError, on as RawOperation, ot as NumericScalar, pi as UnsupportedOperationError, pn as ValidationResult, pt as EnumScalar, qi as Decimal, qn as InitialModelState, qr as Getter, qt as StatementHandler, ri as ClientInitializationError, rr as ScalarState, si as NestedWriteAssertionError, sn as validateSchema, st as VectorScalar, ti as InvalidTransactionInputError, tr as GeneratorDefaultBrand, ui as PendingOperationError, un as isSchemaValidationError, ur as PointSchema, ut as NumberScalar, v as ObservationUnit, vi as MigrationError, vn as UnwrapPendingOperations, vr as JsonSchema, vt as BooleanScalar, wi as ValueTooLongError, wr as IsoTimeSchema, wt as getSchemas, xi as ForeignKeyError, xt as ReferencesStage, y as ObserveHandler, yi as isMigrationError, yn as isPendingOperation, yr as JsonValue, yt as BlobScalar, z as VariantToManyRelation, zi as toPrismaErrorCode, zn as FieldRef, zr as DbNull } from "./index-Ci8b13Lm.mjs";
2
2
  import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-Q_twK-wW.mjs";
3
3
  export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, type ClientTypeState, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain-C4EUyLzF.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-D3m1S7Uc.mjs";import{i as c,n as l,r as u,t as d}from"./cache-CIPRF-pz.mjs";import{C as f,D as p,E as m,S as h,T as g,b as _,v,w as y,x as b,y as x}from"./error-mapping-6op318w6.mjs";import{n as S,t as C}from"./migrations-Bn1SatyB.mjs";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,t as R,u as z,v as B}from"./validation-gwZYm3Yn.mjs";import{n as V,t as H}from"./transaction-4dfqals6.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-BcroBusN.mjs";import{F as X}from"./geo-point-codec-pAWYj5ZZ.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-BvHwL73I.mjs";import{C as re,S as ie}from"./scalar-Dyns7kc7.mjs";import{a as ae,i as oe}from"./validator-yrGnrsAo.mjs";import{n as se}from"./builder-BxCr9ANq.mjs";import{d as ce,m as le}from"./result-shape-ic2j3Tze.mjs";import{t as ue}from"./client-DUulrWw5.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-LpRNeSG2.mjs";import{t as he}from"./schema-CUm_yh6L.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,l as CacheInvalidKeyError,u as CacheInvalidTTLError,c as CacheOperationNotCacheableError,v as CheckConstraintError,L as ClientInitializationError,j as ConnectionError,W as DbNull,X as Decimal,T as FeatureNotSupportedError,F as ForbiddenError,x as ForeignKeyError,H as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,E as NestedWriteAssertionError,M as NestedWriteError,z as NotFoundError,_ as NotNullConstraintError,ce as PendingOperation,D as PendingOperationError,O as QueryEngineError,I as QueryError,ie as SchemaValidationError,ne as Sql,V as TransactionError,b as UniqueConstraintError,N as UnsupportedOperationError,R as ValidationError,h as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,f as isCheckConstraintError,A as isClientInitializationError,K as isFieldRef,y as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,k as isNotFoundError,g as isNotNullConstraintError,le as isPendingOperation,w as isPendingOperationError,o as isRetryableError,re as isSchemaValidationError,te as isSql,m as isUniqueConstraintError,B as isUnsupportedOperationError,P as isValidationError,p as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain-C4EUyLzF.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-D3m1S7Uc.mjs";import{i as c,n as l,r as u,t as d}from"./cache-CIPRF-pz.mjs";import{C as f,D as p,E as m,S as h,T as g,b as _,v,w as y,x as b,y as x}from"./error-mapping-6op318w6.mjs";import{n as S,t as C}from"./migrations-Bn1SatyB.mjs";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,t as R,u as z,v as B}from"./validation-gwZYm3Yn.mjs";import{n as V,t as H}from"./transaction-4dfqals6.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-BcroBusN.mjs";import{F as X}from"./geo-point-codec-pAWYj5ZZ.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-BvHwL73I.mjs";import{C as re,S as ie}from"./scalar-Dyns7kc7.mjs";import{a as ae,i as oe}from"./validator-yrGnrsAo.mjs";import{n as se}from"./builder-BxCr9ANq.mjs";import{d as ce,m as le}from"./result-shape-ic2j3Tze.mjs";import{t as ue}from"./client-DACEO6tS.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-LpRNeSG2.mjs";import{t as he}from"./schema-CUm_yh6L.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,l as CacheInvalidKeyError,u as CacheInvalidTTLError,c as CacheOperationNotCacheableError,v as CheckConstraintError,L as ClientInitializationError,j as ConnectionError,W as DbNull,X as Decimal,T as FeatureNotSupportedError,F as ForbiddenError,x as ForeignKeyError,H as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,E as NestedWriteAssertionError,M as NestedWriteError,z as NotFoundError,_ as NotNullConstraintError,ce as PendingOperation,D as PendingOperationError,O as QueryEngineError,I as QueryError,ie as SchemaValidationError,ne as Sql,V as TransactionError,b as UniqueConstraintError,N as UnsupportedOperationError,R as ValidationError,h as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,f as isCheckConstraintError,A as isClientInitializationError,K as isFieldRef,y as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,k as isNotFoundError,g as isNotNullConstraintError,le as isPendingOperation,w as isPendingOperationError,o as isRetryableError,re as isSchemaValidationError,te as isSql,m as isUniqueConstraintError,B as isUnsupportedOperationError,P as isValidationError,p as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,4 +1,4 @@
1
- import { Fi as VibORMError, Vi as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-oVv9RLt5.mjs";
1
+ import { Fi as VibORMError, Vi as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-Ci8b13Lm.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain-C4EUyLzF.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-D3m1S7Uc.mjs";import{c as g,s as _,u as ee}from"./observation-Co72iCd1.mjs";import{t as te}from"./version-B9azgPiR.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain-C4EUyLzF.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-D3m1S7Uc.mjs";import{c as g,s as _,u as ee}from"./observation-Co72iCd1.mjs";import{t as te}from"./version-DLtcW9kn.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
2
2
  //# sourceMappingURL=instrumentation.mjs.map
package/dist/libsql.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import { Client, Config, Transaction } from "@libsql/client";
3
3
 
4
4
  //#region src/drivers/libsql/index.d.ts
package/dist/libsql.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-BF7gr4_b.mjs";import{n}from"./base-D3m1S7Uc.mjs";import{l as r,p as i}from"./error-mapping-6op318w6.mjs";import{i as a}from"./validation-gwZYm3Yn.mjs";import{c as o}from"./execution-context-asSCmyas.mjs";import{n as s}from"./client-DUulrWw5.mjs";import{c,i as l,r as u,t as d}from"./driver-DseQwbsu.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-C5_KQPZn.mjs";import{t as g}from"./sqlite-adapter-B3dRr5fl.mjs";const _=new WeakSet,v={client:!0,databaseUrl:!0,dataDir:!0,authToken:!0,options:!0};function convertValuesForLibSQL(e){return e.map(e=>{let t=h(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(p(t))return t instanceof ArrayBuffer?t:f(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,n)=>{let r=t(e.rowsAffected,{provider:`libsql`,operation:n});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends d{adapter=new g;maxBindParametersPerStatement=32766;result=m;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient)this.serializeTransactions=this.suppliedClient.protocol===`file`;else{let e=this.getDatabaseUrl();this.serializeTransactions=e===`:memory:`||e.startsWith(`file:`)}this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||_.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,n,a){if(`commit`in e)throw r(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),a?.maxWaitMs,{driverName:this.driverName,form:`callback`});return i({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:o(n),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(_.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&_.has(e))throw new a(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:n.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){c(e,`libsql`,v);let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-BF7gr4_b.mjs";import{n}from"./base-D3m1S7Uc.mjs";import{l as r,p as i}from"./error-mapping-6op318w6.mjs";import{i as a}from"./validation-gwZYm3Yn.mjs";import{c as o}from"./execution-context-asSCmyas.mjs";import{n as s}from"./client-DACEO6tS.mjs";import{c,i as l,r as u,t as d}from"./driver-DseQwbsu.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-C5_KQPZn.mjs";import{t as g}from"./sqlite-adapter-CLWY4B8w.mjs";const _=new WeakSet,v={client:!0,databaseUrl:!0,dataDir:!0,authToken:!0,options:!0};function convertValuesForLibSQL(e){return e.map(e=>{let t=h(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(p(t))return t instanceof ArrayBuffer?t:f(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,n)=>{let r=t(e.rowsAffected,{provider:`libsql`,operation:n});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends d{adapter=new g;maxBindParametersPerStatement=32766;result=m;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient)this.serializeTransactions=this.suppliedClient.protocol===`file`;else{let e=this.getDatabaseUrl();this.serializeTransactions=e===`:memory:`||e.startsWith(`file:`)}this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||_.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,n,a){if(`commit`in e)throw r(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),a?.maxWaitMs,{driverName:this.driverName,form:`callback`});return i({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:o(n),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(_.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&_.has(e))throw new a(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:n.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){c(e,`libsql`,v);let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
2
2
  //# sourceMappingURL=libsql.mjs.map
@@ -1,6 +1,6 @@
1
- import { vi as MigrationError, yi as isMigrationError } from "../index-oVv9RLt5.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-C3KX6S85.mjs";
1
+ import { vi as MigrationError, yi as isMigrationError } from "../index-Ci8b13Lm.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CUcPdJwD.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-Dw0FR78e.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C56-FLkl.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-3FqgR4eS.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-H7fJwgPR.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-D-XiaClb.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { vi as MigrationError, yi as isMigrationError } from "../index-oVv9RLt5.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-C3KX6S85.mjs";
1
+ import { vi as MigrationError, yi as isMigrationError } from "../index-Ci8b13Lm.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CUcPdJwD.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-Dw0FR78e.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C56-FLkl.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-3FqgR4eS.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-H7fJwgPR.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-D-XiaClb.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { vi as MigrationError, yi as isMigrationError } from "../index-oVv9RLt5.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-C3KX6S85.mjs";
1
+ import { vi as MigrationError, yi as isMigrationError } from "../index-Ci8b13Lm.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CUcPdJwD.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-Dw0FR78e.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C56-FLkl.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-3FqgR4eS.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-H7fJwgPR.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-D-XiaClb.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { s as MigrationLimits, t as MigrationClient } from "../planner-C3KX6S85.mjs";
1
+ import { s as MigrationLimits, t as MigrationClient } from "../planner-CUcPdJwD.mjs";
2
2
  import { i as Sha256, n as MigrationStorageWriter } from "../contract-Dw0FR78e.mjs";
3
- import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-3FqgR4eS.mjs";
3
+ import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-D-XiaClb.mjs";
4
4
 
5
5
  //#region src/migrations/tenant.d.ts
6
6
 
@@ -1,6 +1,6 @@
1
- import { vi as MigrationError, yi as isMigrationError } from "./index-oVv9RLt5.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-C3KX6S85.mjs";
1
+ import { vi as MigrationError, yi as isMigrationError } from "./index-Ci8b13Lm.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-CUcPdJwD.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "./contract-Dw0FR78e.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-C56-FLkl.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-3FqgR4eS.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-H7fJwgPR.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-D-XiaClb.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
package/dist/mysql2.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
3
3
 
4
4
  //#region src/drivers/mysql2/index.d.ts
package/dist/mysql2.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-BF7gr4_b.mjs";import{i}from"./base-D3m1S7Uc.mjs";import{l as a,p as o}from"./error-mapping-6op318w6.mjs";import{p as s,r as c}from"./validation-gwZYm3Yn.mjs";import{n as l}from"./transaction-4dfqals6.mjs";import{c as u}from"./execution-context-asSCmyas.mjs";import{n as d}from"./client-DUulrWw5.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./mysql-adapter-B1U35CJn.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new c(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new s(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new s(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw i(e)?e:new c(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new c(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new c(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new c(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw a(this.driverName);let i=e,s=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),c=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw c=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await s.query(f(d)),await s.beginTransaction()}),callback:()=>t(s),commit:()=>runOrDestroy(()=>s.commit()),rollback:()=>runOrDestroy(()=>s.rollback()),phases:u(n),close:()=>{try{if(c){s.destroy();return}s.release()}catch(e){throw super.transactionCleanupFailed(new l(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw a(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-BF7gr4_b.mjs";import{i}from"./base-D3m1S7Uc.mjs";import{l as a,p as o}from"./error-mapping-6op318w6.mjs";import{p as s,r as c}from"./validation-gwZYm3Yn.mjs";import{n as l}from"./transaction-4dfqals6.mjs";import{c as u}from"./execution-context-asSCmyas.mjs";import{n as d}from"./client-DACEO6tS.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./mysql-adapter-B1U35CJn.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new c(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new s(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new s(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw i(e)?e:new c(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new c(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new c(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new c(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw a(this.driverName);let i=e,s=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),c=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw c=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await s.query(f(d)),await s.beginTransaction()}),callback:()=>t(s),commit:()=>runOrDestroy(()=>s.commit()),rollback:()=>runOrDestroy(()=>s.rollback()),phases:u(n),close:()=>{try{if(c){s.destroy();return}s.release()}catch(e){throw super.transactionCleanupFailed(new l(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw a(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
2
2
  //# sourceMappingURL=mysql2.mjs.map
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
1
+ import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import { NeonQueryFunction } from "@neondatabase/serverless";
3
3
 
4
4
  //#region src/drivers/neon-http/index.d.ts